[ONOS-4164] PceManager device and link event handling

Change-Id: I55d8f60e0fcc0e23f4c14045a8e20bd89f635913
diff --git a/apps/pce/app/src/main/java/org/onosproject/pce/pceservice/PceManager.java b/apps/pce/app/src/main/java/org/onosproject/pce/pceservice/PceManager.java
index aa16f80..2e148db 100644
--- a/apps/pce/app/src/main/java/org/onosproject/pce/pceservice/PceManager.java
+++ b/apps/pce/app/src/main/java/org/onosproject/pce/pceservice/PceManager.java
@@ -19,6 +19,7 @@
 
 import java.util.Collection;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.List;
@@ -60,6 +61,8 @@
 import org.onosproject.incubator.net.tunnel.TunnelName;
 import org.onosproject.incubator.net.tunnel.TunnelService;
 import org.onosproject.mastership.MastershipService;
+import org.onosproject.net.config.NetworkConfigEvent;
+import org.onosproject.net.config.NetworkConfigListener;
 import org.onosproject.net.config.NetworkConfigService;
 import org.onosproject.net.DefaultAnnotations;
 import org.onosproject.net.DefaultAnnotations.Builder;
@@ -67,12 +70,17 @@
 import org.onosproject.net.DeviceId;
 import org.onosproject.net.Link;
 import org.onosproject.net.Path;
+import org.onosproject.net.device.DeviceEvent;
+import org.onosproject.net.device.DeviceListener;
 import org.onosproject.net.device.DeviceService;
 import org.onosproject.net.flowobjective.FlowObjectiveService;
 import org.onosproject.net.flowobjective.Objective;
 import org.onosproject.net.intent.Constraint;
 import org.onosproject.net.intent.constraint.BandwidthConstraint;
+import org.onosproject.net.link.LinkListener;
 import org.onosproject.net.link.LinkEvent;
+import org.onosproject.net.link.LinkService;
+import org.onosproject.net.MastershipRole;
 import org.onosproject.pce.pceservice.constraint.CapabilityConstraint;
 import org.onosproject.pce.pceservice.constraint.CapabilityConstraint.CapabilityType;
 import org.onosproject.pce.pceservice.constraint.CostConstraint;
@@ -134,8 +142,14 @@
 public class PceManager implements PceService {
     private static final Logger log = LoggerFactory.getLogger(PceManager.class);
 
+    public static final long GLOBAL_LABEL_SPACE_MIN = 4097;
+    public static final long GLOBAL_LABEL_SPACE_MAX = 5121;
+    private static final String DEVICE_NULL = "Device-cannot be null";
+    private static final String LINK_NULL = "Link-cannot be null";
     public static final String PCE_SERVICE_APP = "org.onosproject.pce";
     private static final String LOCAL_LSP_ID_GEN_TOPIC = "pcep-local-lsp-id";
+    public static final String DEVICE_TYPE = "type";
+    public static final String L3_DEVICE = "L3";
     private static final int PREFIX_LENGTH = 32;
 
     private static final String TUNNEL_CONSUMER_ID_GEN_TOPIC = "pcep-tunnel-consumer-id";
@@ -150,6 +164,10 @@
     private IdGenerator localLspIdIdGen;
     protected DistributedSet<Short> localLspIdFreeList;
 
+    // LSR-id and device-id mapping for checking capability if L3 device is not
+    // having its capability
+    private Map<String, DeviceId> lsrIdDeviceIdMap = new HashMap<>();
+
     @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
     protected CoreService coreService;
 
@@ -178,6 +196,9 @@
     protected DeviceService deviceService;
 
     @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected LinkService linkService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
     protected NetworkConfigService netCfgService;
 
     @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
@@ -196,6 +217,9 @@
     protected TopologyService topologyService;
 
     private TunnelListener listener = new InnerTunnelListener();
+    private DeviceListener deviceListener = new InternalDeviceListener();
+    private LinkListener linkListener = new InternalLinkListener();
+    private InternalConfigListener cfgListener = new InternalConfigListener();
     private BasicPceccHandler crHandler;
     private PceccSrTeBeHandler srTeHandler;
     private ApplicationId appId;
@@ -220,9 +244,13 @@
         crHandler.initialize(labelRsrcService, flowObjectiveService, appId, pceStore);
 
         srTeHandler = PceccSrTeBeHandler.getInstance();
-        srTeHandler.initialize(labelRsrcAdminService, labelRsrcService, flowObjectiveService, appId, pceStore);
+        srTeHandler.initialize(labelRsrcAdminService, labelRsrcService, flowObjectiveService, appId, pceStore,
+                               deviceService);
 
         tunnelService.addListener(listener);
+        deviceService.addListener(deviceListener);
+        linkService.addListener(linkListener);
+        netCfgService.addListener(cfgListener);
 
         tunnelConsumerIdGen = coreService.getIdGenerator(TUNNEL_CONSUMER_ID_GEN_TOPIC);
         localLspIdIdGen = coreService.getIdGenerator(LOCAL_LSP_ID_GEN_TOPIC);
@@ -237,15 +265,24 @@
         executor = Executors.newSingleThreadScheduledExecutor();
         //Start a timer when the component is up, with initial delay of 30min and periodic delays at 30min
         executor.scheduleAtFixedRate(new GlobalOptimizationTimer(), INITIAL_DELAY, PERIODIC_DELAY, TimeUnit.MINUTES);
+
+        // Reserve global node pool
+        if (!srTeHandler.reserveGlobalPool(GLOBAL_LABEL_SPACE_MIN, GLOBAL_LABEL_SPACE_MAX)) {
+            log.debug("Global node pool was already reserved.");
+        }
+
         log.info("Started");
     }
 
     @Deactivate
     protected void deactivate() {
         tunnelService.removeListener(listener);
+        deviceService.removeListener(deviceListener);
+        linkService.removeListener(linkListener);
+        netCfgService.removeListener(cfgListener);
         packetService.removeProcessor(processor);
         topologyService.removeListener(topologyListener);
-        //Shutdown the thread when component is deactivated
+        // Shutdown the thread when component is deactivated
         executor.shutdown();
         log.info("Stopped");
     }
@@ -819,6 +856,234 @@
             resource = Resources.continuous(link.src().deviceId(), link.src().port(), Bandwidth.class)
                     .resource(bandwidth);
             resourceService.allocate(consumer, resource); // Reusing new tunnel's TunnelConsumerId intentionally.
+
+        }
+    }
+
+    /**
+     * Allocates node label to specific device.
+     *
+     * @param specificDevice device to which node label needs to be allocated
+     */
+    public void allocateNodeLabel(Device specificDevice) {
+        checkNotNull(specificDevice, DEVICE_NULL);
+
+        DeviceId deviceId = specificDevice.id();
+
+        // Retrieve lsrId of a specific device
+        if (specificDevice.annotations() == null) {
+            log.debug("Device {} does not have annotations.", specificDevice.toString());
+            return;
+        }
+
+        String lsrId = specificDevice.annotations().value(LSRID);
+        if (lsrId == null) {
+            log.debug("Unable to retrieve lsr-id of a device {}.", specificDevice.toString());
+            return;
+        }
+
+        // Get capability config from netconfig
+        DeviceCapability cfg = netCfgService.getConfig(DeviceId.deviceId(lsrId), DeviceCapability.class);
+        if (cfg == null) {
+            log.error("Unable to find corresponding capability for a lsrd {} from NetConfig.", lsrId);
+            // Save info. When PCEP session is comes up then allocate node-label
+            lsrIdDeviceIdMap.put(lsrId, specificDevice.id());
+            return;
+        }
+
+        // Check whether device has SR-TE Capability
+        if (cfg.labelStackCap()) {
+            if (!srTeHandler.allocateNodeLabel(deviceId, lsrId)) {
+                log.error("Node label allocation for a device id {} has failed.", deviceId.toString());
+            }
+        }
+    }
+
+    /**
+     * Releases node label of a specific device.
+     *
+     * @param specificDevice this device label and lsr-id information will be
+     *            released in other existing devices
+     */
+    public void releaseNodeLabel(Device specificDevice) {
+        checkNotNull(specificDevice, DEVICE_NULL);
+
+        DeviceId deviceId = specificDevice.id();
+
+        // Retrieve lsrId of a specific device
+        if (specificDevice.annotations() == null) {
+            log.debug("Device {} does not have annotations.", specificDevice.toString());
+            return;
+        }
+
+        String lsrId = specificDevice.annotations().value(LSRID);
+        if (lsrId == null) {
+            log.debug("Unable to retrieve lsr-id of a device {}.", specificDevice.toString());
+            return;
+        }
+
+        // Get capability config from netconfig
+        DeviceCapability cfg = netCfgService.getConfig(DeviceId.deviceId(lsrId), DeviceCapability.class);
+        if (cfg == null) {
+            log.error("Unable to find corresponding capabilty for a lsrd {} from NetConfig.", lsrId);
+            return;
+        }
+
+        // Check whether device has SR-TE Capability
+        if (cfg.labelStackCap()) {
+            if (!srTeHandler.releaseNodeLabel(deviceId, lsrId)) {
+                log.error("Unable to release node label for a device id {}.", deviceId.toString());
+            }
+        }
+    }
+
+    /**
+     * Allocates adjacency label for a link.
+     *
+     * @param link link
+     */
+    public void allocateAdjacencyLabel(Link link) {
+        checkNotNull(link, LINK_NULL);
+
+        Device specificDevice = deviceService.getDevice(link.src().deviceId());
+        DeviceId deviceId = specificDevice.id();
+
+        // Retrieve lsrId of a specific device
+        if (specificDevice.annotations() == null) {
+            log.debug("Device {} does not have annotations.", specificDevice.toString());
+            return;
+        }
+
+        String lsrId = specificDevice.annotations().value(LSRID);
+        if (lsrId == null) {
+            log.debug("Unable to retrieve lsr-id of a device {}.", specificDevice.toString());
+            return;
+        }
+
+        // Get capability config from netconfig
+        DeviceCapability cfg = netCfgService.getConfig(DeviceId.deviceId(lsrId), DeviceCapability.class);
+        if (cfg == null) {
+            log.error("Unable to find corresponding capabilty for a lsrd {} from NetConfig.", lsrId);
+            // Save info. When PCEP session comes up then allocate adjacency
+            // label
+            if (lsrIdDeviceIdMap.get(lsrId) != null) {
+                lsrIdDeviceIdMap.put(lsrId, specificDevice.id());
+            }
+            return;
+        }
+
+        // Check whether device has SR-TE Capability
+        if (cfg.labelStackCap()) {
+            if (!srTeHandler.allocateAdjacencyLabel(link)) {
+                log.error("Unable to allocate adjacency label for a link {}.", link.toString());
+                return;
+            }
+        }
+
+        return;
+    }
+
+    /**
+     * Releases allocated adjacency label of a link.
+     *
+     * @param link link
+     */
+    public void releaseAdjacencyLabel(Link link) {
+        checkNotNull(link, LINK_NULL);
+
+        Device specificDevice = deviceService.getDevice(link.src().deviceId());
+        DeviceId deviceId = specificDevice.id();
+
+        // Retrieve lsrId of a specific device
+        if (specificDevice.annotations() == null) {
+            log.debug("Device {} does not have annotations.", specificDevice.toString());
+            return;
+        }
+
+        String lsrId = specificDevice.annotations().value(LSRID);
+        if (lsrId == null) {
+            log.debug("Unable to retrieve lsr-id of a device {}.", specificDevice.toString());
+            return;
+        }
+
+        // Get capability config from netconfig
+        DeviceCapability cfg = netCfgService.getConfig(DeviceId.deviceId(lsrId), DeviceCapability.class);
+        if (cfg == null) {
+            log.error("Unable to find corresponding capabilty for a lsrd {} from NetConfig.", lsrId);
+            return;
+        }
+
+        // Check whether device has SR-TE Capability
+        if (cfg.labelStackCap()) {
+            if (!srTeHandler.releaseAdjacencyLabel(link)) {
+                log.error("Unable to release adjacency labels for a link {}.", link.toString());
+                return;
+            }
+        }
+
+        return;
+    }
+
+    /*
+     * Handle device events.
+     */
+    private class InternalDeviceListener implements DeviceListener {
+        @Override
+        public void event(DeviceEvent event) {
+            Device specificDevice = (Device) event.subject();
+            if (specificDevice == null) {
+                log.error("Unable to find device from device event.");
+                return;
+            }
+
+            switch (event.type()) {
+
+            case DEVICE_ADDED:
+                // Node-label allocation is being done during Label DB Sync.
+                // So, when device is detected, no need to do node-label
+                // allocation.
+                break;
+
+            case DEVICE_REMOVED:
+                // Release node-label
+                if (mastershipService.getLocalRole(specificDevice.id()) == MastershipRole.MASTER) {
+                    releaseNodeLabel(specificDevice);
+                }
+                break;
+
+            default:
+                break;
+            }
+        }
+    }
+
+    /*
+     * Handle link events.
+     */
+    private class InternalLinkListener implements LinkListener {
+        @Override
+        public void event(LinkEvent event) {
+            Link link = (Link) event.subject();
+
+            switch (event.type()) {
+
+            case LINK_ADDED:
+                // Allocate adjacency label
+                if (mastershipService.getLocalRole(link.src().deviceId()) == MastershipRole.MASTER) {
+                    allocateAdjacencyLabel(link);
+                }
+                break;
+
+            case LINK_REMOVED:
+                // Release adjacency label
+                if (mastershipService.getLocalRole(link.src().deviceId()) == MastershipRole.MASTER) {
+                    releaseAdjacencyLabel(link);
+                }
+                break;
+
+            default:
+                break;
+            }
         }
     }
 
@@ -851,8 +1116,11 @@
 
             case TUNNEL_UPDATED:
                 // Allocate/send labels for basic PCECC tunnels.
-                if ((tunnel.state() == ESTABLISHED) && (lspType == WITHOUT_SIGNALLING_AND_WITHOUT_SR)) {
-                    crHandler.allocateLabel(tunnel);
+                if ((tunnel.state() == ESTABLISHED) && (lspType == WITHOUT_SIGNALLING_AND_WITHOUT_SR)
+                        && (mastershipService.getLocalRole(tunnel.path().src().deviceId()) == MastershipRole.MASTER)) {
+                    if (!crHandler.allocateLabel(tunnel)) {
+                        log.error("Unable to allocate labels for a tunnel {}.", tunnel.toString());
+                    }
                 }
 
                 if (tunnel.state() == UNSTABLE) {
@@ -899,7 +1167,9 @@
                         // Delete stored tunnel consumer id from PCE store (while still retaining label list.)
                         PceccTunnelInfo pceccTunnelInfo = pceStore.getTunnelInfo(tunnel.tunnelId());
                         pceccTunnelInfo.tunnelConsumerId(null);
-                        crHandler.releaseLabel(tunnel);
+                        if (mastershipService.getLocalRole(tunnel.path().src().deviceId()) == MastershipRole.MASTER) {
+                            crHandler.releaseLabel(tunnel);
+                        }
                     } else {
                         pceStore.removeTunnelInfo(tunnel.tunnelId());
                     }
@@ -914,8 +1184,62 @@
         }
     }
 
+    private class InternalConfigListener implements NetworkConfigListener {
+
+        @Override
+        public void event(NetworkConfigEvent event) {
+
+            if ((event.type() == NetworkConfigEvent.Type.CONFIG_ADDED)
+                    && event.configClass().equals(DeviceCapability.class)) {
+
+                DeviceId deviceIdLsrId = (DeviceId) event.subject();
+                String lsrId = deviceIdLsrId.toString();
+                DeviceId deviceId = lsrIdDeviceIdMap.get(lsrId);
+                if (deviceId == null) {
+                    log.debug("Unable to find device id for a lsr-id {} from lsr-id and device-id map.", lsrId);
+                    return;
+                }
+
+                DeviceCapability cfg = netCfgService.getConfig(DeviceId.deviceId(lsrId), DeviceCapability.class);
+                if (cfg == null) {
+                    log.error("Unable to find corresponding capabilty for a lsrd {}.", lsrId);
+                    return;
+                }
+
+                if (cfg.labelStackCap()) {
+                    if (mastershipService.getLocalRole(deviceId) == MastershipRole.MASTER) {
+                        // Allocate node-label
+                        if (!srTeHandler.allocateNodeLabel(deviceId, lsrId)) {
+                            log.error("Node label allocation for a device id {} has failed.", deviceId.toString());
+                        }
+
+                        // Allocate adjacency label to links which are
+                        // originated from this specific device id
+                        Set<Link> links = linkService.getDeviceEgressLinks(deviceId);
+                        for (Link link : links) {
+                            if (!srTeHandler.allocateAdjacencyLabel(link)) {
+                                log.debug("Unable to allocate adjacency labels for a link {}.", link.toString());
+                                return;
+                            }
+                        }
+                    }
+                }
+
+                // Remove lsrId info from map
+                lsrIdDeviceIdMap.remove(lsrId);
+            }
+        }
+    }
+
     private boolean syncLabelDb(DeviceId deviceId) {
         checkNotNull(deviceId);
+
+        Device specificDevice = deviceService.getDevice(deviceId);
+        if (specificDevice == null) {
+            log.error("Unable to find device for specific device id {}.", deviceId.toString());
+            return false;
+        }
+
         Map<DeviceId, LabelResourceId> globalNodeLabelMap = pceStore.getGlobalNodeLabels();
 
         for (Entry<DeviceId, LabelResourceId> entry : globalNodeLabelMap.entrySet()) {
@@ -957,6 +1281,18 @@
                                            LabelResourceId.labelResourceId(0),
                                            IpPrefix.valueOf(END_OF_SYNC_IP_PREFIX),
                                            Objective.Operation.ADD, true);
+        if (mastershipService.getLocalRole(specificDevice.id()) == MastershipRole.MASTER) {
+            // Allocate node-label to this specific device.
+            allocateNodeLabel(specificDevice);
+
+            // Allocate adjacency label
+            Set<Link> links = linkService.getDeviceEgressLinks(specificDevice.id());
+            if (links != null) {
+                for (Link link : links) {
+                    allocateAdjacencyLabel(link);
+                }
+            }
+        }
 
         return true;
     }
diff --git a/apps/pce/app/src/main/java/org/onosproject/pce/pceservice/PceccSrTeBeHandler.java b/apps/pce/app/src/main/java/org/onosproject/pce/pceservice/PceccSrTeBeHandler.java
index 24413c1..c760bc1 100644
--- a/apps/pce/app/src/main/java/org/onosproject/pce/pceservice/PceccSrTeBeHandler.java
+++ b/apps/pce/app/src/main/java/org/onosproject/pce/pceservice/PceccSrTeBeHandler.java
@@ -37,6 +37,8 @@
 import org.onosproject.incubator.net.resource.label.LabelResourceService;
 import org.onosproject.incubator.net.tunnel.DefaultLabelStack;
 import org.onosproject.incubator.net.tunnel.LabelStack;
+import org.onosproject.net.device.DeviceService;
+import org.onosproject.net.Device;
 import org.onosproject.net.DeviceId;
 import org.onosproject.pce.pcestore.api.PceStore;
 import org.onosproject.net.Link;
@@ -69,10 +71,8 @@
     private static final String LABEL_RESOURCE_ADMIN_SERVICE_NULL = "Label Resource Admin Service cannot be null";
     private static final String LABEL_RESOURCE_SERVICE_NULL = "Label Resource Service cannot be null";
     private static final String PCE_STORE_NULL = "PCE Store cannot be null";
-    private static final String DEVICE_SERVICE_NULL = "Device Service cannot be null";
     private static final String DEVICE_ID_NULL = "Device-Id cannot be null";
     private static final String LSR_ID_NULL = "LSR-Id cannot be null";
-    private static final String DEVICE_ID_LSR_ID_MAP_NULL = "Device-Id and LSR-Id map cannot be null";
     private static final String LINK_NULL = "Link cannot be null";
     private static final String PATH_NULL = "Path cannot be null";
     private static final String LSR_ID = "lsrId";
@@ -81,6 +81,7 @@
     private LabelResourceAdminService labelRsrcAdminService;
     private LabelResourceService labelRsrcService;
     private FlowObjectiveService flowObjectiveService;
+    private DeviceService deviceService;
     private PceStore pceStore;
     private ApplicationId appId;
 
@@ -110,16 +111,17 @@
      * @param flowObjectiveService flow objective service to push device label information
      * @param appId application id
      * @param pceStore PCE label store
+     * @param deviceService device service
      */
-    public void initialize(LabelResourceAdminService labelRsrcAdminService,
-                           LabelResourceService labelRsrcService,
-                           FlowObjectiveService flowObjectiveService,
-                           ApplicationId appId, PceStore pceStore) {
+    public void initialize(LabelResourceAdminService labelRsrcAdminService, LabelResourceService labelRsrcService,
+                           FlowObjectiveService flowObjectiveService, ApplicationId appId, PceStore pceStore,
+                           DeviceService deviceService) {
         this.labelRsrcAdminService = labelRsrcAdminService;
         this.labelRsrcService = labelRsrcService;
         this.flowObjectiveService = flowObjectiveService;
         this.pceStore = pceStore;
         this.appId = appId;
+        this.deviceService = deviceService;
     }
 
     /**
@@ -136,72 +138,102 @@
     }
 
     /**
+     * Retrieve lsr-id from device annotation.
+     *
+     * @param deviceId specific device id from which lsr-id needs to be retrieved
+     * @return lsr-id of a device
+     */
+    public String getLsrId(DeviceId deviceId) {
+        checkNotNull(deviceId, DEVICE_ID_NULL);
+        Device device = deviceService.getDevice(deviceId);
+        if (device == null) {
+            log.debug("Device is not available for device id {} in device service.", deviceId.toString());
+            return null;
+        }
+
+        // Retrieve lsr-id from device
+        if (device.annotations() == null) {
+            log.debug("Device {} does not have annotation.", device.toString());
+            return null;
+        }
+
+        String lsrId = device.annotations().value(LSR_ID);
+        if (lsrId == null) {
+            log.debug("The lsr-id of device {} is null.", device.toString());
+            return null;
+        }
+        return lsrId;
+    }
+
+    /**
      * Allocates node label from global node label pool to specific device.
      * Configure this device with labels and lsrid mapping of all other devices and vice versa.
      *
      * @param specificDeviceId node label needs to be allocated to specific device
      * @param specificLsrId lsrid of specific device
-     * @param deviceIdLsrIdMap deviceid and lsrid mapping
      * @return success or failure
      */
-    public boolean allocateNodeLabel(DeviceId specificDeviceId, String specificLsrId,
-                                     Map<DeviceId, String> deviceIdLsrIdMap) {
+    public boolean allocateNodeLabel(DeviceId specificDeviceId, String specificLsrId) {
         long applyNum = 1; // For each node only one node label
         LabelResourceId specificLabelId = null;
 
         checkNotNull(specificDeviceId, DEVICE_ID_NULL);
         checkNotNull(specificLsrId, LSR_ID_NULL);
-        checkNotNull(deviceIdLsrIdMap, DEVICE_ID_LSR_ID_MAP_NULL);
         checkNotNull(labelRsrcService, LABEL_RESOURCE_SERVICE_NULL);
         checkNotNull(pceStore, PCE_STORE_NULL);
 
-        // The specificDeviceId is the new device and is not there in the deviceIdLsrIdMap.
+        // Check whether node-label was already configured for this specific device.
+        if (pceStore.getGlobalNodeLabel(specificDeviceId) != null) {
+            log.error("Node label was already configured for device {}.", specificDeviceId.toString());
+            return false;
+        }
+
+        // The specificDeviceId is the new device and is not there in the pce store.
         // So, first generate its label and configure label and its lsr-id to it.
         Collection<LabelResource> result = labelRsrcService.applyFromGlobalPool(applyNum);
         if (result.size() > 0) {
-           // Only one element (label-id) to retrieve
-           Iterator<LabelResource> iterator = result.iterator();
-           DefaultLabelResource defaultLabelResource = (DefaultLabelResource) iterator.next();
-           specificLabelId = defaultLabelResource.labelResourceId();
-           if (specificLabelId == null) {
-              log.error("Unable to retrieve global node label for a device id {}.", specificDeviceId.toString());
-              return false;
-           }
+            // Only one element (label-id) to retrieve
+            Iterator<LabelResource> iterator = result.iterator();
+            DefaultLabelResource defaultLabelResource = (DefaultLabelResource) iterator.next();
+            specificLabelId = defaultLabelResource.labelResourceId();
+            if (specificLabelId == null) {
+                log.error("Unable to retrieve global node label for a device id {}.", specificDeviceId.toString());
+                return false;
+            }
         } else {
-           log.error("Unable to allocate global node label for a device id {}.", specificDeviceId.toString());
-           return false;
+            log.error("Unable to allocate global node label for a device id {}.", specificDeviceId.toString());
+            return false;
         }
 
+        // store it
         pceStore.addGlobalNodeLabel(specificDeviceId, specificLabelId);
+
         // Push its label information into specificDeviceId
         advertiseNodeLabelRule(specificDeviceId, specificLabelId,
                                IpPrefix.valueOf(IpAddress.valueOf(specificLsrId), PREFIX_LENGTH),
                                Objective.Operation.ADD, false);
 
-        // Configure (node-label, lsr-id) mapping of each devices in list to specific device and vice versa.
-        for (Map.Entry<DeviceId, String> element:deviceIdLsrIdMap.entrySet()) {
-           DeviceId otherDevId = element.getKey();
-           String otherLsrId = element.getValue();
-           if (otherLsrId == null) {
-               log.error("The lsr-id of device id {} is null.", otherDevId.toString());
-               releaseNodeLabel(specificDeviceId, specificLsrId, deviceIdLsrIdMap);
-               return false;
-           }
+        // Configure (node-label, lsr-id) mapping of each devices into specific device and vice versa.
+        for (Map.Entry<DeviceId, LabelResourceId> element : pceStore.getGlobalNodeLabels().entrySet()) {
+            DeviceId otherDevId = element.getKey();
+            LabelResourceId otherLabelId = element.getValue();
 
-           // Label for other device in list should be already allocated.
-           LabelResourceId otherLabelId = pceStore.getGlobalNodeLabel(otherDevId);
-           if (otherLabelId == null) {
-              log.error("Unable to find global node label in store for a device id {}.", otherDevId.toString());
-              releaseNodeLabel(specificDeviceId, specificLsrId, deviceIdLsrIdMap);
-              return false;
-           }
+            // Get lsr-id of a device
+            String otherLsrId = getLsrId(otherDevId);
+            if (otherLsrId == null) {
+                log.error("The lsr-id of device id {} is null.", otherDevId.toString());
+                releaseNodeLabel(specificDeviceId, specificLsrId);
+                return false;
+            }
 
-           // Push to device
-           // Push label information of specificDeviceId to otherDevId in list and vice versa.
-           advertiseNodeLabelRule(otherDevId, specificLabelId, IpPrefix.valueOf(IpAddress.valueOf(specificLsrId),
-                                  PREFIX_LENGTH), Objective.Operation.ADD, false);
-           advertiseNodeLabelRule(specificDeviceId, otherLabelId, IpPrefix.valueOf(IpAddress.valueOf(otherLsrId),
-                                  PREFIX_LENGTH), Objective.Operation.ADD, false);
+            // Push to device
+            // Push label information of specificDeviceId to otherDevId in list and vice versa.
+            advertiseNodeLabelRule(otherDevId, specificLabelId,
+                                   IpPrefix.valueOf(IpAddress.valueOf(specificLsrId), PREFIX_LENGTH),
+                                   Objective.Operation.ADD, false);
+            advertiseNodeLabelRule(specificDeviceId, otherLabelId,
+                                   IpPrefix.valueOf(IpAddress.valueOf(otherLsrId), PREFIX_LENGTH),
+                                   Objective.Operation.ADD, false);
         }
 
         return true;
@@ -213,14 +245,11 @@
      *
      * @param specificDeviceId node label needs to be released for specific device
      * @param specificLsrId lsrid of specific device
-     * @param deviceIdLsrIdMap deviceid and lsrid mapping
      * @return success or failure
      */
-    public boolean releaseNodeLabel(DeviceId specificDeviceId, String specificLsrId,
-                                    Map<DeviceId, String> deviceIdLsrIdMap) {
+    public boolean releaseNodeLabel(DeviceId specificDeviceId, String specificLsrId) {
         checkNotNull(specificDeviceId, DEVICE_ID_NULL);
         checkNotNull(specificLsrId, LSR_ID_NULL);
-        checkNotNull(deviceIdLsrIdMap, DEVICE_ID_LSR_ID_MAP_NULL);
         checkNotNull(labelRsrcService, LABEL_RESOURCE_SERVICE_NULL);
         checkNotNull(pceStore, PCE_STORE_NULL);
         boolean retValue = true;
@@ -229,20 +258,21 @@
         // Retrieve node label of this specific device from store
         LabelResourceId labelId = pceStore.getGlobalNodeLabel(specificDeviceId);
         if (labelId == null) {
-           log.error("Unable to retrieve label of a device id {} from store.", specificDeviceId.toString());
-           return false;
+            log.error("Unable to retrieve label of a device id {} from store.", specificDeviceId.toString());
+            return false;
         }
 
-        // Go through all devices in the map and remove label entry
-        for (Map.Entry<DeviceId, String> element:deviceIdLsrIdMap.entrySet()) {
-           DeviceId otherDevId = element.getKey();
+        // Go through all devices in the pce store and remove label entry from device
+        for (Map.Entry<DeviceId, LabelResourceId> element : pceStore.getGlobalNodeLabels().entrySet()) {
+            DeviceId otherDevId = element.getKey();
 
-           // Remove this specific device label information from all other nodes except
-           // this specific node where connection already lost.
-           if (!specificDeviceId.equals(otherDevId)) {
-              advertiseNodeLabelRule(otherDevId, labelId, IpPrefix.valueOf(IpAddress.valueOf(specificLsrId),
-                                     PREFIX_LENGTH), Objective.Operation.REMOVE, false);
-           }
+            // Remove this specific device label information from all other nodes except
+            // this specific node where connection already lost.
+            if (!specificDeviceId.equals(otherDevId)) {
+                advertiseNodeLabelRule(otherDevId, labelId,
+                                       IpPrefix.valueOf(IpAddress.valueOf(specificLsrId), PREFIX_LENGTH),
+                                       Objective.Operation.REMOVE, false);
+            }
         }
 
         // Release from label manager
@@ -277,24 +307,30 @@
         checkNotNull(labelRsrcService, LABEL_RESOURCE_SERVICE_NULL);
         checkNotNull(pceStore, PCE_STORE_NULL);
 
+        // Checks whether adjacency label was already allocated
+        LabelResourceId labelId = pceStore.getAdjLabel(link);
+        if (labelId != null) {
+            log.debug("Adjacency label {} was already allocated for a link {}.", labelId.toString(), link.toString());
+            return false;
+        }
+
         // Allocate adjacency label to a link from label manager.
         // Take label from source device pool to allocate.
         labelList = labelRsrcService.applyFromDevicePool(srcDeviceId, applyNum);
         if (labelList.size() <= 0) {
-           log.error("Unable to allocate label to a device id {}.", srcDeviceId.toString());
-           return false;
+            log.error("Unable to allocate label to a device id {}.", srcDeviceId.toString());
+            return false;
         }
 
         // Currently only one label to a device. So, no need to iterate through list
         Iterator<LabelResource> iterator = labelList.iterator();
         DefaultLabelResource defaultLabelResource = (DefaultLabelResource) iterator.next();
-        LabelResourceId labelId = defaultLabelResource.labelResourceId();
+        labelId = defaultLabelResource.labelResourceId();
         if (labelId == null) {
-           log.error("Unable to allocate label to a device id {}.", srcDeviceId.toString());
-           return false;
+            log.error("Unable to allocate label to a device id {}.", srcDeviceId.toString());
+            return false;
         }
-        log.debug("Allocated adjacency label {} to a link {}.", labelId.toString(),
-                  link.toString());
+        log.debug("Allocated adjacency label {} to a link {}.", labelId.toString(), link.toString());
 
         // Push adjacency label to device
         installAdjLabelRule(srcDeviceId, labelId, link.src().port(), link.dst().port(), Objective.Operation.ADD);
@@ -304,46 +340,46 @@
         return true;
     }
 
-   /**
-     * Releases unused adjacency labels from device pools.
-     *
-     * @param link between devices
-     * @return success or failure
-     */
+    /**
+      * Releases unused adjacency labels from device pools.
+      *
+      * @param link between devices
+      * @return success or failure
+      */
     public boolean releaseAdjacencyLabel(Link link) {
-       checkNotNull(link, LINK_NULL);
-       checkNotNull(labelRsrcService, LABEL_RESOURCE_SERVICE_NULL);
-       checkNotNull(pceStore, PCE_STORE_NULL);
-       boolean retValue = true;
+        checkNotNull(link, LINK_NULL);
+        checkNotNull(labelRsrcService, LABEL_RESOURCE_SERVICE_NULL);
+        checkNotNull(pceStore, PCE_STORE_NULL);
+        boolean retValue = true;
 
-       // Retrieve link label from store
-       LabelResourceId labelId = pceStore.getAdjLabel(link);
-       if (labelId == null) {
-          log.error("Unabel to retrieve label for a link {} from store.", link.toString());
-          return false;
-       }
+        // Retrieve link label from store
+        LabelResourceId labelId = pceStore.getAdjLabel(link);
+        if (labelId == null) {
+            log.error("Unabel to retrieve label for a link {} from store.", link.toString());
+            return false;
+        }
 
-       // Device
-       DeviceId srcDeviceId = link.src().deviceId();
+        // Device
+        DeviceId srcDeviceId = link.src().deviceId();
 
-       // Release adjacency label from device
-       installAdjLabelRule(srcDeviceId, labelId, link.src().port(), link.dst().port(), Objective.Operation.REMOVE);
+        // Release adjacency label from device
+        installAdjLabelRule(srcDeviceId, labelId, link.src().port(), link.dst().port(), Objective.Operation.REMOVE);
 
-       // Release link label from label manager
-       Multimap<DeviceId, LabelResource> release = ArrayListMultimap.create();
-       DefaultLabelResource defaultLabelResource = new DefaultLabelResource(srcDeviceId, labelId);
-       release.put(srcDeviceId, defaultLabelResource);
-       if (!labelRsrcService.releaseToDevicePool(release)) {
-          log.error("Unable to release label id {} from label manager.", labelId.toString());
-          retValue = false;
-       }
+        // Release link label from label manager
+        Multimap<DeviceId, LabelResource> release = ArrayListMultimap.create();
+        DefaultLabelResource defaultLabelResource = new DefaultLabelResource(srcDeviceId, labelId);
+        release.put(srcDeviceId, defaultLabelResource);
+        if (!labelRsrcService.releaseToDevicePool(release)) {
+            log.error("Unable to release label id {} from label manager.", labelId.toString());
+            retValue = false;
+        }
 
-       // Remove adjacency label from store
-       if (!pceStore.removeAdjLabel(link)) {
-          log.error("Unable to remove adjacency label id {} from store.", labelId.toString());
-          retValue = false;
-       }
-       return retValue;
+        // Remove adjacency label from store
+        if (!pceStore.removeAdjLabel(link)) {
+            log.error("Unable to remove adjacency label id {} from store.", labelId.toString());
+            retValue = false;
+        }
+        return retValue;
     }
 
     /**
@@ -372,16 +408,16 @@
                 deviceId = link.src().deviceId();
                 nodeLabelId = pceStore.getGlobalNodeLabel(deviceId);
                 if (nodeLabelId == null) {
-                   log.error("Unable to find node label for a device id {} in store.", deviceId.toString());
-                   return null;
+                    log.error("Unable to find node label for a device id {} in store.", deviceId.toString());
+                    return null;
                 }
                 labelStack.add(nodeLabelId);
 
                 // Add adjacency label for this link
                 adjLabelId = pceStore.getAdjLabel(link);
                 if (adjLabelId == null) {
-                   log.error("Adjacency label id is null for a link {}.", link.toString());
-                   return null;
+                    log.error("Adjacency label id is null for a link {}.", link.toString());
+                    return null;
                 }
                 labelStack.add(adjLabelId);
             }
@@ -389,13 +425,13 @@
             // This is the last link in path
             // Add destination device label now.
             if (link != null) {
-               deviceId = link.dst().deviceId();
-               nodeLabelId = pceStore.getGlobalNodeLabel(deviceId);
-               if (nodeLabelId == null) {
-                  log.error("Unable to find node label for a device id {} in store.", deviceId.toString());
-                  return null;
-               }
-               labelStack.add(nodeLabelId);
+                deviceId = link.dst().deviceId();
+                nodeLabelId = pceStore.getGlobalNodeLabel(deviceId);
+                if (nodeLabelId == null) {
+                    log.error("Unable to find node label for a device id {} in store.", deviceId.toString());
+                    return null;
+                }
+                labelStack.add(nodeLabelId);
             }
         } else {
             log.debug("Empty link in path.");
@@ -418,15 +454,11 @@
 
         selectorBuilder.matchMplsLabel(MplsLabel.mplsLabel(labelId.id().intValue()));
 
-        TrafficTreatment treatment = DefaultTrafficTreatment.builder()
-                .build();
+        TrafficTreatment treatment = DefaultTrafficTreatment.builder().build();
 
         ForwardingObjective.Builder forwardingObjective = DefaultForwardingObjective.builder()
-                .withSelector(selectorBuilder.build())
-                .withTreatment(treatment)
-                .withFlag(ForwardingObjective.Flag.VERSATILE)
-                .fromApp(appId)
-                .makePermanent();
+                .withSelector(selectorBuilder.build()).withTreatment(treatment)
+                .withFlag(ForwardingObjective.Flag.VERSATILE).fromApp(appId).makePermanent();
 
         if (type.equals(Objective.Operation.ADD)) {
 
@@ -445,8 +477,8 @@
      * @param type type of operation
      * @param bBos is this the end of sync push
      */
-    public void advertiseNodeLabelRule(DeviceId deviceId, LabelResourceId labelId,
-                                        IpPrefix ipPrefix, Objective.Operation type, boolean bBos) {
+    public void advertiseNodeLabelRule(DeviceId deviceId, LabelResourceId labelId, IpPrefix ipPrefix,
+                                       Objective.Operation type, boolean bBos) {
         checkNotNull(flowObjectiveService);
         checkNotNull(appId);
         TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
@@ -458,15 +490,11 @@
             selectorBuilder.matchMplsBos(bBos);
         }
 
-        TrafficTreatment treatment = DefaultTrafficTreatment.builder()
-                .build();
+        TrafficTreatment treatment = DefaultTrafficTreatment.builder().build();
 
         ForwardingObjective.Builder forwardingObjective = DefaultForwardingObjective.builder()
-                .withSelector(selectorBuilder.build())
-                .withTreatment(treatment)
-                .withFlag(ForwardingObjective.Flag.VERSATILE)
-                .fromApp(appId)
-                .makePermanent();
+                .withSelector(selectorBuilder.build()).withTreatment(treatment)
+                .withFlag(ForwardingObjective.Flag.VERSATILE).fromApp(appId).makePermanent();
 
         if (type.equals(Objective.Operation.ADD)) {
             flowObjectiveService.forward(deviceId, forwardingObjective.add());
@@ -484,9 +512,8 @@
      * @param dstPortNum remote port of the adjacency
      * @param type type of operation
      */
-    public void installAdjLabelRule(DeviceId deviceId, LabelResourceId labelId,
-                                     PortNumber srcPortNum, PortNumber dstPortNum,
-                                     Objective.Operation type) {
+    public void installAdjLabelRule(DeviceId deviceId, LabelResourceId labelId, PortNumber srcPortNum,
+                                    PortNumber dstPortNum, Objective.Operation type) {
         checkNotNull(flowObjectiveService);
         checkNotNull(appId);
         TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
@@ -495,15 +522,11 @@
         selectorBuilder.matchTcpSrc(TpPort.tpPort((int) srcPortNum.toLong()));
         selectorBuilder.matchTcpDst(TpPort.tpPort((int) dstPortNum.toLong()));
 
-        TrafficTreatment treatment = DefaultTrafficTreatment.builder()
-                .build();
+        TrafficTreatment treatment = DefaultTrafficTreatment.builder().build();
 
         ForwardingObjective.Builder forwardingObjective = DefaultForwardingObjective.builder()
-                .withSelector(selectorBuilder.build())
-                .withTreatment(treatment)
-                .withFlag(ForwardingObjective.Flag.VERSATILE)
-                .fromApp(appId)
-                .makePermanent();
+                .withSelector(selectorBuilder.build()).withTreatment(treatment)
+                .withFlag(ForwardingObjective.Flag.VERSATILE).fromApp(appId).makePermanent();
 
         if (type.equals(Objective.Operation.ADD)) {
             flowObjectiveService.forward(deviceId, forwardingObjective.add());
diff --git a/apps/pce/app/src/test/java/org/onosproject/pce/pceservice/PceManagerTest.java b/apps/pce/app/src/test/java/org/onosproject/pce/pceservice/PceManagerTest.java
index 4b1faaf..602c328 100644
--- a/apps/pce/app/src/test/java/org/onosproject/pce/pceservice/PceManagerTest.java
+++ b/apps/pce/app/src/test/java/org/onosproject/pce/pceservice/PceManagerTest.java
@@ -1,12 +1,15 @@
 package org.onosproject.pce.pceservice;
 
 import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.notNullValue;
+import static org.hamcrest.Matchers.nullValue;
 import static org.hamcrest.core.Is.is;
 import static org.onlab.graph.GraphPathSearch.ALL_PATHS;
+import static org.onosproject.incubator.net.tunnel.Tunnel.State.ESTABLISHED;
+import static org.onosproject.incubator.net.tunnel.Tunnel.State.UNSTABLE;
 import static org.onosproject.net.Link.State.ACTIVE;
 import static org.onosproject.net.Link.Type.DIRECT;
-import static org.onosproject.pce.pceservice.constraint.CostConstraint.Type.COST;
-import static org.onosproject.pce.pceservice.constraint.CostConstraint.Type.TE_COST;
+import static org.onosproject.net.MastershipRole.MASTER;
 import static org.onosproject.net.resource.Resources.continuous;
 import static org.onosproject.pce.pceservice.LspType.SR_WITHOUT_SIGNALLING;
 import static org.onosproject.pce.pceservice.LspType.WITHOUT_SIGNALLING_AND_WITHOUT_SR;
@@ -19,11 +22,11 @@
 import static org.onosproject.pce.pceservice.PathComputationTest.DEVICE2;
 import static org.onosproject.pce.pceservice.PathComputationTest.DEVICE3;
 import static org.onosproject.pce.pceservice.PathComputationTest.DEVICE4;
+import static org.onosproject.pce.pceservice.PceManager.PCEP_PORT;
 import static org.onosproject.pce.pceservice.PcepAnnotationKeys.LOCAL_LSP_ID;
 import static org.onosproject.pce.pceservice.PcepAnnotationKeys.PLSP_ID;
-import static org.onosproject.incubator.net.tunnel.Tunnel.State.UNSTABLE;
-import static org.onosproject.incubator.net.tunnel.Tunnel.State.ESTABLISHED;
-import static org.onosproject.net.MastershipRole.MASTER;
+import static org.onosproject.pce.pceservice.constraint.CostConstraint.Type.COST;
+import static org.onosproject.pce.pceservice.constraint.CostConstraint.Type.TE_COST;
 
 import java.net.URISyntaxException;
 import java.util.Collection;
@@ -51,6 +54,7 @@
 import org.onosproject.core.DefaultApplicationId;
 import org.onosproject.core.IdGenerator;
 import org.onosproject.event.Event;
+import org.onosproject.incubator.net.resource.label.LabelResourceAdminService;
 import org.onosproject.incubator.net.resource.label.LabelResourceId;
 import org.onosproject.incubator.net.resource.label.LabelResourceService;
 import org.onosproject.incubator.net.tunnel.DefaultTunnel;
@@ -65,23 +69,25 @@
 import org.onosproject.net.Annotations;
 import org.onosproject.net.ConnectPoint;
 import org.onosproject.net.DefaultAnnotations;
+import org.onosproject.net.DefaultAnnotations.Builder;
 import org.onosproject.net.DefaultDevice;
 import org.onosproject.net.DefaultLink;
 import org.onosproject.net.Device;
-import org.onosproject.net.DefaultAnnotations.Builder;
-import org.onosproject.net.MastershipRole;
-import org.onosproject.net.device.DeviceServiceAdapter;
-import org.onosproject.net.flowobjective.ForwardingObjective;
 import org.onosproject.net.DeviceId;
 import org.onosproject.net.ElementId;
 import org.onosproject.net.Link;
+import org.onosproject.net.MastershipRole;
 import org.onosproject.net.Path;
 import org.onosproject.net.PortNumber;
 import org.onosproject.net.SparseAnnotations;
+import org.onosproject.net.device.DeviceEvent;
+import org.onosproject.net.device.DeviceListener;
+import org.onosproject.net.flowobjective.ForwardingObjective;
 import org.onosproject.net.intent.Constraint;
 import org.onosproject.net.intent.IntentId;
 import org.onosproject.net.intent.constraint.BandwidthConstraint;
 import org.onosproject.net.link.LinkEvent;
+import org.onosproject.net.link.LinkListener;
 import org.onosproject.net.packet.DefaultInboundPacket;
 import org.onosproject.net.packet.DefaultPacketContext;
 import org.onosproject.net.packet.InboundPacket;
@@ -106,15 +112,16 @@
 import org.onosproject.pce.pceservice.PathComputationTest.MockPathResourceService;
 import org.onosproject.pce.pceservice.constraint.CostConstraint;
 import org.onosproject.pce.pcestore.api.PceStore;
+import org.onosproject.pce.util.FlowObjServiceAdapter;
 import org.onosproject.pce.util.LabelResourceAdapter;
+import org.onosproject.pce.util.MockDeviceService;
+import org.onosproject.pce.util.MockLinkService;
 import org.onosproject.pce.util.PceStoreAdapter;
 import org.onosproject.pce.util.TunnelServiceAdapter;
 import org.onosproject.pcep.api.DeviceCapability;
-import org.onosproject.pce.util.FlowObjServiceAdapter;
 import org.onosproject.store.service.TestStorageService;
 
 import com.google.common.collect.ImmutableSet;
-import static org.onosproject.pce.pceservice.PceManager.PCEP_PORT;
 
 /**
  * Tests the functions of PceManager.
@@ -133,16 +140,22 @@
     private PacketService packetService = new MockPacketService();
     private MockDeviceService deviceService = new MockDeviceService();
     private MockNetConfigRegistryAdapter netConfigRegistry = new PathComputationTest.MockNetConfigRegistryAdapter();
+    private MockLinkService linkService = new MockLinkService();
     private MockFlowObjService flowObjectiveService = new MockFlowObjService();
     private PceStore pceStore = new PceStoreAdapter();
     private LabelResourceService labelResourceService = new LabelResourceAdapter();
+    private LabelResourceAdminService labelRsrcAdminService = new LabelResourceAdapter();
 
     public static ProviderId providerId = new ProviderId("pce", "foo");
     private static final String L3 = "L3";
     private static final String LSRID = "lsrId";
+    private static final String PCECC_CAPABILITY = "pceccCapability";
+    private static final String SR_CAPABILITY = "srCapability";
+    private static final String LABEL_STACK_CAPABILITY = "labelStackCapability";
 
     private TopologyGraph graph = null;
     private Device deviceD1, deviceD2, deviceD3, deviceD4;
+    private Device pcepDeviceD1, pcepDeviceD2, pcepDeviceD3, pcepDeviceD4;
     private Link link1, link2, link3, link4;
     protected static int flowsDownloaded;
     private TunnelListener tunnelListener;
@@ -162,7 +175,9 @@
         pceManager.storageService = storageService;
         pceManager.packetService = packetService;
         pceManager.deviceService = deviceService;
+        pceManager.linkService = linkService;
         pceManager.netCfgService = netConfigRegistry;
+        pceManager.labelRsrcAdminService = labelRsrcAdminService;
         pceManager.labelRsrcService = labelResourceService;
         pceManager.flowObjectiveService = flowObjectiveService;
         pceManager.pceStore = pceStore;
@@ -219,6 +234,7 @@
         DefaultAnnotations.Builder builderDev3 = DefaultAnnotations.builder();
         DefaultAnnotations.Builder builderDev4 = DefaultAnnotations.builder();
 
+        // Making L3 devices
         builderDev1.set(AnnotationKeys.TYPE, L3);
         builderDev1.set(LSRID, "1.1.1.1");
 
@@ -1254,6 +1270,86 @@
         assertThat(pathService.paths().iterator().next().cost(), is((double) 180));
     }
 
+    /*
+     * Tests node label allocation/removal in SR-TE case based on device event.
+     */
+    @Test
+    public void deviceEventTest() {
+        // Make four router topology with SR-TE capabilities.
+        build4RouterTopo(true, false, true, true, 0);
+
+        // Add new L3 device
+        DefaultAnnotations.Builder builderDev5 = DefaultAnnotations.builder();
+        builderDev5.set(AnnotationKeys.TYPE, L3);
+        builderDev5.set(LSRID, "5.5.5.5");
+
+        Device dev5 = new MockDevice(DeviceId.deviceId("P005"), builderDev5.build());
+        deviceService.addDevice(dev5);
+
+        // Add capability
+        DeviceCapability device5Cap = netConfigRegistry.addConfig(DeviceId.deviceId("5.5.5.5"), DeviceCapability.class);
+        device5Cap.setLabelStackCap(true)
+                .setLocalLabelCap(false)
+                .setSrCap(true)
+                .apply();
+
+        // Get listener
+        DeviceListener listener = deviceService.getListener();
+
+        // Generate Remove events
+        deviceService.removeDevice(dev5);
+        DeviceEvent event = new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, dev5);
+        listener.event(event);
+
+        assertThat(pceStore.getGlobalNodeLabel(dev5.id()), is(nullValue()));
+    }
+
+    /**
+     * Tests adjacency label allocation/removal in SR-TE case based on link event.
+     */
+    @Test
+    public void linkEventTest() {
+        // Make four router topology with SR-TE capabilities.
+        build4RouterTopo(true, false, true, true, 0);
+
+        // Get listener
+        LinkListener listener = linkService.getListener();
+
+        // Adding link3
+        linkService.addLink(link3);
+
+        // Generate events
+        LinkEvent event = new LinkEvent(LinkEvent.Type.LINK_ADDED, link3);
+        listener.event(event);
+
+        assertThat(pceStore.getAdjLabel(link3), is(notNullValue()));
+
+        // Adding link4
+        linkService.addLink(link4);
+
+        event = new LinkEvent(LinkEvent.Type.LINK_ADDED, link4);
+        listener.event(event);
+
+        assertThat(pceStore.getAdjLabel(link4), is(notNullValue()));
+
+        // Remove link3
+        linkService.removeLink(link3);
+
+        // Generate events
+        event = new LinkEvent(LinkEvent.Type.LINK_REMOVED, link3);
+        listener.event(event);
+
+        assertThat(pceStore.getAdjLabel(link3), is(nullValue()));
+
+        // Remove link4
+        linkService.removeLink(link4);
+
+        event = new LinkEvent(LinkEvent.Type.LINK_REMOVED, link4);
+        listener.event(event);
+
+        assertThat(pceStore.getAdjLabel(link4), is(nullValue()));
+    }
+
     @After
     public void tearDown() {
         pceManager.deactivate();
@@ -1264,6 +1360,9 @@
         pceManager.storageService = null;
         pceManager.packetService = null;
         pceManager.deviceService = null;
+        pceManager.linkService = null;
+        pceManager.netCfgService = null;
+        pceManager.labelRsrcAdminService = null;
         pceManager.labelRsrcService = null;
         pceManager.flowObjectiveService = null;
         pceManager.pceStore = null;
@@ -1441,6 +1540,7 @@
 
             return result.size() == 0 ? Collections.emptySet() : ImmutableSet.copyOf(result);
         }
+
         @Override
         public Iterable<Tunnel> getTunnels(DeviceId deviceId) {
             List<Tunnel> tunnelList = new LinkedList<>();
@@ -1483,29 +1583,6 @@
         }
     }
 
-    private class MockDeviceService extends DeviceServiceAdapter {
-        List<Device> devices = new LinkedList<>();
-
-        private void addDevice(Device dev) {
-            devices.add(dev);
-        }
-
-        @Override
-        public Device getDevice(DeviceId deviceId) {
-            for (Device dev : devices) {
-                if (dev.id().equals(deviceId)) {
-                    return dev;
-                }
-            }
-            return null;
-        }
-
-        @Override
-        public Iterable<Device> getAvailableDevices() {
-            return devices;
-        }
-    }
-
     private PacketProcessor pktProcessor = null;
 
     private class MockPacketService extends PacketServiceAdapter {
diff --git a/apps/pce/app/src/test/java/org/onosproject/pce/pceservice/PceccSrTeBeHandlerTest.java b/apps/pce/app/src/test/java/org/onosproject/pce/pceservice/PceccSrTeBeHandlerTest.java
index a49bb0b..70f7376 100644
--- a/apps/pce/app/src/test/java/org/onosproject/pce/pceservice/PceccSrTeBeHandlerTest.java
+++ b/apps/pce/app/src/test/java/org/onosproject/pce/pceservice/PceccSrTeBeHandlerTest.java
@@ -19,36 +19,44 @@
 import static org.hamcrest.Matchers.is;
 import static org.hamcrest.Matchers.notNullValue;
 import static org.hamcrest.Matchers.nullValue;
-
 import static org.onosproject.net.Link.Type.DIRECT;
+import static org.onosproject.pce.pceservice.PathComputationTest.D1;
+import static org.onosproject.pce.pceservice.PathComputationTest.D2;
+import static org.onosproject.pce.pceservice.PathComputationTest.D3;
+import static org.onosproject.pce.pceservice.PathComputationTest.D4;
+import static org.onosproject.pce.pceservice.PathComputationTest.D5;
 
-import java.util.HashMap;
 import java.util.Iterator;
-import java.util.Map;
 import java.util.List;
 import java.util.LinkedList;
 
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
-
 import org.onosproject.incubator.net.resource.label.LabelResourceId;
 import org.onosproject.core.ApplicationId;
 import org.onosproject.core.CoreService;
 import org.onosproject.incubator.net.resource.label.LabelResourceAdminService;
 import org.onosproject.incubator.net.resource.label.LabelResourceService;
 import org.onosproject.incubator.net.tunnel.LabelStack;
+import org.onosproject.net.AnnotationKeys;
+import org.onosproject.net.Annotations;
 import org.onosproject.net.ConnectPoint;
 import org.onosproject.net.DefaultAnnotations;
+import org.onosproject.net.DefaultDevice;
 import org.onosproject.net.DefaultPath;
+import org.onosproject.net.Device;
 import org.onosproject.net.DeviceId;
 import org.onosproject.net.PortNumber;
 import org.onosproject.net.flowobjective.FlowObjectiveService;
 import org.onosproject.net.Path;
+import org.onosproject.pce.pceservice.PathComputationTest.MockNetConfigRegistryAdapter;
 import org.onosproject.pce.pcestore.api.PceStore;
 import org.onosproject.net.provider.ProviderId;
 import org.onosproject.pce.util.LabelResourceAdapter;
 import org.onosproject.pce.util.PceStoreAdapter;
+import org.onosproject.pce.util.MockDeviceService;
+import org.onosproject.pcep.api.DeviceCapability;
 import org.onosproject.net.DefaultLink;
 import org.onosproject.net.Link;
 
@@ -59,20 +67,24 @@
 
     public static final long GLOBAL_LABEL_SPACE_MIN = 4097;
     public static final long GLOBAL_LABEL_SPACE_MAX = 5121;
+    private static final String L3 = "L3";
+    private static final String LSRID = "lsrId";
 
     private PceccSrTeBeHandler srTeHandler;
-    protected LabelResourceAdminService labelRsrcAdminService;
-    protected LabelResourceService labelRsrcService;
-    protected PceStore pceStore;
-    private FlowObjectiveService flowObjectiveService;
     private CoreService coreService;
+    private LabelResourceAdminService labelRsrcAdminService;
+    private LabelResourceService labelRsrcService;
+    private PceStore pceStore;
+    private MockDeviceService deviceService;
+    private FlowObjectiveService flowObjectiveService;
+    private MockNetConfigRegistryAdapter netCfgService = new PathComputationTest.MockNetConfigRegistryAdapter();
     private ApplicationId appId;
     private ProviderId providerId;
-    private DeviceId deviceId1;
-    private DeviceId deviceId2;
-    private DeviceId deviceId3;
-    private DeviceId deviceId4;
-    private DeviceId deviceId5;
+    private Device deviceD1;
+    private Device deviceD2;
+    private Device deviceD3;
+    private Device deviceD4;
+    private Device deviceD5;
     private PortNumber port1;
     private PortNumber port2;
     private PortNumber port3;
@@ -84,9 +96,6 @@
     private Link link4;
     private Path path1;
     LabelResourceId labelId;
-    private LabelResourceId labelId1 = LabelResourceId.labelResourceId(4098);
-    private LabelResourceId labelId2 = LabelResourceId.labelResourceId(4099);
-    private Map<DeviceId, String> deviceIdLsrIdMap;
 
     @Before
     public void setUp() throws Exception {
@@ -98,16 +107,64 @@
         coreService = new PceManagerTest.MockCoreService();
         appId = coreService.registerApplication("org.onosproject.pce");
         pceStore = new PceStoreAdapter();
-        srTeHandler.initialize(labelRsrcAdminService, labelRsrcService, flowObjectiveService, appId, pceStore);
+        deviceService = new MockDeviceService();
+        srTeHandler.initialize(labelRsrcAdminService, labelRsrcService, flowObjectiveService, appId, pceStore,
+                               deviceService);
 
         // Creates path
         // Creates list of links
         providerId = new ProviderId("of", "foo");
-        deviceId1 = DeviceId.deviceId("of:A");
-        deviceId2 = DeviceId.deviceId("of:B");
-        deviceId3 = DeviceId.deviceId("of:C");
-        deviceId4 = DeviceId.deviceId("of:D");
-        deviceId5 = DeviceId.deviceId("of:E");
+
+        // Devices
+        DefaultAnnotations.Builder builderDev1 = DefaultAnnotations.builder();
+        DefaultAnnotations.Builder builderDev2 = DefaultAnnotations.builder();
+        DefaultAnnotations.Builder builderDev3 = DefaultAnnotations.builder();
+        DefaultAnnotations.Builder builderDev4 = DefaultAnnotations.builder();
+        DefaultAnnotations.Builder builderDev5 = DefaultAnnotations.builder();
+
+        builderDev1.set(AnnotationKeys.TYPE, L3);
+        builderDev1.set(LSRID, "1.1.1.1");
+
+        builderDev2.set(AnnotationKeys.TYPE, L3);
+        builderDev2.set(LSRID, "2.2.2.2");
+
+        builderDev3.set(AnnotationKeys.TYPE, L3);
+        builderDev3.set(LSRID, "3.3.3.3");
+
+        builderDev4.set(AnnotationKeys.TYPE, L3);
+        builderDev4.set(LSRID, "4.4.4.4");
+
+        builderDev5.set(AnnotationKeys.TYPE, L3);
+        builderDev5.set(LSRID, "5.5.5.5");
+
+        deviceD1 = new MockDevice(D1.deviceId(), builderDev1.build());
+        deviceD2 = new MockDevice(D2.deviceId(), builderDev2.build());
+        deviceD3 = new MockDevice(D3.deviceId(), builderDev3.build());
+        deviceD4 = new MockDevice(D4.deviceId(), builderDev4.build());
+        deviceD5 = new MockDevice(D5.deviceId(), builderDev5.build());
+
+        deviceService.addDevice(deviceD1);
+        deviceService.addDevice(deviceD2);
+        deviceService.addDevice(deviceD3);
+        deviceService.addDevice(deviceD4);
+        deviceService.addDevice(deviceD5);
+
+        DeviceCapability device1Cap = netCfgService.addConfig(DeviceId.deviceId("1.1.1.1"), DeviceCapability.class);
+        device1Cap.setLabelStackCap(true).setLocalLabelCap(false).setSrCap(true).apply();
+
+        DeviceCapability device2Cap = netCfgService.addConfig(DeviceId.deviceId("2.2.2.2"), DeviceCapability.class);
+        device2Cap.setLabelStackCap(true).setLocalLabelCap(false).setSrCap(true).apply();
+
+        DeviceCapability device3Cap = netCfgService.addConfig(DeviceId.deviceId("3.3.3.3"), DeviceCapability.class);
+        device3Cap.setLabelStackCap(true).setLocalLabelCap(false).setSrCap(true).apply();
+
+        DeviceCapability device4Cap = netCfgService.addConfig(DeviceId.deviceId("4.4.4.4"), DeviceCapability.class);
+        device4Cap.setLabelStackCap(true).setLocalLabelCap(false).setSrCap(true).apply();
+
+        DeviceCapability device5Cap = netCfgService.addConfig(DeviceId.deviceId("5.5.5.5"), DeviceCapability.class);
+        device5Cap.setLabelStackCap(true).setLocalLabelCap(false).setSrCap(true).apply();
+
+        // Port Numbers
         port1 = PortNumber.portNumber(1);
         port2 = PortNumber.portNumber(2);
         port3 = PortNumber.portNumber(3);
@@ -115,41 +172,25 @@
         port5 = PortNumber.portNumber(5);
         List<Link> linkList = new LinkedList<>();
 
-        link1 = DefaultLink.builder()
-                .providerId(providerId)
+        link1 = DefaultLink.builder().providerId(providerId)
                 .annotations(DefaultAnnotations.builder().set("key1", "yahoo").build())
-                .src(new ConnectPoint(deviceId1, port1))
-                .dst(new ConnectPoint(deviceId2, port2))
-                .type(DIRECT)
-                .state(Link.State.ACTIVE)
-                .build();
+                .src(new ConnectPoint(deviceD1.id(), port1)).dst(new ConnectPoint(deviceD2.id(), port2)).type(DIRECT)
+                .state(Link.State.ACTIVE).build();
         linkList.add(link1);
-        link2 = DefaultLink.builder()
-                .providerId(providerId)
+        link2 = DefaultLink.builder().providerId(providerId)
                 .annotations(DefaultAnnotations.builder().set("key2", "yahoo").build())
-                .src(new ConnectPoint(deviceId2, port2))
-                .dst(new ConnectPoint(deviceId3, port3))
-                .type(DIRECT)
-                .state(Link.State.ACTIVE)
-                .build();
+                .src(new ConnectPoint(deviceD2.id(), port2)).dst(new ConnectPoint(deviceD3.id(), port3)).type(DIRECT)
+                .state(Link.State.ACTIVE).build();
         linkList.add(link2);
-        link3 = DefaultLink.builder()
-                .providerId(providerId)
+        link3 = DefaultLink.builder().providerId(providerId)
                 .annotations(DefaultAnnotations.builder().set("key3", "yahoo").build())
-                .src(new ConnectPoint(deviceId3, port3))
-                .dst(new ConnectPoint(deviceId4, port4))
-                .type(DIRECT)
-                .state(Link.State.ACTIVE)
-                .build();
+                .src(new ConnectPoint(deviceD3.id(), port3)).dst(new ConnectPoint(deviceD4.id(), port4)).type(DIRECT)
+                .state(Link.State.ACTIVE).build();
         linkList.add(link3);
-        link4 = DefaultLink.builder()
-                .providerId(providerId)
+        link4 = DefaultLink.builder().providerId(providerId)
                 .annotations(DefaultAnnotations.builder().set("key4", "yahoo").build())
-                .src(new ConnectPoint(deviceId4, port4))
-                .dst(new ConnectPoint(deviceId5, port5))
-                .type(DIRECT)
-                .state(Link.State.ACTIVE)
-                .build();
+                .src(new ConnectPoint(deviceD4.id(), port4)).dst(new ConnectPoint(deviceD5.id(), port5)).type(DIRECT)
+                .state(Link.State.ACTIVE).build();
         linkList.add(link4);
 
         // Path
@@ -174,127 +215,60 @@
      */
     @Test
     public void testReserveGlobalPool() {
-        assertThat(srTeHandler.reserveGlobalPool(GLOBAL_LABEL_SPACE_MIN,
-                GLOBAL_LABEL_SPACE_MAX), is(true));
+        assertThat(srTeHandler.reserveGlobalPool(GLOBAL_LABEL_SPACE_MIN, GLOBAL_LABEL_SPACE_MAX), is(true));
     }
 
     /**
      * Checks the operation of allocateNodeLabel() method on node label.
-     * Considered some nodes are already available before PceManager came up.
      */
     @Test
-    public void testAllocateNodeLabel1() {
-        // Specific device deviceId1
-
-        // Devices mapping with lsr-id
-        deviceIdLsrIdMap = new HashMap<>();
+    public void testAllocateNodeLabel() {
+        // Specific device D1.deviceId
 
         //device 1
         String lsrId1 = "11.1.1.1";
-        deviceIdLsrIdMap.put(deviceId1, lsrId1);
+        // Allocate node label for specific device D1deviceId
+        assertThat(srTeHandler.allocateNodeLabel(D1.deviceId(), lsrId1), is(true));
+        // Retrieve label from store
+        LabelResourceId labelId = pceStore.getGlobalNodeLabel(D1.deviceId());
+        // Check whether label is generated for this device D1.deviceId()
+        assertThat(labelId, is(notNullValue()));
 
         // device 2
         String lsrId2 = "12.1.1.1";
-        deviceIdLsrIdMap.put(deviceId2, lsrId2);
+        // Allocate node label for specific device D2.deviceId()
+        assertThat(srTeHandler.allocateNodeLabel(D2.deviceId(), lsrId2), is(true));
+        // Retrieve label from store
+        labelId = pceStore.getGlobalNodeLabel(D2.deviceId());
+        // Check whether label is generated for this device D2.deviceId()
+        assertThat(labelId, is(notNullValue()));
 
         // device 3
         String lsrId3 = "13.1.1.1";
-        deviceIdLsrIdMap.put(deviceId3, lsrId3);
+        // Allocate node label for specific device D3.deviceId()
+        assertThat(srTeHandler.allocateNodeLabel(D3.deviceId(), lsrId3), is(true));
+        // Retrieve label from store
+        labelId = pceStore.getGlobalNodeLabel(D3.deviceId());
+        // Check whether label is generated for this device D3.deviceId()
+        assertThat(labelId, is(notNullValue()));
 
         // device 4
         String lsrId4 = "14.1.1.1";
-        deviceIdLsrIdMap.put(deviceId4, lsrId4);
+        // Allocate node label for specific device D4.deviceId()
+        assertThat(srTeHandler.allocateNodeLabel(D4.deviceId(), lsrId4), is(true));
+        // Retrieve label from store
+        labelId = pceStore.getGlobalNodeLabel(D4.deviceId());
+        // Check whether label is generated for this device D4.deviceId()
+        assertThat(labelId, is(notNullValue()));
 
         // device 5
         String lsrId5 = "15.1.1.1";
-        deviceIdLsrIdMap.put(deviceId5, lsrId5);
-
-        // Considered devices are stored in deviceIdLsrIdMap.
-        // Creating temporary tempDeviceIdLsrIdMap to pass to allocateNodeLabel()
-        Map<DeviceId, String> tempDeviceIdLsrIdMap = new HashMap<>();
-        for (Map.Entry element : deviceIdLsrIdMap.entrySet()) {
-            DeviceId devId = (DeviceId) element.getKey();
-            String lsrId = (String) element.getValue();
-
-            // Allocate node label for specific device devId
-            assertThat(srTeHandler.allocateNodeLabel(devId, lsrId, tempDeviceIdLsrIdMap), is(true));
-
-            // Retrieve label from store
-            LabelResourceId labelId = pceStore.getGlobalNodeLabel(devId);
-
-            // Check whether label is generated for this device devId
-            assertThat(labelId, is(notNullValue()));
-
-            //Now add device to tempDeviceIdLsrIdMap
-            tempDeviceIdLsrIdMap.put(devId, lsrId);
-        }
-    }
-
-    /**
-     * Checks the operation of allocateNodeLabel() method on node label.
-     * Considered initially map is empty and keep on getting new devices from event.
-     */
-    @Test
-    public void testAllocateNodeLabel2() {
-        // Specific device deviceId1
-
-        // Device-id mapping with lsr-id
-        deviceIdLsrIdMap = new HashMap<>();
-
-        //device 1
-        String lsrId1 = "11.1.1.1";
-        // Allocate node label for specific device deviceId1
-        assertThat(srTeHandler.allocateNodeLabel(deviceId1, lsrId1, deviceIdLsrIdMap), is(true));
+        // Allocate node label for specific device D5.deviceId()
+        assertThat(srTeHandler.allocateNodeLabel(D5.deviceId(), lsrId5), is(true));
         // Retrieve label from store
-        LabelResourceId labelId = pceStore.getGlobalNodeLabel(deviceId1);
-        // Check whether label is generated for this device deviceId1
+        labelId = pceStore.getGlobalNodeLabel(D5.deviceId());
+        // Check whether label is generated for this device D5.deviceId()
         assertThat(labelId, is(notNullValue()));
-        //Now add device to deviceIdLsrIdMap
-        deviceIdLsrIdMap.put(deviceId1, lsrId1);
-
-        // device 2
-        String lsrId2 = "12.1.1.1";
-        // Allocate node label for specific device deviceId2
-        assertThat(srTeHandler.allocateNodeLabel(deviceId2, lsrId2, deviceIdLsrIdMap), is(true));
-        // Retrieve label from store
-        labelId = pceStore.getGlobalNodeLabel(deviceId2);
-        // Check whether label is generated for this device deviceId2
-        assertThat(labelId, is(notNullValue()));
-        //Now add device to deviceIdLsrIdMap
-        deviceIdLsrIdMap.put(deviceId2, lsrId2);
-
-        // device 3
-        String lsrId3 = "13.1.1.1";
-        // Allocate node label for specific device deviceId3
-        assertThat(srTeHandler.allocateNodeLabel(deviceId3, lsrId3, deviceIdLsrIdMap), is(true));
-        // Retrieve label from store
-        labelId = pceStore.getGlobalNodeLabel(deviceId3);
-        // Check whether label is generated for this device deviceId3
-        assertThat(labelId, is(notNullValue()));
-        //Now add device to deviceIdLsrIdMap
-        deviceIdLsrIdMap.put(deviceId3, lsrId3);
-
-        // device 4
-        String lsrId4 = "14.1.1.1";
-        // Allocate node label for specific device deviceId4
-        assertThat(srTeHandler.allocateNodeLabel(deviceId4, lsrId4, deviceIdLsrIdMap), is(true));
-        // Retrieve label from store
-        labelId = pceStore.getGlobalNodeLabel(deviceId4);
-        // Check whether label is generated for this device deviceId4
-        assertThat(labelId, is(notNullValue()));
-        //Now add device to deviceIdLsrIdMap
-        deviceIdLsrIdMap.put(deviceId4, lsrId4);
-
-        // device 5
-        String lsrId5 = "15.1.1.1";
-        // Allocate node label for specific device deviceId5
-        assertThat(srTeHandler.allocateNodeLabel(deviceId5, lsrId5, deviceIdLsrIdMap), is(true));
-        // Retrieve label from store
-        labelId = pceStore.getGlobalNodeLabel(deviceId5);
-        // Check whether label is generated for this device deviceId5
-        assertThat(labelId, is(notNullValue()));
-        //Now add device to deviceIdLsrIdMap
-        deviceIdLsrIdMap.put(deviceId5, lsrId5);
     }
 
     /**
@@ -302,69 +276,59 @@
      */
     @Test
     public void testReleaseNodeLabelSuccess() {
-        testAllocateNodeLabel2();
-        // Specific device deviceId1
+        testAllocateNodeLabel();
+        // Specific device D1.deviceId()
 
         //device 1
         String lsrId1 = "11.1.1.1";
         // Check whether successfully released node label
-        assertThat(srTeHandler.releaseNodeLabel(deviceId1, lsrId1, deviceIdLsrIdMap), is(true));
+        assertThat(srTeHandler.releaseNodeLabel(D1.deviceId(), lsrId1), is(true));
         // Check whether successfully removed label from store
-        LabelResourceId labelId = pceStore.getGlobalNodeLabel(deviceId1);
+        LabelResourceId labelId = pceStore.getGlobalNodeLabel(D1.deviceId());
         assertThat(labelId, is(nullValue()));
-        // Remove released deviceId1
-        deviceIdLsrIdMap.remove(deviceId1);
 
         //device 2
         String lsrId2 = "12.1.1.1";
         // Check whether successfully released node label
-        assertThat(srTeHandler.releaseNodeLabel(deviceId2, lsrId2, deviceIdLsrIdMap), is(true));
+        assertThat(srTeHandler.releaseNodeLabel(D2.deviceId(), lsrId2), is(true));
         // Check whether successfully removed label from store
-        labelId = pceStore.getGlobalNodeLabel(deviceId2);
+        labelId = pceStore.getGlobalNodeLabel(D2.deviceId());
         assertThat(labelId, is(nullValue()));
-        // Remove released deviceId2
-        deviceIdLsrIdMap.remove(deviceId2);
 
         //device 3
         String lsrId3 = "13.1.1.1";
         // Check whether successfully released node label
-        assertThat(srTeHandler.releaseNodeLabel(deviceId3, lsrId3, deviceIdLsrIdMap), is(true));
+        assertThat(srTeHandler.releaseNodeLabel(D3.deviceId(), lsrId3), is(true));
         // Check whether successfully removed label from store
-        labelId = pceStore.getGlobalNodeLabel(deviceId3);
+        labelId = pceStore.getGlobalNodeLabel(D3.deviceId());
         assertThat(labelId, is(nullValue()));
-        // Remove released deviceId3
-        deviceIdLsrIdMap.remove(deviceId3);
 
         //device 4
         String lsrId4 = "14.1.1.1";
         // Check whether successfully released node label
-        assertThat(srTeHandler.releaseNodeLabel(deviceId4, lsrId4, deviceIdLsrIdMap), is(true));
+        assertThat(srTeHandler.releaseNodeLabel(D4.deviceId(), lsrId4), is(true));
         // Check whether successfully removed label from store
-        labelId = pceStore.getGlobalNodeLabel(deviceId4);
+        labelId = pceStore.getGlobalNodeLabel(D4.deviceId());
         assertThat(labelId, is(nullValue()));
-        // Remove released deviceId4
-        deviceIdLsrIdMap.remove(deviceId4);
 
         //device 5
         String lsrId5 = "15.1.1.1";
         // Check whether successfully released node label
-        assertThat(srTeHandler.releaseNodeLabel(deviceId5, lsrId5, deviceIdLsrIdMap), is(true));
+        assertThat(srTeHandler.releaseNodeLabel(D5.deviceId(), lsrId5), is(true));
         // Check whether successfully removed label from store
-        labelId = pceStore.getGlobalNodeLabel(deviceId5);
+        labelId = pceStore.getGlobalNodeLabel(D5.deviceId());
         assertThat(labelId, is(nullValue()));
-        // Remove released deviceId5
-        deviceIdLsrIdMap.remove(deviceId5);
     }
 
     @Test
     public void testReleaseNodeLabelFailure() {
-        testAllocateNodeLabel2();
+        testAllocateNodeLabel();
 
         //device 6
         String lsrId6 = "16.1.1.1";
         // Check whether successfully released node label
         DeviceId deviceId6 = DeviceId.deviceId("foo6");
-        assertThat(srTeHandler.releaseNodeLabel(deviceId6, lsrId6, deviceIdLsrIdMap), is(false));
+        assertThat(srTeHandler.releaseNodeLabel(deviceId6, lsrId6), is(false));
     }
 
     /**
@@ -430,15 +394,15 @@
     public void testComputeLabelStack() {
         // Allocate node labels to each devices
         labelId = LabelResourceId.labelResourceId(4097);
-        pceStore.addGlobalNodeLabel(deviceId1, labelId);
+        pceStore.addGlobalNodeLabel(D1.deviceId(), labelId);
         labelId = LabelResourceId.labelResourceId(4098);
-        pceStore.addGlobalNodeLabel(deviceId2, labelId);
+        pceStore.addGlobalNodeLabel(D2.deviceId(), labelId);
         labelId = LabelResourceId.labelResourceId(4099);
-        pceStore.addGlobalNodeLabel(deviceId3, labelId);
+        pceStore.addGlobalNodeLabel(D3.deviceId(), labelId);
         labelId = LabelResourceId.labelResourceId(4100);
-        pceStore.addGlobalNodeLabel(deviceId4, labelId);
+        pceStore.addGlobalNodeLabel(D4.deviceId(), labelId);
         labelId = LabelResourceId.labelResourceId(4101);
-        pceStore.addGlobalNodeLabel(deviceId5, labelId);
+        pceStore.addGlobalNodeLabel(D5.deviceId(), labelId);
 
         // Allocate adjacency labels to each devices
         labelId = LabelResourceId.labelResourceId(5122);
@@ -453,42 +417,48 @@
         // Compute label stack
         LabelStack labelStack = srTeHandler.computeLabelStack(path1);
 
-        // check node-label of deviceId1
+        // check node-label of D1.deviceId()
         List<LabelResourceId> labelList = labelStack.labelResources();
         Iterator<LabelResourceId> iterator = labelList.iterator();
         labelId = iterator.next();
         assertThat(labelId, is(LabelResourceId.labelResourceId(4097)));
 
-        // check adjacency label of deviceId1
+        // check adjacency label of D1.deviceId()
         labelId = iterator.next();
         assertThat(labelId, is(LabelResourceId.labelResourceId(5122)));
 
-        // check node-label of deviceId2
+        // check node-label of D2.deviceId()
         labelId = iterator.next();
         assertThat(labelId, is(LabelResourceId.labelResourceId(4098)));
 
-        // check adjacency label of deviceId2
+        // check adjacency label of D2.deviceId()
         labelId = iterator.next();
         assertThat(labelId, is(LabelResourceId.labelResourceId(5123)));
 
-        // check node-label of deviceId3
+        // check node-label of D3.deviceId()
         labelId = iterator.next();
         assertThat(labelId, is(LabelResourceId.labelResourceId(4099)));
 
-        // check adjacency label of deviceId3
+        // check adjacency label of D3.deviceId()
         labelId = iterator.next();
         assertThat(labelId, is(LabelResourceId.labelResourceId(5124)));
 
-        // check node-label of deviceId4
+        // check node-label of D4.deviceId()
         labelId = iterator.next();
         assertThat(labelId, is(LabelResourceId.labelResourceId(4100)));
 
-        // check adjacency label of deviceId4
+        // check adjacency label of D4.deviceId()
         labelId = iterator.next();
         assertThat(labelId, is(LabelResourceId.labelResourceId(5125)));
 
-        // check node-label of deviceId5
+        // check node-label of D5.deviceId()
         labelId = iterator.next();
         assertThat(labelId, is(LabelResourceId.labelResourceId(4101)));
     }
+
+    private class MockDevice extends DefaultDevice {
+        MockDevice(DeviceId id, Annotations annotations) {
+            super(null, id, null, null, null, null, null, null, annotations);
+        }
+    }
 }
diff --git a/apps/pce/app/src/test/java/org/onosproject/pce/util/LinkServiceAdapter.java b/apps/pce/app/src/test/java/org/onosproject/pce/util/LinkServiceAdapter.java
new file mode 100644
index 0000000..3673fc9
--- /dev/null
+++ b/apps/pce/app/src/test/java/org/onosproject/pce/util/LinkServiceAdapter.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright 2016-present 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.pce.util;
+
+import java.util.Set;
+
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.Link;
+import org.onosproject.net.link.LinkListener;
+import org.onosproject.net.link.LinkService;
+import org.onosproject.net.Link.State;
+
+import com.google.common.collect.FluentIterable;
+
+/**
+ * Test adapter for link service.
+ */
+public class LinkServiceAdapter implements LinkService {
+    @Override
+    public int getLinkCount() {
+        return 0;
+    }
+
+    @Override
+    public Iterable<Link> getLinks() {
+        return null;
+    }
+
+    @Override
+    public Iterable<Link> getActiveLinks() {
+        return FluentIterable.from(getLinks())
+                .filter(input -> input.state() == State.ACTIVE);
+    }
+
+    @Override
+    public Set<Link> getDeviceLinks(DeviceId deviceId) {
+        return null;
+    }
+
+    @Override
+    public Set<Link> getDeviceEgressLinks(DeviceId deviceId) {
+        return null;
+    }
+
+    @Override
+    public Set<Link> getDeviceIngressLinks(DeviceId deviceId) {
+        return null;
+    }
+
+    @Override
+    public Set<Link> getLinks(ConnectPoint connectPoint) {
+        return null;
+    }
+
+    @Override
+    public Set<Link> getEgressLinks(ConnectPoint connectPoint) {
+        return null;
+    }
+
+    @Override
+    public Set<Link> getIngressLinks(ConnectPoint connectPoint) {
+        return null;
+    }
+
+    @Override
+    public Link getLink(ConnectPoint src, ConnectPoint dst) {
+        return null;
+    }
+
+    @Override
+    public void addListener(LinkListener listener) {
+    }
+
+    @Override
+    public void removeListener(LinkListener listener) {
+    }
+}
diff --git a/apps/pce/app/src/test/java/org/onosproject/pce/util/MockDeviceService.java b/apps/pce/app/src/test/java/org/onosproject/pce/util/MockDeviceService.java
new file mode 100644
index 0000000..a0ed08b
--- /dev/null
+++ b/apps/pce/app/src/test/java/org/onosproject/pce/util/MockDeviceService.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2016-present 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.pce.util;
+
+import java.util.LinkedList;
+import java.util.List;
+
+import org.onosproject.net.device.DeviceListener;
+import org.onosproject.net.device.DeviceServiceAdapter;
+import org.onosproject.net.Device;
+import org.onosproject.net.DeviceId;
+
+/**
+ * Test fixture for the device service.
+ */
+public class MockDeviceService extends DeviceServiceAdapter {
+    private List<Device> devices = new LinkedList<>();
+    private DeviceListener listener;
+
+    public void addDevice(Device dev) {
+        devices.add(dev);
+    }
+
+    public void removeDevice(Device dev) {
+        devices.remove(dev);
+    }
+
+    @Override
+    public Device getDevice(DeviceId deviceId) {
+        for (Device dev : devices) {
+            if (dev.id().equals(deviceId)) {
+                return dev;
+            }
+        }
+        return null;
+    }
+
+    @Override
+    public Iterable<Device> getAvailableDevices() {
+        return devices;
+    }
+
+    @Override
+    public void addListener(DeviceListener listener) {
+        this.listener = listener;
+    }
+
+    /**
+     * Get the listener.
+     */
+    public DeviceListener getListener() {
+        return listener;
+    }
+}
diff --git a/apps/pce/app/src/test/java/org/onosproject/pce/util/MockLinkService.java b/apps/pce/app/src/test/java/org/onosproject/pce/util/MockLinkService.java
new file mode 100644
index 0000000..30b696a
--- /dev/null
+++ b/apps/pce/app/src/test/java/org/onosproject/pce/util/MockLinkService.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright 2016-present 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.pce.util;
+
+import org.onosproject.net.Link;
+import org.onosproject.net.link.LinkServiceAdapter;
+import org.onosproject.net.link.LinkListener;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Test fixture for the link service.
+ */
+public class MockLinkService extends LinkServiceAdapter {
+    List<Link> links = new ArrayList<>();
+    LinkListener listener;
+
+    @Override
+    public int getLinkCount() {
+        return links.size();
+    }
+
+    @Override
+    public Iterable<Link> getLinks() {
+        return links;
+    }
+
+    @Override
+    public void addListener(LinkListener listener) {
+        this.listener = listener;
+    }
+
+    /**
+     * Get listener.
+     */
+    public LinkListener getListener() {
+        return listener;
+    }
+
+    /**
+     * Add link.
+     *
+     * @param link needs to be added to list
+     */
+    public void addLink(Link link) {
+        links.add(link);
+    }
+
+    /**
+     * Delete link.
+     *
+     * @param link needs to be deleted from list
+     */
+    public void removeLink(Link link) {
+        links.remove(link);
+    }
+}