Segment Routing refactor with flow objectives

Change-Id: I0b87f89bb8b18522b9d38bdf5e96f55485b6f1e3
diff --git a/src/main/java/org/onosproject/segmentrouting/DefaultRoutingHandler.java b/src/main/java/org/onosproject/segmentrouting/DefaultRoutingHandler.java
index 3a2d243..c5bd6ba 100644
--- a/src/main/java/org/onosproject/segmentrouting/DefaultRoutingHandler.java
+++ b/src/main/java/org/onosproject/segmentrouting/DefaultRoutingHandler.java
@@ -24,7 +24,6 @@
 import org.onosproject.net.DeviceId;
 import org.onosproject.net.Link;
 import org.onosproject.net.MastershipRole;
-import org.onosproject.net.flow.FlowRule;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -38,7 +37,8 @@
 
 public class DefaultRoutingHandler {
 
-    private static Logger log = LoggerFactory.getLogger(DefaultRoutingHandler.class);
+    private static Logger log = LoggerFactory
+            .getLogger(DefaultRoutingHandler.class);
 
     private SegmentRoutingManager srManager;
     private RoutingRulePopulator rulePopulator;
@@ -56,7 +56,8 @@
         // population process started.
         STARTED,
 
-        // population process was aborted due to errors, mostly for groups not found.
+        // population process was aborted due to errors, mostly for groups not
+        // found.
         ABORTED,
 
         // population process was finished successfully.
@@ -89,8 +90,7 @@
         log.info("Starts to populate routing rules");
 
         for (Device sw : srManager.deviceService.getDevices()) {
-            if (srManager.mastershipService.
-                    getLocalRole(sw.id()) != MastershipRole.MASTER) {
+            if (srManager.mastershipService.getLocalRole(sw.id()) != MastershipRole.MASTER) {
                 continue;
             }
 
@@ -323,11 +323,11 @@
     private boolean populateEcmpRoutingRules(DeviceId destSw,
                                              ECMPShortestPathGraph ecmpSPG) {
 
-        HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> switchVia =
-                ecmpSPG.getAllLearnedSwitchesAndVia();
+        HashMap<Integer, HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>>> switchVia = ecmpSPG
+                .getAllLearnedSwitchesAndVia();
         for (Integer itrIdx : switchVia.keySet()) {
-            HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap =
-                    switchVia.get(itrIdx);
+            HashMap<DeviceId, ArrayList<ArrayList<DeviceId>>> swViaMap = switchVia
+                    .get(itrIdx);
             for (DeviceId targetSw : swViaMap.keySet()) {
                 Set<DeviceId> nextHops = new HashSet<>();
 
@@ -347,15 +347,17 @@
         return true;
     }
 
-    private boolean populateEcmpRoutingRulePartial(DeviceId targetSw, DeviceId destSw,
-                                Set<DeviceId> nextHops) {
+    private boolean populateEcmpRoutingRulePartial(DeviceId targetSw,
+                                                   DeviceId destSw,
+                                                   Set<DeviceId> nextHops) {
         boolean result;
 
         if (nextHops.isEmpty()) {
             nextHops.add(destSw);
         }
 
-        // If both target switch and dest switch are edge routers, then set IP rule
+        // If both target switch and dest switch are edge routers, then set IP
+        // rule
         // for both subnet and router IP.
         if (config.isEdgeDevice(targetSw) && config.isEdgeDevice(destSw)) {
             List<Ip4Prefix> subnets = config.getSubnets(destSw);
@@ -374,7 +376,7 @@
                 return false;
             }
 
-        // If the target switch is an edge router, then set IP rules for the router IP.
+        // TODO: If the target switch is an edge router, then set IP rules for the router IP.
         } else if (config.isEdgeDevice(targetSw)) {
             Ip4Address routerIp = config.getRouterIp(destSw);
             IpPrefix routerIpPrefix = IpPrefix.valueOf(routerIp, IpPrefix.MAX_INET_MASK_LENGTH);
@@ -383,7 +385,7 @@
                 return false;
             }
 
-        // If the target switch is an transit router, then set MPLS rules only.
+        // TODO: If the target switch is an transit router, then set MPLS rules only.
         } else if (!config.isEdgeDevice(targetSw)) {
             result = rulePopulator.populateMplsRule(targetSw, destSw, nextHops);
             if (!result) {
@@ -395,38 +397,25 @@
     }
 
     /**
-     * Populates table miss entries for all tables, and pipeline rules for
-     * VLAN and TACM tables.
+     * Populates table miss entries for all tables, and pipeline rules for VLAN
+     * and TACM tables.
      *
      * @param deviceId Switch ID to set the rules
      */
     public void populateTtpRules(DeviceId deviceId) {
-
-        rulePopulator.populateTableMissEntry(deviceId, FlowRule.Type.VLAN,
-                true, false, false, FlowRule.Type.DEFAULT);
-        rulePopulator.populateTableMissEntry(deviceId, FlowRule.Type.ETHER,
-                true, false, false, FlowRule.Type.DEFAULT);
-        rulePopulator.populateTableMissEntry(deviceId, FlowRule.Type.IP,
-                false, true, true, FlowRule.Type.ACL);
-        rulePopulator.populateTableMissEntry(deviceId, FlowRule.Type.MPLS,
-                false, true, true, FlowRule.Type.ACL);
-        rulePopulator.populateTableMissEntry(deviceId, FlowRule.Type.ACL,
-                false, false, false, FlowRule.Type.DEFAULT);
-
         rulePopulator.populateTableVlan(deviceId);
         rulePopulator.populateTableTMac(deviceId);
     }
 
     /**
-     * Start the flow rule population process if it was never started.
-     * The process finishes successfully when all flow rules are set and
-     * stops with ABORTED status when any groups required for flows is not
-     * set yet.
+     * Start the flow rule population process if it was never started. The
+     * process finishes successfully when all flow rules are set and stops with
+     * ABORTED status when any groups required for flows is not set yet.
      */
     public void startPopulationProcess() {
         synchronized (populationStatus) {
-            if (populationStatus == Status.IDLE ||
-                    populationStatus == Status.SUCCEEDED) {
+            if (populationStatus == Status.IDLE
+                    || populationStatus == Status.SUCCEEDED) {
                 populationStatus = Status.STARTED;
                 populateAllRoutingRules();
             }
@@ -441,7 +430,8 @@
         synchronized (populationStatus) {
             if (populationStatus == Status.ABORTED) {
                 populationStatus = Status.STARTED;
-                // TODO: we need to restart from the point aborted instead of restarting.
+                // TODO: we need to restart from the point aborted instead of
+                // restarting.
                 populateAllRoutingRules();
             }
         }
diff --git a/src/main/java/org/onosproject/segmentrouting/NetworkConfigHandler.java b/src/main/java/org/onosproject/segmentrouting/NetworkConfigHandler.java
new file mode 100644
index 0000000..d346817
--- /dev/null
+++ b/src/main/java/org/onosproject/segmentrouting/NetworkConfigHandler.java
@@ -0,0 +1,157 @@
+/*
+ * Copyright 2015 Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.segmentrouting;
+
+import com.google.common.collect.Lists;
+
+import org.onlab.packet.Ip4Address;
+import org.onlab.packet.Ip4Prefix;
+import org.onlab.packet.IpPrefix;
+import org.onlab.packet.MacAddress;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.Link;
+import org.onosproject.net.PortNumber;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+import java.util.Set;
+
+/**
+ * This class is temporary class and used only for test.
+ * It will be replaced with "real" Network Config Manager.
+ *
+ * TODO: Knock off this wrapper and directly use DeviceConfiguration class
+ */
+
+public class NetworkConfigHandler {
+
+    private static Logger log = LoggerFactory.getLogger(NetworkConfigHandler.class);
+    private SegmentRoutingManager srManager;
+    private DeviceConfiguration deviceConfig;
+
+    public NetworkConfigHandler(SegmentRoutingManager srManager,
+                                DeviceConfiguration deviceConfig) {
+        this.srManager = srManager;
+        this.deviceConfig = deviceConfig;
+    }
+
+    public List<Ip4Address> getGatewayIpAddress(DeviceId deviceId) {
+        return this.deviceConfig.getSubnetGatewayIps(deviceId);
+    }
+
+    public IpPrefix getRouterIpAddress(DeviceId deviceId) {
+        return IpPrefix.valueOf(deviceConfig.getRouterIp(deviceId), 32);
+    }
+
+    public MacAddress getRouterMacAddress(DeviceId deviceId) {
+        return deviceConfig.getDeviceMac(deviceId);
+    }
+
+    public boolean inSameSubnet(DeviceId deviceId, Ip4Address destIp) {
+
+        List<Ip4Prefix> subnets = getSubnetInfo(deviceId);
+        if (subnets == null) {
+            return false;
+        }
+
+        return subnets.stream()
+               .anyMatch((subnet) -> subnet.contains(destIp));
+    }
+
+    public boolean inSameSubnet(Ip4Address address, int sid) {
+        DeviceId deviceId = deviceConfig.getDeviceId(sid);
+        if (deviceId == null) {
+            log.warn("Cannot find a device for SID {}", sid);
+            return false;
+        }
+
+        return inSameSubnet(deviceId, address);
+    }
+
+    public List<Ip4Prefix> getSubnetInfo(DeviceId deviceId) {
+        return deviceConfig.getSubnets(deviceId);
+    }
+
+    public int getMplsId(DeviceId deviceId) {
+        return deviceConfig.getSegmentId(deviceId);
+    }
+
+    public int getMplsId(MacAddress routerMac) {
+        return deviceConfig.getSegmentId(routerMac);
+    }
+
+    public int getMplsId(Ip4Address routerIpAddress) {
+        return deviceConfig.getSegmentId(routerIpAddress);
+    }
+
+    public boolean isEcmpNotSupportedInTransit(DeviceId deviceId) {
+        //TODO: temporarily changing to true to test with Dell
+        return true;
+    }
+
+    public boolean isTransitRouter(DeviceId deviceId) {
+        return !(deviceConfig.isEdgeDevice(deviceId));
+    }
+
+
+    public boolean isEdgeRouter(DeviceId deviceId) {
+        return deviceConfig.isEdgeDevice(deviceId);
+    }
+
+    private List<PortNumber> getPortsToNeighbors(DeviceId deviceId, List<DeviceId> fwdSws) {
+
+        List<PortNumber> portNumbers = Lists.newArrayList();
+
+        Set<Link> links = srManager.linkService.getDeviceEgressLinks(deviceId);
+        for (Link link: links) {
+            for (DeviceId swId: fwdSws) {
+                if (link.dst().deviceId().equals(swId)) {
+                    portNumbers.add(link.src().port());
+                    break;
+                }
+            }
+        }
+
+        return portNumbers;
+    }
+
+    public List<PortNumber> getPortsToDevice(DeviceId deviceId) {
+        List<PortNumber> portNumbers = Lists.newArrayList();
+
+        Set<Link> links = srManager.linkService.getDeviceEgressLinks(deviceId);
+        for (Link link: links) {
+            if (link.dst().deviceId().equals(deviceId)) {
+                portNumbers.add(link.src().port());
+            }
+        }
+
+        return portNumbers;
+    }
+
+
+    public Ip4Address getDestinationRouterAddress(Ip4Address destIpAddress) {
+        return deviceConfig.getRouterIpAddressForASubnetHost(destIpAddress);
+    }
+
+    public DeviceId getDeviceId(Ip4Address ip4Address) {
+        return deviceConfig.getDeviceId(ip4Address);
+    }
+
+    public MacAddress getRouterMac(Ip4Address targetAddress) {
+        return deviceConfig.getRouterMacForAGatewayIp(targetAddress);
+    }
+}
diff --git a/src/main/java/org/onosproject/segmentrouting/RoutingRulePopulator.java b/src/main/java/org/onosproject/segmentrouting/RoutingRulePopulator.java
index c4db26c..2d2102b 100644
--- a/src/main/java/org/onosproject/segmentrouting/RoutingRulePopulator.java
+++ b/src/main/java/org/onosproject/segmentrouting/RoutingRulePopulator.java
@@ -21,23 +21,25 @@
 import org.onlab.packet.IpPrefix;
 import org.onlab.packet.MacAddress;
 import org.onlab.packet.MplsLabel;
+import org.onlab.packet.VlanId;
 import org.onosproject.segmentrouting.grouphandler.NeighborSet;
 import org.onosproject.net.DeviceId;
 import org.onosproject.net.Link;
 import org.onosproject.net.PortNumber;
-import org.onosproject.net.flow.DefaultFlowRule;
 import org.onosproject.net.flow.DefaultTrafficSelector;
 import org.onosproject.net.flow.DefaultTrafficTreatment;
-import org.onosproject.net.flow.FlowRule;
 import org.onosproject.net.flow.TrafficSelector;
 import org.onosproject.net.flow.TrafficTreatment;
-import org.onosproject.net.group.DefaultGroupKey;
-import org.onosproject.net.group.Group;
+import org.onosproject.net.flow.criteria.Criteria;
+import org.onosproject.net.flowobjective.DefaultFilteringObjective;
+import org.onosproject.net.flowobjective.DefaultForwardingObjective;
+import org.onosproject.net.flowobjective.FilteringObjective;
+import org.onosproject.net.flowobjective.ForwardingObjective;
+import org.onosproject.net.flowobjective.ForwardingObjective.Builder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import java.util.ArrayList;
-import java.util.Collection;
 import java.util.List;
 import java.util.Set;
 import java.util.concurrent.atomic.AtomicLong;
@@ -46,7 +48,8 @@
 
 public class RoutingRulePopulator {
 
-    private static final Logger log = LoggerFactory.getLogger(RoutingRulePopulator.class);
+    private static final Logger log = LoggerFactory
+            .getLogger(RoutingRulePopulator.class);
 
     private AtomicLong rulePopulationCounter;
     private SegmentRoutingManager srManager;
@@ -77,7 +80,8 @@
     }
 
     /**
-     * Populates IP flow rules for specific hosts directly connected to the switch.
+     * Populates IP flow rules for specific hosts directly connected to the
+     * switch.
      *
      * @param deviceId switch ID to set the rules
      * @param hostIp host IP address
@@ -99,12 +103,15 @@
         TrafficTreatment treatment = tbuilder.build();
         TrafficSelector selector = sbuilder.build();
 
-        FlowRule f = new DefaultFlowRule(deviceId, selector, treatment, 100,
-                srManager.appId, 600, false, FlowRule.Type.IP);
+        ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
+                .builder().fromApp(srManager.appId).makePermanent()
+                .withSelector(selector).withTreatment(treatment)
+                .withPriority(100).withFlag(ForwardingObjective.Flag.SPECIFIC);
 
-        srManager.flowRuleService.applyFlowRules(f);
+        log.debug("Installing IPv4 forwarding objective "
+                + "for host {} in switch {}", hostIp, deviceId);
+        srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add());
         rulePopulationCounter.incrementAndGet();
-        log.debug("Flow rule {} is set to switch {}", f, deviceId);
     }
 
     /**
@@ -116,11 +123,12 @@
      * @param nextHops next hop switch ID list
      * @return true if all rules are set successfully, false otherwise
      */
-    public boolean populateIpRuleForSubnet(DeviceId deviceId, List<Ip4Prefix> subnets,
-                                           DeviceId destSw, Set<DeviceId> nextHops) {
+    public boolean populateIpRuleForSubnet(DeviceId deviceId,
+                                           List<Ip4Prefix> subnets,
+                                           DeviceId destSw,
+                                           Set<DeviceId> nextHops) {
 
-        //List<IpPrefix> subnets = extractSubnet(subnetInfo);
-        for (IpPrefix subnet: subnets) {
+        for (IpPrefix subnet : subnets) {
             if (!populateIpRuleForRouter(deviceId, subnet, destSw, nextHops)) {
                 return false;
             }
@@ -138,8 +146,9 @@
      * @param nextHops next hop switch ID list
      * @return true if all rules are set successfully, false otherwise
      */
-    public boolean populateIpRuleForRouter(DeviceId deviceId, IpPrefix ipPrefix,
-                                           DeviceId destSw, Set<DeviceId> nextHops) {
+    public boolean populateIpRuleForRouter(DeviceId deviceId,
+                                           IpPrefix ipPrefix, DeviceId destSw,
+                                           Set<DeviceId> nextHops) {
 
         TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
         TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
@@ -149,7 +158,8 @@
 
         NeighborSet ns = null;
 
-        //If the next hop is the same as the final destination, then MPLS label is not set.
+        // If the next hop is the same as the final destination, then MPLS label
+        // is not set.
         if (nextHops.size() == 1 && nextHops.toArray()[0].equals(destSw)) {
             tbuilder.decNwTtl();
             ns = new NeighborSet(nextHops);
@@ -158,34 +168,28 @@
             ns = new NeighborSet(nextHops, config.getSegmentId(destSw));
         }
 
-        DefaultGroupKey groupKey = (DefaultGroupKey) srManager.getGroupKey(ns);
-        if (groupKey == null) {
-            log.warn("Group key is not found for ns {}", ns);
-            return false;
-        }
-        Group group = srManager.groupService.getGroup(deviceId, groupKey);
-        if (group != null) {
-            tbuilder.group(group.id());
-        } else {
-            log.warn("No group found for NeighborSet {} from {} to {}",
-                    ns, deviceId, destSw);
-            return false;
-        }
-
         TrafficTreatment treatment = tbuilder.build();
         TrafficSelector selector = sbuilder.build();
 
-        FlowRule f = new DefaultFlowRule(deviceId, selector, treatment, 100,
-                srManager.appId, 600, false, FlowRule.Type.IP);
-
-        srManager.flowRuleService.applyFlowRules(f);
+        ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
+                .builder()
+                .fromApp(srManager.appId)
+                .makePermanent()
+                .nextStep(srManager.getNextObjectiveId(deviceId, ns))
+                .withTreatment(treatment)
+                .withSelector(selector)
+                .withPriority(100)
+                .withFlag(ForwardingObjective.Flag.SPECIFIC);
+        log.debug("Installing IPv4 forwarding objective "
+                + "for router IP/subnet {} in switch {}",
+                ipPrefix,
+                deviceId);
+        srManager.flowObjectiveService.forward(deviceId, fwdBuilder.add());
         rulePopulationCounter.incrementAndGet();
-        log.debug("IP flow rule {} is set to switch {}", f, deviceId);
 
         return true;
     }
 
-
     /**
      * Populates MPLS flow rules to all transit routers.
      *
@@ -194,35 +198,53 @@
      * @param nextHops next hops switch ID list
      * @return true if all rules are set successfully, false otherwise
      */
-    public boolean populateMplsRule(DeviceId deviceId, DeviceId destSwId, Set<DeviceId> nextHops) {
+    public boolean populateMplsRule(DeviceId deviceId, DeviceId destSwId,
+                                    Set<DeviceId> nextHops) {
 
         TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
-        Collection<TrafficTreatment> treatments = new ArrayList<>();
+        List<ForwardingObjective.Builder> fwdObjBuilders = new ArrayList<ForwardingObjective.Builder>();
 
         // TODO Handle the case of Bos == false
         sbuilder.matchMplsLabel(MplsLabel.mplsLabel(config.getSegmentId(destSwId)));
         sbuilder.matchEthType(Ethernet.MPLS_UNICAST);
 
-        //If the next hop is the destination router, do PHP
+        // If the next hop is the destination router, do PHP
         if (nextHops.size() == 1 && destSwId.equals(nextHops.toArray()[0])) {
-            TrafficTreatment treatmentBos =
-                    getMplsTreatment(deviceId, destSwId, nextHops, true, true);
-            TrafficTreatment treatment =
-                    getMplsTreatment(deviceId, destSwId, nextHops, true, false);
-            if (treatmentBos != null) {
-                treatments.add(treatmentBos);
+            ForwardingObjective.Builder fwdObjBosBuilder =
+                    getMplsForwardingObjective(deviceId,
+                                               destSwId,
+                                               nextHops,
+                                               true,
+                                               true);
+            // TODO: Check with Sangho on why we need this
+            ForwardingObjective.Builder fwdObjNoBosBuilder =
+                    getMplsForwardingObjective(deviceId,
+                                               destSwId,
+                                               nextHops,
+                                               true,
+                                               false);
+            if (fwdObjBosBuilder != null) {
+                fwdObjBuilders.add(fwdObjBosBuilder);
             } else {
                 log.warn("Failed to set MPLS rules.");
                 return false;
             }
         } else {
-            TrafficTreatment treatmentBos =
-                    getMplsTreatment(deviceId, destSwId, nextHops, false, true);
-            TrafficTreatment treatment =
-                    getMplsTreatment(deviceId, destSwId, nextHops, false, false);
-
-            if (treatmentBos != null) {
-                treatments.add(treatmentBos);
+            ForwardingObjective.Builder fwdObjBosBuilder =
+                    getMplsForwardingObjective(deviceId,
+                                               destSwId,
+                                               nextHops,
+                                               false,
+                                               true);
+            // TODO: Check with Sangho on why we need this
+            ForwardingObjective.Builder fwdObjNoBosBuilder =
+                    getMplsForwardingObjective(deviceId,
+                                               destSwId,
+                                               nextHops,
+                                               false,
+                                               false);
+            if (fwdObjBosBuilder != null) {
+                fwdObjBuilders.add(fwdObjBosBuilder);
             } else {
                 log.warn("Failed to set MPLS rules.");
                 return false;
@@ -230,34 +252,42 @@
         }
 
         TrafficSelector selector = sbuilder.build();
-        for (TrafficTreatment treatment: treatments) {
-            FlowRule f = new DefaultFlowRule(deviceId, selector, treatment, 100,
-                    srManager.appId, 600, false, FlowRule.Type.MPLS);
-            srManager.flowRuleService.applyFlowRules(f);
+        for (ForwardingObjective.Builder fwdObjBuilder : fwdObjBuilders) {
+            ((Builder) ((Builder) fwdObjBuilder.fromApp(srManager.appId)
+                    .makePermanent()).withSelector(selector)
+                    .withPriority(100))
+                    .withFlag(ForwardingObjective.Flag.SPECIFIC);
+            log.debug("Installing MPLS forwarding objective in switch {}",
+                      deviceId);
+            srManager.flowObjectiveService.forward(deviceId,
+                                                   fwdObjBuilder.add());
             rulePopulationCounter.incrementAndGet();
-            log.debug("MPLS rule {} is set to {}", f, deviceId);
         }
 
         return true;
     }
 
+    private ForwardingObjective.Builder getMplsForwardingObjective(DeviceId deviceId,
+                                                                   DeviceId destSw,
+                                                                   Set<DeviceId> nextHops,
+                                                                   boolean phpRequired,
+                                                                   boolean isBos) {
 
-    private TrafficTreatment getMplsTreatment(DeviceId deviceId, DeviceId destSw,
-                                             Set<DeviceId> nextHops,
-                                             boolean phpRequired, boolean isBos) {
+        ForwardingObjective.Builder fwdBuilder = DefaultForwardingObjective
+                .builder().withFlag(ForwardingObjective.Flag.SPECIFIC);
 
         TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
 
         if (phpRequired) {
+            log.debug("getMplsForwardingObjective: php required");
             tbuilder.copyTtlIn();
             if (isBos) {
-                tbuilder.popMpls(Ethernet.TYPE_IPV4)
-                        .decNwTtl();
+                tbuilder.popMpls(Ethernet.TYPE_IPV4).decNwTtl();
             } else {
-                tbuilder.popMpls(Ethernet.MPLS_UNICAST)
-                .decMplsTtl();
+                tbuilder.popMpls(Ethernet.MPLS_UNICAST).decMplsTtl();
             }
         } else {
+            log.debug("getMplsForwardingObjective: php not required");
             tbuilder.decMplsTtl();
         }
 
@@ -271,24 +301,14 @@
             tbuilder.setEthSrc(config.getDeviceMac(deviceId))
                     .setEthDst(config.getDeviceMac(nextHop))
                     .setOutput(link.src().port());
+            fwdBuilder.withTreatment(tbuilder.build());
         } else {
             NeighborSet ns = new NeighborSet(nextHops);
-            DefaultGroupKey groupKey = (DefaultGroupKey) srManager.getGroupKey(ns);
-            if (groupKey == null) {
-                log.warn("Group key is not found for ns {}", ns);
-                return null;
-            }
-            Group group = srManager.groupService.getGroup(deviceId, groupKey);
-            if (group != null) {
-                tbuilder.group(group.id());
-            } else {
-                log.warn("No group found for ns {} key {} in {}", ns,
-                        srManager.getGroupKey(ns), deviceId);
-                return null;
-            }
+            fwdBuilder.nextStep(srManager
+                    .getNextObjectiveId(deviceId, ns));
         }
 
-        return tbuilder.build();
+        return fwdBuilder;
     }
 
     private boolean isECMPSupportedInTransitRouter() {
@@ -298,109 +318,41 @@
     }
 
     /**
-     * Populates VLAN flows rules.
-     * All packets are forwarded to TMAC table.
+     * Populates VLAN flows rules. All packets are forwarded to TMAC table.
      *
      * @param deviceId switch ID to set the rules
      */
     public void populateTableVlan(DeviceId deviceId) {
-        TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
-        TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
-
-        tbuilder.transition(FlowRule.Type.ETHER);
-
-        TrafficTreatment treatment = tbuilder.build();
-        TrafficSelector selector = sbuilder.build();
-
-        FlowRule f = new DefaultFlowRule(deviceId, selector, treatment, 100,
-                srManager.appId, 600, false, FlowRule.Type.VLAN);
-
-        srManager.flowRuleService.applyFlowRules(f);
-
-        log.debug("Vlan flow rule {} is set to switch {}", f, deviceId);
+        FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
+        fob.withKey(Criteria.matchInPort(PortNumber.ALL))
+                .addCondition(Criteria.matchVlanId(VlanId.NONE));
+        fob.permit().fromApp(srManager.appId);
+        log.debug("populateTableVlan: Installing filtering objective for untagged packets");
+        srManager.flowObjectiveService.filter(deviceId, fob.add());
     }
 
     /**
-     * Populates TMAC table rules.
-     * IP packets are forwarded to IP table.
-     * MPLS packets are forwarded to MPLS table.
+     * Populates TMAC table rules. IP packets are forwarded to IP table. MPLS
+     * packets are forwarded to MPLS table.
      *
      * @param deviceId switch ID to set the rules
      */
     public void populateTableTMac(DeviceId deviceId) {
 
-        // flow rule for IP packets
-        TrafficSelector selectorIp = DefaultTrafficSelector.builder()
-                .matchEthType(Ethernet.TYPE_IPV4)
-                .matchEthDst(config.getDeviceMac(deviceId))
-                .build();
-        TrafficTreatment treatmentIp = DefaultTrafficTreatment.builder()
-                .transition(FlowRule.Type.IP)
-                .build();
-
-        FlowRule flowIp = new DefaultFlowRule(deviceId, selectorIp, treatmentIp, 100,
-                srManager.appId, 600, false, FlowRule.Type.ETHER);
-
-        srManager.flowRuleService.applyFlowRules(flowIp);
-
-        // flow rule for MPLS packets
-        TrafficSelector selectorMpls = DefaultTrafficSelector.builder()
-                .matchEthType(Ethernet.MPLS_UNICAST)
-                .matchEthDst(config.getDeviceMac(deviceId))
-                .build();
-        TrafficTreatment treatmentMpls = DefaultTrafficTreatment.builder()
-                .transition(FlowRule.Type.MPLS)
-                .build();
-
-        FlowRule flowMpls = new DefaultFlowRule(deviceId, selectorMpls, treatmentMpls, 100,
-                srManager.appId, 600, false, FlowRule.Type.ETHER);
-
-        srManager.flowRuleService.applyFlowRules(flowMpls);
-
-    }
-
-    /**
-     * Populates a table miss entry.
-     *
-     * @param deviceId switch ID to set rules
-     * @param tableToAdd table to set the rules
-     * @param toControllerNow flag to send packets to controller immediately
-     * @param toControllerWrite flag to send packets to controller at the end of pipeline
-     * @param toTable flag to send packets to a specific table
-     * @param tableToSend table type to send packets when the toTable flag is set
-     */
-    public void populateTableMissEntry(DeviceId deviceId, FlowRule.Type tableToAdd, boolean toControllerNow,
-                                       boolean toControllerWrite,
-                                       boolean toTable, FlowRule.Type tableToSend) {
-        // TODO: Change arguments to EnumSet
-        TrafficSelector selector = DefaultTrafficSelector.builder()
-                .build();
-        TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
-
-        if (toControllerNow) {
-            tBuilder.setOutput(PortNumber.CONTROLLER);
-        }
-
-        if (toControllerWrite) {
-            tBuilder.deferred().setOutput(PortNumber.CONTROLLER);
-        }
-
-        if (toTable) {
-            tBuilder.transition(tableToSend);
-        }
-
-        FlowRule flow = new DefaultFlowRule(deviceId, selector, tBuilder.build(), 0,
-                srManager.appId, 600, false, tableToAdd);
-
-        srManager.flowRuleService.applyFlowRules(flow);
-
+        FilteringObjective.Builder fob = DefaultFilteringObjective.builder();
+        fob.withKey(Criteria.matchInPort(PortNumber.ALL))
+                .addCondition(Criteria.matchEthDst(config
+                                      .getDeviceMac(deviceId)));
+        fob.permit().fromApp(srManager.appId);
+        log.debug("populateTableVlan: Installing filtering objective for router mac");
+        srManager.flowObjectiveService.filter(deviceId, fob.add());
     }
 
     private Link selectOneLink(DeviceId srcId, Set<DeviceId> destIds) {
 
         Set<Link> links = srManager.linkService.getDeviceEgressLinks(srcId);
         DeviceId destId = (DeviceId) destIds.toArray()[0];
-        for (Link link: links) {
+        for (Link link : links) {
             if (link.dst().deviceId().equals(destId)) {
                 return link;
             }
diff --git a/src/main/java/org/onosproject/segmentrouting/SegmentRoutingManager.java b/src/main/java/org/onosproject/segmentrouting/SegmentRoutingManager.java
index 956fc1e..b7167c8 100644
--- a/src/main/java/org/onosproject/segmentrouting/SegmentRoutingManager.java
+++ b/src/main/java/org/onosproject/segmentrouting/SegmentRoutingManager.java
@@ -36,12 +36,10 @@
 import org.onosproject.net.device.DeviceEvent;
 import org.onosproject.net.device.DeviceListener;
 import org.onosproject.net.device.DeviceService;
-import org.onosproject.net.flow.FlowRuleService;
+import org.onosproject.net.flowobjective.FlowObjectiveService;
 import org.onosproject.net.group.Group;
 import org.onosproject.net.group.GroupEvent;
 import org.onosproject.net.group.GroupKey;
-import org.onosproject.net.group.GroupListener;
-import org.onosproject.net.group.GroupService;
 import org.onosproject.net.host.HostService;
 import org.onosproject.net.intent.IntentService;
 import org.onosproject.net.link.LinkEvent;
@@ -68,7 +66,8 @@
 @Component(immediate = true)
 public class SegmentRoutingManager {
 
-    private static Logger log = LoggerFactory.getLogger(SegmentRoutingManager.class);
+    private static Logger log = LoggerFactory
+            .getLogger(SegmentRoutingManager.class);
 
     @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
     protected CoreService coreService;
@@ -89,15 +88,12 @@
     protected DeviceService deviceService;
 
     @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
-    protected FlowRuleService flowRuleService;
+    protected FlowObjectiveService flowObjectiveService;
 
     @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
     protected LinkService linkService;
 
     @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
-    protected GroupService groupService;
-
-    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
     protected MastershipService mastershipService;
     protected ArpHandler arpHandler = null;
     protected IcmpHandler icmpHandler = null;
@@ -110,12 +106,12 @@
     private InternalPacketProcessor processor = new InternalPacketProcessor();
     private InternalEventHandler eventHandler = new InternalEventHandler();
 
-    private ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
+    private ScheduledExecutorService executorService = Executors
+            .newScheduledThreadPool(1);
 
     private static ScheduledFuture<?> eventHandlerFuture = null;
     private ConcurrentLinkedQueue<Event> eventQueue = new ConcurrentLinkedQueue<Event>();
-    private Map<DeviceId, DefaultGroupHandler> groupHandlerMap
-            = new ConcurrentHashMap<DeviceId, DefaultGroupHandler>();
+    private Map<DeviceId, DefaultGroupHandler> groupHandlerMap = new ConcurrentHashMap<DeviceId, DefaultGroupHandler>();
 
     private NetworkConfigManager networkConfigService = new NetworkConfigManager();;
 
@@ -125,7 +121,8 @@
 
     @Activate
     protected void activate() {
-        appId = coreService.registerApplication("org.onosproject.segmentrouting");
+        appId = coreService
+                .registerApplication("org.onosproject.segmentrouting");
         networkConfigService.init();
         deviceConfiguration = new DeviceConfiguration(networkConfigService);
         arpHandler = new ArpHandler(this);
@@ -136,25 +133,22 @@
 
         packetService.addProcessor(processor, PacketProcessor.ADVISOR_MAX + 2);
         linkService.addListener(new InternalLinkListener());
-        groupService.addListener(new InternalGroupListener());
         deviceService.addListener(new InternalDeviceListener());
 
-        for (Device device: deviceService.getDevices()) {
-            if (mastershipService.
-                    getLocalRole(device.id()) == MastershipRole.MASTER) {
-                DefaultGroupHandler groupHandler =
-                    DefaultGroupHandler.createGroupHandler(device.id(),
-                            appId, deviceConfiguration, linkService, groupService);
-                groupHandler.createGroups();
+        for (Device device : deviceService.getDevices()) {
+            if (mastershipService.getLocalRole(device.id()) == MastershipRole.MASTER) {
+                DefaultGroupHandler groupHandler = DefaultGroupHandler
+                        .createGroupHandler(device.id(), appId,
+                                            deviceConfiguration, linkService,
+                                            flowObjectiveService);
                 groupHandlerMap.put(device.id(), groupHandler);
                 defaultRoutingHandler.populateTtpRules(device.id());
                 log.debug("Initiating default group handling for {}", device.id());
             } else {
                 log.debug("Activate: Local role {} "
-                                + "is not MASTER for device {}",
-                        mastershipService.
-                                getLocalRole(device.id()),
-                        device.id());
+                                  + "is not MASTER for device {}",
+                          mastershipService.getLocalRole(device.id()),
+                          device.id());
             }
         }
 
@@ -177,13 +171,19 @@
      */
     public GroupKey getGroupKey(NeighborSet ns) {
 
-        for (DefaultGroupHandler groupHandler: groupHandlerMap.values()) {
+        for (DefaultGroupHandler groupHandler : groupHandlerMap.values()) {
             return groupHandler.getGroupKey(ns);
         }
 
         return null;
     }
 
+    public int getNextObjectiveId(DeviceId deviceId, NeighborSet ns) {
+
+        return (groupHandlerMap.get(deviceId) != null) ? groupHandlerMap
+                .get(deviceId).getNextObjectiveId(ns) : -1;
+    }
+
     private class InternalPacketProcessor implements PacketProcessor {
 
         @Override
@@ -213,8 +213,8 @@
     private class InternalLinkListener implements LinkListener {
         @Override
         public void event(LinkEvent event) {
-            if (event.type() == LinkEvent.Type.LINK_ADDED ||
-                    event.type() == LinkEvent.Type.LINK_REMOVED) {
+            if (event.type() == LinkEvent.Type.LINK_ADDED
+                    || event.type() == LinkEvent.Type.LINK_REMOVED) {
                 scheduleEventHandlerIfNotScheduled(event);
             }
         }
@@ -224,12 +224,10 @@
 
         @Override
         public void event(DeviceEvent event) {
-            if (mastershipService.
-                    getLocalRole(event.subject().id()) != MastershipRole.MASTER) {
+            if (mastershipService.getLocalRole(event.subject().id()) != MastershipRole.MASTER) {
                 log.debug("Local role {} is not MASTER for device {}",
-                        mastershipService.
-                                getLocalRole(event.subject().id()),
-                        event.subject().id());
+                          mastershipService.getLocalRole(event.subject().id()),
+                          event.subject().id());
                 return;
             }
 
@@ -245,38 +243,18 @@
         }
     }
 
-    private class InternalGroupListener implements GroupListener {
-
-        @Override
-        public void event(GroupEvent event) {
-            switch (event.type()) {
-                case GROUP_ADDED:
-                    scheduleEventHandlerIfNotScheduled(event);
-                    break;
-                case GROUP_ADD_REQUESTED:
-                    log.info("Group add requested");
-                    break;
-                case GROUP_UPDATED:
-                    break;
-                default:
-                    log.warn("Unhandled group event type: {}", event.type());
-            }
-        }
-    }
-
     private void scheduleEventHandlerIfNotScheduled(Event event) {
 
         eventQueue.add(event);
         numOfEvents++;
-        if (eventHandlerFuture == null ||
-                eventHandlerFuture.isDone()) {
-            eventHandlerFuture = executorService.schedule(eventHandler,
-                    100, TimeUnit.MILLISECONDS);
+        if (eventHandlerFuture == null || eventHandlerFuture.isDone()) {
+            eventHandlerFuture = executorService
+                    .schedule(eventHandler, 100, TimeUnit.MILLISECONDS);
             numOfHandlerScheduled++;
         }
 
         log.trace("numOfEvents {}, numOfEventHanlderScheduled {}", numOfEvents,
-                numOfHandlerScheduled);
+                  numOfHandlerScheduled);
 
     }
 
@@ -301,25 +279,22 @@
                     }
                 } else if (event.type() == DeviceEvent.Type.PORT_REMOVED) {
                     processPortRemoved((Device) event.subject(),
-                            ((DeviceEvent) event).port());
+                                       ((DeviceEvent) event).port());
                 } else {
                     log.warn("Unhandled event type: {}", event.type());
                 }
             }
             log.debug("numOfHandlerExecution {} numOfEventHanlderScheduled {} numOfEvents {}",
-                    numOfHandlerExecution, numOfHandlerScheduled, numOfEvents);
+                      numOfHandlerExecution, numOfHandlerScheduled, numOfEvents);
         }
     }
 
-
-
     private void processLinkAdded(Link link) {
         log.debug("A new link {} was added", link.toString());
 
-        if (mastershipService.
-                getLocalRole(link.src().deviceId()) == MastershipRole.MASTER) {
-            DefaultGroupHandler groupHandler =
-                    groupHandlerMap.get(link.src().deviceId());
+        if (mastershipService.getLocalRole(link.src().deviceId()) == MastershipRole.MASTER) {
+            DefaultGroupHandler groupHandler = groupHandlerMap.get(link.src()
+                    .deviceId());
             if (groupHandler != null) {
                 groupHandler.linkUp(link);
             }
@@ -332,7 +307,6 @@
         defaultRoutingHandler.populateRoutingRulesForLinkStatusChange(link);
     }
 
-
     private void processGroupAdded(Group group) {
         log.debug("A new group with ID {} was added", group.id());
         defaultRoutingHandler.resumePopulationProcess();
@@ -341,20 +315,14 @@
     private void processDeviceAdded(Device device) {
         log.debug("A new device with ID {} was added", device.id());
         defaultRoutingHandler.populateTtpRules(device.id());
-        DefaultGroupHandler dgh = DefaultGroupHandler.createGroupHandler(
-                device.id(),
-                appId,
-                deviceConfiguration,
-                linkService,
-                groupService);
-        dgh.createGroups();
+        DefaultGroupHandler dgh = DefaultGroupHandler.createGroupHandler(device
+                .id(), appId, deviceConfiguration, linkService, flowObjectiveService);
         groupHandlerMap.put(device.id(), dgh);
     }
 
     private void processPortRemoved(Device device, Port port) {
         log.debug("Port {} was removed", port.toString());
-        DefaultGroupHandler groupHandler =
-                groupHandlerMap.get(device.id());
+        DefaultGroupHandler groupHandler = groupHandlerMap.get(device.id());
         if (groupHandler != null) {
             groupHandler.portDown(port.number());
         }
diff --git a/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultEdgeGroupHandler.java b/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultEdgeGroupHandler.java
index 0cd5743..e54f51f 100644
--- a/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultEdgeGroupHandler.java
+++ b/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultEdgeGroupHandler.java
@@ -15,7 +15,6 @@
  */
 package org.onosproject.segmentrouting.grouphandler;
 
-import java.util.Arrays;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
@@ -26,10 +25,7 @@
 import org.onosproject.net.Link;
 import org.onosproject.net.flow.DefaultTrafficTreatment;
 import org.onosproject.net.flow.TrafficTreatment;
-import org.onosproject.net.group.DefaultGroupBucket;
-import org.onosproject.net.group.GroupBucket;
-import org.onosproject.net.group.GroupBuckets;
-import org.onosproject.net.group.GroupService;
+import org.onosproject.net.flowobjective.FlowObjectiveService;
 import org.onosproject.net.link.LinkService;
 
 /**
@@ -55,8 +51,8 @@
                                   ApplicationId appId,
                                   DeviceProperties config,
                                   LinkService linkService,
-                                  GroupService groupService) {
-        super(deviceId, appId, config, linkService, groupService);
+                                  FlowObjectiveService flowObjService) {
+        super(deviceId, appId, config, linkService, flowObjService);
     }
 
     @Override
@@ -130,7 +126,7 @@
                         .setMpls(MplsLabel.
                                  mplsLabel(ns.getEdgeLabel()));
             }
-            GroupBucket updatedBucket = DefaultGroupBucket.
+            /*GroupBucket updatedBucket = DefaultGroupBucket.
                     createSelectGroupBucket(tBuilder.build());
             GroupBuckets updatedBuckets = new GroupBuckets(
                                         Arrays.asList(updatedBucket));
@@ -140,7 +136,8 @@
                                            getGroupKey(ns),
                                            updatedBuckets,
                                            getGroupKey(ns),
-                                           appId);
+                                           appId);*/
+            //TODO: Use nextObjective APIs to update the next objective
         }
     }
 
diff --git a/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultGroupHandler.java b/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultGroupHandler.java
index 0ac3728..cb295db 100644
--- a/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultGroupHandler.java
+++ b/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultGroupHandler.java
@@ -20,10 +20,11 @@
 
 import java.net.URI;
 import java.util.ArrayList;
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
+import java.util.Random;
 import java.util.Set;
 
 import org.onlab.packet.MacAddress;
@@ -35,25 +36,18 @@
 import org.onosproject.net.PortNumber;
 import org.onosproject.net.flow.DefaultTrafficTreatment;
 import org.onosproject.net.flow.TrafficTreatment;
-import org.onosproject.net.group.DefaultGroupBucket;
-import org.onosproject.net.group.DefaultGroupDescription;
+import org.onosproject.net.flowobjective.DefaultNextObjective;
+import org.onosproject.net.flowobjective.FlowObjectiveService;
+import org.onosproject.net.flowobjective.NextObjective;
 import org.onosproject.net.group.DefaultGroupKey;
-import org.onosproject.net.group.Group;
-import org.onosproject.net.group.GroupBucket;
-import org.onosproject.net.group.GroupBuckets;
-import org.onosproject.net.group.GroupDescription;
-import org.onosproject.net.group.GroupEvent;
 import org.onosproject.net.group.GroupKey;
-import org.onosproject.net.group.GroupListener;
-import org.onosproject.net.group.GroupService;
 import org.onosproject.net.link.LinkService;
 import org.slf4j.Logger;
 
 /**
- * Default ECMP group handler creation module. This
- * component creates a set of ECMP groups for every neighbor
- * that this device is connected to based on whether the
- * current device is an edge device or a transit device.
+ * Default ECMP group handler creation module. This component creates a set of
+ * ECMP groups for every neighbor that this device is connected to based on
+ * whether the current device is an edge device or a transit device.
  */
 public class DefaultGroupHandler {
     protected final Logger log = getLogger(getClass());
@@ -66,88 +60,78 @@
     protected final boolean isEdgeRouter;
     protected final MacAddress nodeMacAddr;
     protected LinkService linkService;
-    protected GroupService groupService;
+    protected FlowObjectiveService flowObjectiveService;
 
     protected HashMap<DeviceId, Set<PortNumber>> devicePortMap =
             new HashMap<DeviceId, Set<PortNumber>>();
     protected HashMap<PortNumber, DeviceId> portDeviceMap =
             new HashMap<PortNumber, DeviceId>();
+    protected HashMap<GroupKey, Integer> deviceNextObjectiveIds =
+            new HashMap<GroupKey, Integer>();
+    protected Random rand = new Random();
 
-    private GroupListener listener = new InternalGroupListener();
     protected KryoNamespace.Builder kryo = new KryoNamespace.Builder()
-    .register(URI.class)
-    .register(HashSet.class)
-    .register(DeviceId.class)
-    .register(PortNumber.class)
-    .register(NeighborSet.class)
-    .register(PolicyGroupIdentifier.class)
-    .register(PolicyGroupParams.class)
-    .register(GroupBucketIdentifier.class)
-    .register(GroupBucketIdentifier.BucketOutputType.class);
+            .register(URI.class).register(HashSet.class)
+            .register(DeviceId.class).register(PortNumber.class)
+            .register(NeighborSet.class).register(PolicyGroupIdentifier.class)
+            .register(PolicyGroupParams.class)
+            .register(GroupBucketIdentifier.class)
+            .register(GroupBucketIdentifier.BucketOutputType.class);
 
-    protected DefaultGroupHandler(DeviceId deviceId,
-                               ApplicationId appId,
-                               DeviceProperties config,
-                               LinkService linkService,
-                               GroupService groupService) {
+    protected DefaultGroupHandler(DeviceId deviceId, ApplicationId appId,
+                                  DeviceProperties config,
+                                  LinkService linkService,
+                                  FlowObjectiveService flowObjService) {
         this.deviceId = checkNotNull(deviceId);
         this.appId = checkNotNull(appId);
         this.deviceConfig = checkNotNull(config);
         this.linkService = checkNotNull(linkService);
-        this.groupService = checkNotNull(groupService);
         allSegmentIds = checkNotNull(config.getAllDeviceSegmentIds());
         nodeSegmentId = config.getSegmentId(deviceId);
         isEdgeRouter = config.isEdgeDevice(deviceId);
         nodeMacAddr = checkNotNull(config.getDeviceMac(deviceId));
-
-        this.groupService.addListener(listener);
+        this.flowObjectiveService = flowObjService;
 
         populateNeighborMaps();
     }
 
     /**
-     * Creates a group handler object based on the type of device. If
-     * device is of edge type it returns edge group handler, else it
-     * returns transit group handler.
+     * Creates a group handler object based on the type of device. If device is
+     * of edge type it returns edge group handler, else it returns transit group
+     * handler.
      *
      * @param deviceId device identifier
      * @param appId application identifier
      * @param config interface to retrieve the device properties
      * @param linkService link service object
-     * @param groupService group service object
+     * @param flowObjService flow objective service object
      * @return default group handler type
      */
     public static DefaultGroupHandler createGroupHandler(DeviceId deviceId,
-                                                  ApplicationId appId,
-                                                  DeviceProperties config,
-                                                  LinkService linkService,
-                                                  GroupService groupService) {
+                                                         ApplicationId appId,
+                                                         DeviceProperties config,
+                                                         LinkService linkService,
+                                                         FlowObjectiveService flowObjService) {
         if (config.isEdgeDevice(deviceId)) {
-            return new DefaultEdgeGroupHandler(deviceId,
-                                               appId,
-                                               config,
-                                               linkService,
-                                               groupService);
+            return new DefaultEdgeGroupHandler(deviceId, appId, config,
+                                               linkService, flowObjService);
         } else {
-            return new DefaultTransitGroupHandler(deviceId,
-                                                  appId,
-                                                  config,
-                                                  linkService,
-                                                  groupService);
+            return new DefaultTransitGroupHandler(deviceId, appId, config,
+                                                  linkService, flowObjService);
         }
     }
 
     /**
-     * Creates the auto created groups for this device based on the
-     * current snapshot of the topology.
+     * Creates the auto created groups for this device based on the current
+     * snapshot of the topology.
      */
-    //Empty implementations to be overridden by derived classes
+    // Empty implementations to be overridden by derived classes
     public void createGroups() {
     }
 
     /**
-     * Performs group creation or update procedures when a new link
-     * is discovered on this device.
+     * Performs group creation or update procedures when a new link is
+     * discovered on this device.
      *
      * @param newLink new neighbor link
      */
@@ -158,16 +142,14 @@
             return;
         }
 
-
         if (!newLink.src().deviceId().equals(deviceId)) {
             log.warn("linkUp: deviceId{} doesn't match with link src{}",
-                     deviceId,
-                     newLink.src().deviceId());
+                     deviceId, newLink.src().deviceId());
             return;
         }
 
-        log.debug("Device {} linkUp at local port {} to neighbor {}",
-                  deviceId, newLink.src().port(), newLink.dst().deviceId());
+        log.debug("Device {} linkUp at local port {} to neighbor {}", deviceId,
+                  newLink.src().port(), newLink.dst().deviceId());
         if (devicePortMap.get(newLink.dst().deviceId()) == null) {
             // New Neighbor
             newNeighbor(newLink);
@@ -178,8 +160,7 @@
     }
 
     /**
-     * Performs group recovery procedures when a port goes down
-     * on this device.
+     * Performs group recovery procedures when a port goes down on this device.
      *
      * @param port port number that has gone down
      */
@@ -188,35 +169,34 @@
             log.warn("portDown: unknown port");
             return;
         }
-        log.debug("Device {} portDown {} to neighbor {}",
-                  deviceId, port, portDeviceMap.get(port));
-        Set<NeighborSet> nsSet = computeImpactedNeighborsetForPortEvent(
-                                                     portDeviceMap.get(port),
-                                                     devicePortMap.keySet());
+        log.debug("Device {} portDown {} to neighbor {}", deviceId, port,
+                  portDeviceMap.get(port));
+        Set<NeighborSet> nsSet = computeImpactedNeighborsetForPortEvent(portDeviceMap
+                                                                                .get(port),
+                                                                        devicePortMap
+                                                                                .keySet());
         for (NeighborSet ns : nsSet) {
             // Create the bucket to be removed
-            TrafficTreatment.Builder tBuilder =
-                    DefaultTrafficTreatment.builder();
+            TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment
+                    .builder();
             tBuilder.setOutput(port)
-                    .setEthDst(deviceConfig.getDeviceMac(
-                         portDeviceMap.get(port)))
-                    .setEthSrc(nodeMacAddr);
+                    .setEthDst(deviceConfig.getDeviceMac(portDeviceMap
+                                       .get(port))).setEthSrc(nodeMacAddr);
             if (ns.getEdgeLabel() != NeighborSet.NO_EDGE_LABEL) {
-                tBuilder.pushMpls()
-                    .setMpls(MplsLabel.mplsLabel(ns.getEdgeLabel()));
+                tBuilder.pushMpls().setMpls(MplsLabel.mplsLabel(ns
+                                                    .getEdgeLabel()));
             }
-            GroupBucket removeBucket = DefaultGroupBucket.
-                    createSelectGroupBucket(tBuilder.build());
-            GroupBuckets removeBuckets = new GroupBuckets(
-                                               Arrays.asList(removeBucket));
-            log.debug("portDown in device{}: "
-                    + "groupService.removeBucketsFromGroup "
-                    + "for neighborset{}", deviceId, ns);
-            groupService.removeBucketsFromGroup(deviceId,
-                                                getGroupKey(ns),
-                                                removeBuckets,
-                                                getGroupKey(ns),
-                                                appId);
+            /*
+             * GroupBucket removeBucket = DefaultGroupBucket.
+             * createSelectGroupBucket(tBuilder.build()); GroupBuckets
+             * removeBuckets = new GroupBuckets( Arrays.asList(removeBucket));
+             * log.debug("portDown in device{}: " +
+             * "groupService.removeBucketsFromGroup " + "for neighborset{}",
+             * deviceId, ns); groupService.removeBucketsFromGroup(deviceId,
+             * getGroupKey(ns), removeBuckets, getGroupKey(ns), appId);
+             */
+            //TODO: Use next objective API to update the previously created
+            //next objectives.
         }
 
         devicePortMap.get(portDeviceMap.get(port)).remove(port);
@@ -224,33 +204,44 @@
     }
 
     /**
-     * Returns a group associated with the key.
+     * Returns the next objective associated with the neighborset.
+     * If there is no next objective for this neighborset, this API
+     * would create a next objective and return.
      *
-     * @param key cookie associated with the group
-     * @return group if found or null
+     * @param ns neighborset
+     * @return int if found or -1
      */
-    public Group getGroup(GroupKey key) {
-        return groupService.getGroup(deviceId, key);
+    public int getNextObjectiveId(NeighborSet ns) {
+        Integer nextId = deviceNextObjectiveIds.get(getGroupKey(ns));
+        if (nextId == null) {
+            createGroupsFromNeighborsets(Collections.singleton(ns));
+            nextId = deviceNextObjectiveIds.get(getGroupKey(ns));
+            if (nextId == null) {
+                log.warn("getNextObjectiveId: unable to create next objective");
+                return -1;
+            }
+        }
+        return nextId.intValue();
     }
 
-    //Empty implementation
+    // Empty implementation
     protected void newNeighbor(Link newLink) {
     }
 
-    //Empty implementation
+    // Empty implementation
     protected void newPortToExistingNeighbor(Link newLink) {
     }
 
-    //Empty implementation
-    protected Set<NeighborSet> computeImpactedNeighborsetForPortEvent(
-                                    DeviceId impactedNeighbor,
-                                    Set<DeviceId> updatedNeighbors) {
+    // Empty implementation
+    protected Set<NeighborSet>
+        computeImpactedNeighborsetForPortEvent(DeviceId impactedNeighbor,
+                                               Set<DeviceId> updatedNeighbors) {
         return null;
     }
 
     private void populateNeighborMaps() {
         Set<Link> outgoingLinks = linkService.getDeviceEgressLinks(deviceId);
-        for (Link link:outgoingLinks) {
+        for (Link link : outgoingLinks) {
             if (link.type() != Link.Type.DIRECT) {
                 continue;
             }
@@ -258,7 +249,8 @@
         }
     }
 
-    protected void addNeighborAtPort(DeviceId neighborId, PortNumber portToNeighbor) {
+    protected void addNeighborAtPort(DeviceId neighborId,
+                                     PortNumber portToNeighbor) {
         // Update DeviceToPort database
         log.debug("Device {} addNeighborAtPort: neighbor {} at port {}",
                   deviceId, neighborId, portToNeighbor);
@@ -276,8 +268,7 @@
         }
     }
 
-    protected Set<Set<DeviceId>>
-            getPowerSetOfNeighbors(Set<DeviceId> neighbors) {
+    protected Set<Set<DeviceId>> getPowerSetOfNeighbors(Set<DeviceId> neighbors) {
         List<DeviceId> list = new ArrayList<DeviceId>(neighbors);
         Set<Set<DeviceId>> sets = new HashSet<Set<DeviceId>>();
         // get the number of elements in the neighbors
@@ -304,15 +295,14 @@
         return (deviceConfig.getSegmentId(deviceId) == sId);
     }
 
-    protected List<Integer> getSegmentIdsTobePairedWithNeighborSet(
-                                   Set<DeviceId> neighbors) {
+    protected List<Integer> getSegmentIdsTobePairedWithNeighborSet(Set<DeviceId> neighbors) {
 
         List<Integer> nsSegmentIds = new ArrayList<Integer>();
 
         // Always pair up with no edge label
-        //If (neighbors.size() == 1) {
+        // If (neighbors.size() == 1) {
         nsSegmentIds.add(-1);
-        //}
+        // }
 
         // Filter out SegmentIds matching with the
         // nodes in the combo
@@ -338,70 +328,28 @@
 
     protected void createGroupsFromNeighborsets(Set<NeighborSet> nsSet) {
         for (NeighborSet ns : nsSet) {
-            // Create the bucket array from the neighbor set
-            List<GroupBucket> buckets = new ArrayList<GroupBucket>();
+            int nextId = flowObjectiveService.allocateNextId();
+            NextObjective.Builder nextObjBuilder = DefaultNextObjective
+                    .builder().withId(nextId)
+                    .withType(NextObjective.Type.HASHED).fromApp(appId);
             for (DeviceId d : ns.getDeviceIds()) {
                 for (PortNumber sp : devicePortMap.get(d)) {
-                    TrafficTreatment.Builder tBuilder =
-                            DefaultTrafficTreatment.builder();
+                    TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment
+                            .builder();
                     tBuilder.setOutput(sp)
                             .setEthDst(deviceConfig.getDeviceMac(d))
                             .setEthSrc(nodeMacAddr);
                     if (ns.getEdgeLabel() != NeighborSet.NO_EDGE_LABEL) {
-                        tBuilder.pushMpls()
-                                .setMpls(MplsLabel.
-                                         mplsLabel(ns.getEdgeLabel()));
+                        tBuilder.pushMpls().setMpls(MplsLabel.mplsLabel(ns
+                                                            .getEdgeLabel()));
                     }
-                    buckets.add(DefaultGroupBucket.createSelectGroupBucket(
-                                                                tBuilder.build()));
+                    nextObjBuilder.addTreatment(tBuilder.build());
                 }
             }
-            GroupBuckets groupBuckets = new GroupBuckets(buckets);
-            GroupDescription newGroupDesc = new DefaultGroupDescription(
-                                      deviceId,
-                                      Group.Type.SELECT,
-                                      groupBuckets,
-                                      getGroupKey(ns),
-                                      appId);
-            log.debug("createGroupsFromNeighborsets: "
-                    + "groupService.addGroup for neighborset{}", ns);
-            groupService.addGroup(newGroupDesc);
-        }
-    }
 
-    protected void handleGroupEvent(GroupEvent event) {
-        switch (event.type()) {
-        case GROUP_ADDED:
-            log.debug("Received GROUP_ADDED from group service "
-                    + "for device {} with group key{} with id{}",
-                      event.subject().deviceId(),
-                      event.subject().appCookie(),
-                      event.subject().id());
-            break;
-        case GROUP_UPDATED:
-            log.trace("Received GROUP_UPDATED from group service "
-                    + "for device {} with group key{} with id{}",
-                      event.subject().deviceId(),
-                      event.subject().appCookie(),
-                      event.subject().id());
-            break;
-        case GROUP_REMOVED:
-            log.debug("Received GROUP_REMOVED from group service "
-                    + "for device {} with group key{} with id{}",
-                      event.subject().deviceId(),
-                      event.subject().appCookie(),
-                      event.subject().id());
-            break;
-        default:
-            break;
-        }
-    }
-
-    private class InternalGroupListener implements GroupListener {
-
-        @Override
-        public void event(GroupEvent event) {
-            handleGroupEvent(event);
+            NextObjective nextObj = nextObjBuilder.add();
+            flowObjectiveService.next(deviceId, nextObj);
+            deviceNextObjectiveIds.put(getGroupKey(ns), nextId);
         }
     }
 
diff --git a/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultTransitGroupHandler.java b/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultTransitGroupHandler.java
index e053622..67e9eef 100644
--- a/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultTransitGroupHandler.java
+++ b/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultTransitGroupHandler.java
@@ -15,7 +15,6 @@
  */
 package org.onosproject.segmentrouting.grouphandler;
 
-import java.util.Arrays;
 import java.util.HashSet;
 import java.util.Set;
 
@@ -25,10 +24,7 @@
 import org.onosproject.net.Link;
 import org.onosproject.net.flow.DefaultTrafficTreatment;
 import org.onosproject.net.flow.TrafficTreatment;
-import org.onosproject.net.group.DefaultGroupBucket;
-import org.onosproject.net.group.GroupBucket;
-import org.onosproject.net.group.GroupBuckets;
-import org.onosproject.net.group.GroupService;
+import org.onosproject.net.flowobjective.FlowObjectiveService;
 import org.onosproject.net.link.LinkService;
 
 /**
@@ -49,8 +45,8 @@
                                   ApplicationId appId,
                                   DeviceProperties config,
                                   LinkService linkService,
-                                  GroupService groupService) {
-        super(deviceId, appId, config, linkService, groupService);
+                                  FlowObjectiveService flowObjService) {
+        super(deviceId, appId, config, linkService, flowObjService);
     }
 
     @Override
@@ -118,7 +114,7 @@
                         .setMpls(MplsLabel.
                                  mplsLabel(ns.getEdgeLabel()));
             }
-            GroupBucket updatedBucket = DefaultGroupBucket.
+            /*GroupBucket updatedBucket = DefaultGroupBucket.
                     createSelectGroupBucket(tBuilder.build());
             GroupBuckets updatedBuckets = new GroupBuckets(
                                         Arrays.asList(updatedBucket));
@@ -128,7 +124,8 @@
                                            getGroupKey(ns),
                                            updatedBuckets,
                                            getGroupKey(ns),
-                                           appId);
+                                           appId);*/
+            //TODO: Use nextObjective APIs to update the next objective
         }
     }
 
diff --git a/src/main/java/org/onosproject/segmentrouting/grouphandler/PolicyGroupHandler.java b/src/main/java/org/onosproject/segmentrouting/grouphandler/PolicyGroupHandler.java
index 9f35c74..d141ed1 100644
--- a/src/main/java/org/onosproject/segmentrouting/grouphandler/PolicyGroupHandler.java
+++ b/src/main/java/org/onosproject/segmentrouting/grouphandler/PolicyGroupHandler.java
@@ -25,19 +25,13 @@
 
 import org.onlab.packet.MplsLabel;
 import org.onosproject.core.ApplicationId;
-import org.onosproject.core.GroupId;
 import org.onosproject.segmentrouting.grouphandler.GroupBucketIdentifier.BucketOutputType;
 import org.onosproject.net.DeviceId;
 import org.onosproject.net.PortNumber;
 import org.onosproject.net.flow.DefaultTrafficTreatment;
 import org.onosproject.net.flow.TrafficTreatment;
-import org.onosproject.net.group.DefaultGroupBucket;
-import org.onosproject.net.group.DefaultGroupDescription;
+import org.onosproject.net.flowobjective.FlowObjectiveService;
 import org.onosproject.net.group.GroupBucket;
-import org.onosproject.net.group.GroupBuckets;
-import org.onosproject.net.group.GroupDescription;
-import org.onosproject.net.group.GroupEvent;
-import org.onosproject.net.group.GroupService;
 import org.onosproject.net.link.LinkService;
 import org.slf4j.Logger;
 
@@ -58,14 +52,14 @@
      * @param appId application identifier
      * @param config interface to retrieve the device properties
      * @param linkService link service object
-     * @param groupService group service object
+     * @param flowObjService flow objective service object
      */
     public PolicyGroupHandler(DeviceId deviceId,
                               ApplicationId appId,
                               DeviceProperties config,
                               LinkService linkService,
-                              GroupService groupService) {
-        super(deviceId, appId, config, linkService, groupService);
+                              FlowObjectiveService flowObjService) {
+        super(deviceId, appId, config, linkService, flowObjService);
     }
 
     public PolicyGroupIdentifier createPolicyGroupChain(String id,
@@ -111,15 +105,16 @@
                                     .setEthSrc(nodeMacAddr)
                                     .pushMpls()
                                     .setMpls(MplsLabel.mplsLabel(label));
-                            outBuckets.add(DefaultGroupBucket.
+                            /*outBuckets.add(DefaultGroupBucket.
                                            createSelectGroupBucket(tBuilder.build()));
                             GroupDescription desc = new
                                     DefaultGroupDescription(deviceId,
                                                             GroupDescription.Type.INDIRECT,
                                                             new GroupBuckets(outBuckets));
-                            //TODO: BoS
+                            //TODO: BoS*/
                             previousGroupkey = key;
-                            groupService.addGroup(desc);
+                            //groupService.addGroup(desc);
+                            //TODO: Use nextObjective APIs here
                         } else {
                             // Intermediate Groups
                             GroupBucketIdentifier bucketId =
@@ -179,20 +174,22 @@
                             .setMpls(MplsLabel.mplsLabel(bucketId.label()));
                     }
                     //TODO: BoS
-                    outBuckets.add(DefaultGroupBucket.
-                                   createSelectGroupBucket(tBuilder.build()));
+                    /*outBuckets.add(DefaultGroupBucket.
+                                   createSelectGroupBucket(tBuilder.build()));*/
                 }
-                GroupDescription desc = new
+                /*GroupDescription desc = new
                         DefaultGroupDescription(deviceId,
                                                 GroupDescription.Type.SELECT,
                                                 new GroupBuckets(outBuckets));
-                groupService.addGroup(desc);
+                groupService.addGroup(desc);*/
+                //TODO: Use nextObjective APIs here
             }
         }
         return innermostGroupkey;
     }
 
-    @Override
+    //TODO: Use nextObjective APIs to handle the group chains
+    /*@Override
     protected void handleGroupEvent(GroupEvent event) {
         if (event.type() == GroupEvent.Type.GROUP_ADDED) {
             if (dependentGroups.get(event.subject().appCookie()) != null) {
@@ -253,7 +250,7 @@
                 }
             }
         }
-    }
+    }*/
 
     public PolicyGroupIdentifier generatePolicyGroupKey(String id,
                                    List<PolicyGroupParams> params) {
@@ -343,9 +340,10 @@
                     groupsToBeDeleted.add(bucketId.outGroup());
                 }
             }
-            groupService.removeGroup(deviceId,
+            /*groupService.removeGroup(deviceId,
                                      getGroupKey(innerMostGroupKey),
-                                     appId);
+                                     appId);*/
+            //TODO: Use nextObjective APIs here
             it.remove();
         }
     }