[ONOS-4513] Move optical Intent compilers out to optical-model (3/3)

- core/net is now optical clean
- reverting part of Change-Id: Ib8ddac6e93327ade9d42984d8eba66be7047d051
 which lead to loss of package import information, causing OSGi issue

Change-Id: Ie6b16abd3ecc872f0920d29c7577a10c44091af6
diff --git a/apps/optical-model/src/main/java/org/onosproject/net/optical/intent/impl/compiler/OpticalCircuitIntentCompiler.java b/apps/optical-model/src/main/java/org/onosproject/net/optical/intent/impl/compiler/OpticalCircuitIntentCompiler.java
new file mode 100644
index 0000000..dbe1ec5
--- /dev/null
+++ b/apps/optical-model/src/main/java/org/onosproject/net/optical/intent/impl/compiler/OpticalCircuitIntentCompiler.java
@@ -0,0 +1,582 @@
+/*
+ * Copyright 2015-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.net.optical.intent.impl.compiler;
+
+import com.google.common.base.Strings;
+
+import org.apache.commons.lang3.tuple.Pair;
+import org.apache.felix.scr.annotations.Activate;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Deactivate;
+import org.apache.felix.scr.annotations.Modified;
+import org.apache.felix.scr.annotations.Property;
+import org.apache.felix.scr.annotations.Reference;
+import org.apache.felix.scr.annotations.ReferenceCardinality;
+import org.onlab.util.Tools;
+import org.onosproject.cfg.ComponentConfigService;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.net.AnnotationKeys;
+import org.onosproject.net.CltSignalType;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.OduSignalId;
+import org.onosproject.net.OduSignalType;
+import org.onosproject.net.OduSignalUtils;
+import org.onosproject.net.Port;
+import org.onosproject.net.TributarySlot;
+import org.onosproject.net.behaviour.TributarySlotQuery;
+import org.onosproject.net.device.DeviceService;
+import org.onosproject.net.driver.Driver;
+import org.onosproject.net.driver.DriverService;
+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.flow.criteria.Criteria;
+import org.onosproject.net.flow.instructions.Instructions;
+import org.onosproject.net.intent.FlowRuleIntent;
+import org.onosproject.net.intent.Intent;
+import org.onosproject.net.intent.IntentCompiler;
+import org.onosproject.net.intent.IntentExtensionService;
+import org.onosproject.net.intent.IntentId;
+import org.onosproject.net.intent.IntentService;
+import org.onosproject.net.intent.OpticalCircuitIntent;
+import org.onosproject.net.intent.OpticalConnectivityIntent;
+import org.onosproject.net.optical.OchPort;
+import org.onosproject.net.optical.OduCltPort;
+import org.onosproject.net.intent.IntentSetMultimap;
+import org.onosproject.net.resource.ResourceAllocation;
+import org.onosproject.net.resource.Resource;
+import org.onosproject.net.resource.ResourceService;
+import org.onosproject.net.resource.Resources;
+import org.osgi.service.component.ComponentContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Sets;
+
+import java.util.Collections;
+import java.util.Dictionary;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static org.onosproject.net.optical.device.OpticalDeviceServiceView.opticalView;
+
+/**
+ * An intent compiler for {@link org.onosproject.net.intent.OpticalCircuitIntent}.
+ */
+@Component(immediate = true)
+public class OpticalCircuitIntentCompiler implements IntentCompiler<OpticalCircuitIntent> {
+
+    private static final Logger log = LoggerFactory.getLogger(OpticalCircuitIntentCompiler.class);
+
+    private static final int DEFAULT_MAX_CAPACITY = 10;
+
+    @Property(name = "maxCapacity", intValue = DEFAULT_MAX_CAPACITY,
+            label = "Maximum utilization of an optical connection.")
+
+    private int maxCapacity = DEFAULT_MAX_CAPACITY;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected ComponentConfigService cfgService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected IntentExtensionService intentManager;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected CoreService coreService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected DeviceService deviceService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected ResourceService resourceService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected IntentSetMultimap intentSetMultimap;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected IntentService intentService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected DriverService driverService;
+
+    private ApplicationId appId;
+
+    @Modified
+    public void modified(ComponentContext context) {
+        if (context == null) {
+            return;
+        }
+
+        Dictionary properties = context.getProperties();
+
+        //TODO for reduction check if the new capacity is smaller than the size of the current mapping
+        String propertyString = Tools.get(properties, "maxCapacity");
+
+        //Ignore if propertyString is empty or null
+        if (!Strings.isNullOrEmpty(propertyString)) {
+            try {
+                int temp = Integer.parseInt(propertyString);
+                //Ensure value is non-negative but allow zero as a way to shutdown the link
+                if (temp >= 0) {
+                    maxCapacity = temp;
+                }
+            } catch (NumberFormatException e) {
+                //Malformed arguments lead to no change of value (user should be notified of error)
+              log.error("The value '{}' for maxCapacity was not parsable as an integer.", propertyString, e);
+            }
+        } else {
+            //Notify of empty value but do not return (other properties will also go in this function)
+            log.error("The value for maxCapacity was set to an empty value.");
+        }
+
+    }
+
+    @Activate
+    public void activate(ComponentContext context) {
+        deviceService = opticalView(deviceService);
+        appId = coreService.registerApplication("org.onosproject.net.intent");
+        intentManager.registerCompiler(OpticalCircuitIntent.class, this);
+        cfgService.registerProperties(getClass());
+        modified(context);
+    }
+
+    @Deactivate
+    public void deactivate() {
+        intentManager.unregisterCompiler(OpticalCircuitIntent.class);
+        cfgService.unregisterProperties(getClass(), false);
+    }
+
+    @Override
+    public List<Intent> compile(OpticalCircuitIntent intent, List<Intent> installable) {
+        // Check if ports are OduClt ports
+        ConnectPoint src = intent.getSrc();
+        ConnectPoint dst = intent.getDst();
+        Port srcPort = deviceService.getPort(src.deviceId(), src.port());
+        Port dstPort = deviceService.getPort(dst.deviceId(), dst.port());
+        checkArgument(srcPort instanceof OduCltPort);
+        checkArgument(dstPort instanceof OduCltPort);
+
+        log.debug("Compiling optical circuit intent between {} and {}", src, dst);
+
+        // Release of intent resources here is only a temporary solution for handling the
+        // case of recompiling due to intent restoration (when intent state is FAILED).
+        // TODO: try to release intent resources in IntentManager.
+        resourceService.release(intent.id());
+
+        // Check OduClt ports availability
+        Resource srcPortResource = Resources.discrete(src.deviceId(), src.port()).resource();
+        Resource dstPortResource = Resources.discrete(dst.deviceId(), dst.port()).resource();
+        // If ports are not available, compilation fails
+        if (!Stream.of(srcPortResource, dstPortResource).allMatch(resourceService::isAvailable)) {
+            throw new OpticalIntentCompilationException("Ports for the intent are not available. Intent: " + intent);
+        }
+        List<Resource> ports = ImmutableList.of(srcPortResource, dstPortResource);
+
+        // Check if both devices support multiplexing (usage of TributarySlots)
+        boolean multiplexingSupported = isMultiplexingSupported(intent.getSrc())
+                && isMultiplexingSupported(intent.getDst());
+
+        OpticalConnectivityIntent connIntent = findOpticalConnectivityIntent(intent.getSrc(), intent.getDst(),
+                intent.getSignalType(), multiplexingSupported);
+
+        if (connIntent != null && !multiplexingSupported) {
+            return compile(intent, src, dst, Optional.of(connIntent), ports, false);
+        }
+
+        // Create optical connectivity intent if needed - no optical intent or not enough slots available
+        if (connIntent == null) {
+            return compile(intent, src, dst, Optional.empty(), ports, multiplexingSupported);
+        }
+
+        List<Resource> slots = availableSlotResources(connIntent.getSrc(), connIntent.getDst(),
+                intent.getSignalType());
+        if (slots.isEmpty()) {
+            return compile(intent, src, dst, Optional.empty(), ports, true);
+        }
+
+        return compile(intent, src, dst, Optional.of(connIntent), ImmutableList.<Resource>builder()
+                .addAll(ports).addAll(slots).build(), false);
+
+    }
+
+    private List<Intent> compile(OpticalCircuitIntent intent, ConnectPoint src, ConnectPoint dst,
+                                 Optional<OpticalConnectivityIntent> existingConnectivity,
+                                 List<Resource> resources, boolean supportsMultiplexing) {
+        OpticalConnectivityIntent connectivityIntent;
+        List<Resource> required;
+        if (existingConnectivity.isPresent()) {
+            connectivityIntent = existingConnectivity.get();
+            required = resources;
+        } else {
+            // Find OCh ports with available resources
+            Pair<OchPort, OchPort> ochPorts = findPorts(intent.getSrc(), intent.getDst(), intent.getSignalType());
+
+            if (ochPorts == null) {
+                throw new OpticalIntentCompilationException("Unable to find suitable OCH ports for intent " + intent);
+            }
+
+            ConnectPoint srcCP = new ConnectPoint(src.elementId(), ochPorts.getLeft().number());
+            ConnectPoint dstCP = new ConnectPoint(dst.elementId(), ochPorts.getRight().number());
+
+            // Create optical connectivity intent
+            connectivityIntent = OpticalConnectivityIntent.builder()
+                    .appId(appId)
+                    .src(srcCP)
+                    .dst(dstCP)
+                    .signalType(ochPorts.getLeft().signalType())
+                    .bidirectional(intent.isBidirectional())
+                    .build();
+
+            if (!supportsMultiplexing) {
+                required = resources;
+            } else {
+                List<Resource> slots = availableSlotResources(srcCP, dstCP, intent.getSignalType());
+                if (slots.isEmpty()) {
+                    throw new OpticalIntentCompilationException("Unable to find Tributary Slots for intent " + intent);
+                }
+                required = ImmutableList.<Resource>builder().addAll(resources).addAll(slots).build();
+            }
+        }
+
+        if (resourceService.allocate(intent.id(), required).isEmpty()) {
+            throw new OpticalIntentCompilationException("Unable to allocate resources for intent " + intent
+                    + ": resources=" + required);
+        }
+
+        intentService.submit(connectivityIntent);
+
+        // Save circuit to connectivity intent mapping
+        intentSetMultimap.allocateMapping(connectivityIntent.id(), intent.id());
+
+        FlowRuleIntent circuitIntent = createFlowRule(intent, connectivityIntent, required.stream().
+                flatMap(x -> Tools.stream(x.valueAs(TributarySlot.class)))
+                .collect(Collectors.toSet()));
+        return ImmutableList.of(circuitIntent);
+    }
+
+    private List<Resource> availableSlotResources(ConnectPoint src, ConnectPoint dst, CltSignalType signalType) {
+        OduSignalType oduSignalType = OduSignalUtils.mappingCltSignalTypeToOduSignalType(signalType);
+        int requestedTsNum = oduSignalType.tributarySlots();
+        Set<TributarySlot> commonTributarySlots = findCommonTributarySlotsOnCps(src, dst);
+        if (commonTributarySlots.isEmpty()) {
+            return Collections.emptyList();
+        }
+        if (commonTributarySlots.size() < requestedTsNum) {
+            return Collections.emptyList();
+        }
+
+        Set<TributarySlot> tributarySlots = commonTributarySlots.stream()
+                .limit(requestedTsNum)
+                .collect(Collectors.toSet());
+
+        final List<ConnectPoint> portsList = ImmutableList.of(src, dst);
+        List<Resource> tributarySlotResources = portsList.stream()
+                .flatMap(cp -> tributarySlots
+                        .stream()
+                        .map(ts-> Resources.discrete(cp.deviceId(), cp.port()).resource().child(ts)))
+                .collect(Collectors.toList());
+
+        if (!tributarySlotResources.stream().allMatch(resourceService::isAvailable)) {
+            log.debug("Resource allocation for {} on {} and {} failed (resource request: {})",
+                    signalType, src, dst, tributarySlotResources);
+            return Collections.emptyList();
+        }
+        return tributarySlotResources;
+    }
+
+    private FlowRuleIntent createFlowRule(OpticalCircuitIntent higherIntent,
+                                          OpticalConnectivityIntent lowerIntent, Set<TributarySlot> slots) {
+        // Create optical circuit intent
+        List<FlowRule> rules = new LinkedList<>();
+        // at the source: ODUCLT port mapping to OCH port
+        rules.add(connectPorts(higherIntent.getSrc(), lowerIntent.getSrc(), higherIntent.priority(), slots));
+        // at the destination: OCH port mapping to ODUCLT port
+        rules.add(connectPorts(lowerIntent.getDst(), higherIntent.getDst(), higherIntent.priority(), slots));
+
+        // Create flow rules for reverse path
+        if (higherIntent.isBidirectional()) {
+           // at the destination: OCH port mapping to ODUCLT port
+            rules.add(connectPorts(lowerIntent.getSrc(), higherIntent.getSrc(), higherIntent.priority(), slots));
+            // at the source: ODUCLT port mapping to OCH port
+            rules.add(connectPorts(higherIntent.getDst(), lowerIntent.getDst(), higherIntent.priority(), slots));
+        }
+
+        return new FlowRuleIntent(appId, rules, higherIntent.resources());
+    }
+
+    /**
+     * Returns existing and available optical connectivity intent that matches the given circuit intent.
+     *
+     * @param src source connect point of optical circuit intent
+     * @param dst destination connect point of optical circuit intent
+     * @param signalType signal type of optical circuit intent
+     * @param multiplexingSupported indicates whether ODU multiplexing is supported
+     * @return existing optical connectivity intent, null otherwise.
+     */
+    private OpticalConnectivityIntent findOpticalConnectivityIntent(ConnectPoint src,
+                                                                    ConnectPoint dst,
+                                                                    CltSignalType signalType,
+                                                                    boolean multiplexingSupported) {
+
+        OduSignalType oduSignalType = OduSignalUtils.mappingCltSignalTypeToOduSignalType(signalType);
+
+        return Tools.stream(intentService.getIntents())
+                .filter(x -> x instanceof OpticalConnectivityIntent)
+                .map(x -> (OpticalConnectivityIntent) x)
+                .filter(x -> src.deviceId().equals(x.getSrc().deviceId()))
+                .filter(x -> dst.deviceId().equals(x.getDst().deviceId()))
+                .filter(x -> isAllowed(src, x.getSrc()))
+                .filter(x -> isAllowed(dst, x.getDst()))
+                .filter(x -> isAvailable(x.id()))
+                .filter(x -> !multiplexingSupported ||
+                        isAvailableTributarySlots(x.getSrc(), x.getDst(), oduSignalType.tributarySlots()))
+                .findFirst()
+                .orElse(null);
+    }
+
+    private boolean isAllowed(ConnectPoint circuitCp, ConnectPoint connectivityCp) {
+        ConnectPoint staticPort = staticPort(circuitCp);
+        return staticPort == null || staticPort.equals(connectivityCp);
+    }
+
+    /**
+     * Checks if current allocations on given resource can satisfy request.
+     * If the resource is null, return true.
+     *
+     * @param resource the resource on which to map the intent
+     * @return true if the resource can accept the request, false otherwise
+     */
+    private boolean isAvailable(IntentId resource) {
+        if (resource == null) {
+            return true;
+        }
+
+        Set<IntentId> mapping = intentSetMultimap.getMapping(resource);
+
+        if (mapping == null) {
+            return true;
+        }
+
+        return mapping.size() < maxCapacity;
+    }
+
+    private boolean isAvailableTributarySlots(ConnectPoint src, ConnectPoint dst, int requestedTsNum) {
+        Set<TributarySlot> common = findCommonTributarySlotsOnCps(src, dst);
+        if (common.isEmpty()) {
+            log.debug("No available TributarySlots");
+            return false;
+        }
+        if (common.size() < requestedTsNum) {
+            log.debug("Not enough available TributarySlots={} < requestedTsNum={}", common.size(), requestedTsNum);
+            return false;
+        }
+        return true;
+    }
+
+    private ConnectPoint staticPort(ConnectPoint connectPoint) {
+        Port port = deviceService.getPort(connectPoint.deviceId(), connectPoint.port());
+
+        String staticPort = port.annotations().value(AnnotationKeys.STATIC_PORT);
+
+        // FIXME: need a better way to match the port
+        if (staticPort != null) {
+            for (Port p : deviceService.getPorts(connectPoint.deviceId())) {
+                if (staticPort.equals(p.number().name())) {
+                    return new ConnectPoint(p.element().id(), p.number());
+                }
+            }
+        }
+
+        return null;
+    }
+
+    private Pair<OchPort, OchPort> findPorts(ConnectPoint src, ConnectPoint dst, CltSignalType signalType) {
+        // According to the OpticalCircuitIntent's signalType find OCH ports with available TributarySlots resources
+        switch (signalType) {
+            case CLT_1GBE:
+            case CLT_10GBE:
+                // First search for OCH ports with OduSignalType of ODU2. If not found - search for those with ODU4
+                return findPorts(src, dst, OduSignalType.ODU2)
+                        .orElse(findPorts(src, dst, OduSignalType.ODU4).orElse(null));
+            case CLT_100GBE:
+                return findPorts(src, dst, OduSignalType.ODU4).orElse(null);
+            case CLT_40GBE:
+            default:
+                return null;
+        }
+    }
+
+    private Optional<Pair<OchPort, OchPort>> findPorts(ConnectPoint src, ConnectPoint dst,
+                                                       OduSignalType ochPortSignalType) {
+        return findAvailableOchPort(src, ochPortSignalType)
+                .flatMap(srcOch ->
+                        findAvailableOchPort(dst, ochPortSignalType).map(dstOch -> Pair.of(srcOch, dstOch)));
+    }
+
+    private Optional<OchPort> findAvailableOchPort(ConnectPoint oduPort, OduSignalType ochPortSignalType) {
+        // First see if the port mappings are constrained
+        ConnectPoint ochCP = staticPort(oduPort);
+
+        if (ochCP != null) {
+            OchPort ochPort = (OchPort) deviceService.getPort(ochCP.deviceId(), ochCP.port());
+            Optional<IntentId> intentId =
+                    resourceService.getResourceAllocations(Resources.discrete(ochCP.deviceId(), ochCP.port()).id())
+                            .stream()
+                            .map(ResourceAllocation::consumerId)
+                            .map(ResourceHelper::getIntentId)
+                            .flatMap(Tools::stream)
+                            .findAny();
+
+            if (isAvailable(intentId.orElse(null))) {
+                return Optional.of(ochPort);
+            }
+            return Optional.empty();
+        }
+
+        // No port constraints, so find any port that works
+        List<Port> ports = deviceService.getPorts(oduPort.deviceId());
+
+        for (Port port : ports) {
+            if (!(port instanceof OchPort)) {
+                continue;
+            }
+            // This should be the first allocation on the OCH port
+            if (!resourceService.isAvailable(Resources.discrete(oduPort.deviceId(), port.number()).resource())) {
+                continue;
+            }
+            // OchPort is required to have the requested oduSignalType
+            if (((OchPort) port).signalType() != ochPortSignalType) {
+                continue;
+            }
+
+            Optional<IntentId> intentId =
+                    resourceService.getResourceAllocations(Resources.discrete(oduPort.deviceId(), port.number()).id())
+                            .stream()
+                            .map(ResourceAllocation::consumerId)
+                            .map(ResourceHelper::getIntentId)
+                            .flatMap(Tools::stream)
+                            .findAny();
+
+            if (isAvailable(intentId.orElse(null))) {
+                return Optional.of((OchPort) port);
+            }
+        }
+
+        return Optional.empty();
+    }
+
+    /**
+     * Builds flow rule for mapping between two ports.
+     *
+     * @param src source port
+     * @param dst destination port
+     * @param priority
+     * @param slots Set of TributarySlots
+     * @return flow rules
+     */
+    private FlowRule connectPorts(ConnectPoint src, ConnectPoint dst, int priority, Set<TributarySlot> slots) {
+        checkArgument(src.deviceId().equals(dst.deviceId()));
+
+        TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
+        TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
+
+        selectorBuilder.matchInPort(src.port());
+        if (!slots.isEmpty()) {
+            Port srcPort = deviceService.getPort(src.deviceId(), src.port());
+            Port dstPort = deviceService.getPort(dst.deviceId(), dst.port());
+            OduSignalType oduCltPortOduSignalType;
+            OduSignalType ochPortOduSignalType;
+
+            if (srcPort instanceof OduCltPort) {
+                oduCltPortOduSignalType =
+                        OduSignalUtils.mappingCltSignalTypeToOduSignalType(((OduCltPort) srcPort).signalType());
+                ochPortOduSignalType = ((OchPort) dstPort).signalType();
+
+                selectorBuilder.add(Criteria.matchOduSignalType(oduCltPortOduSignalType));
+                // use Instruction of OduSignalId only in case of ODU Multiplexing
+                if (oduCltPortOduSignalType != ochPortOduSignalType) {
+                    OduSignalId oduSignalId = OduSignalUtils.buildOduSignalId(ochPortOduSignalType, slots);
+                    treatmentBuilder.add(Instructions.modL1OduSignalId(oduSignalId));
+                }
+            } else { // srcPort is OchPort
+                oduCltPortOduSignalType =
+                        OduSignalUtils.mappingCltSignalTypeToOduSignalType(((OduCltPort) dstPort).signalType());
+                ochPortOduSignalType = ((OchPort) srcPort).signalType();
+
+                selectorBuilder.add(Criteria.matchOduSignalType(oduCltPortOduSignalType));
+                // use Criteria of OduSignalId only in case of ODU Multiplexing
+                if (oduCltPortOduSignalType != ochPortOduSignalType) {
+                    OduSignalId oduSignalId = OduSignalUtils.buildOduSignalId(ochPortOduSignalType, slots);
+                    selectorBuilder.add(Criteria.matchOduSignalId(oduSignalId));
+                }
+            }
+        }
+        treatmentBuilder.setOutput(dst.port());
+
+        FlowRule flowRule = DefaultFlowRule.builder()
+                .forDevice(src.deviceId())
+                .withSelector(selectorBuilder.build())
+                .withTreatment(treatmentBuilder.build())
+                .withPriority(priority)
+                .fromApp(appId)
+                .makePermanent()
+                .build();
+
+        return flowRule;
+    }
+
+    private boolean isMultiplexingSupported(ConnectPoint cp) {
+        Driver driver = driverService.getDriver(cp.deviceId());
+        return driver != null
+                && driver.hasBehaviour(TributarySlotQuery.class)
+                && staticPort(cp) == null;
+    }
+
+    /**
+     * Finds the common TributarySlots available on the two connect points.
+     *
+     * @param src source connect point
+     * @param dst dest connect point
+     * @return set of common TributarySlots on both connect points
+     */
+    Set<TributarySlot> findCommonTributarySlotsOnCps(ConnectPoint src, ConnectPoint dst) {
+        Set<TributarySlot> forward = findTributarySlotsOnCp(src);
+        Set<TributarySlot> backward = findTributarySlotsOnCp(dst);
+        return Sets.intersection(forward, backward);
+    }
+
+    /**
+     * Finds the TributarySlots available on the connect point.
+     *
+     * @param cp connect point
+     * @return set of TributarySlots available on the connect point
+     */
+    Set<TributarySlot> findTributarySlotsOnCp(ConnectPoint cp) {
+        return resourceService.getAvailableResourceValues(
+                Resources.discrete(cp.deviceId(), cp.port()).id(),
+                TributarySlot.class);
+    }
+}
diff --git a/apps/optical-model/src/main/java/org/onosproject/net/optical/intent/impl/compiler/OpticalConnectivityIntentCompiler.java b/apps/optical-model/src/main/java/org/onosproject/net/optical/intent/impl/compiler/OpticalConnectivityIntentCompiler.java
new file mode 100644
index 0000000..3de7aa0
--- /dev/null
+++ b/apps/optical-model/src/main/java/org/onosproject/net/optical/intent/impl/compiler/OpticalConnectivityIntentCompiler.java
@@ -0,0 +1,341 @@
+/*
+ * Copyright 2015-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.net.optical.intent.impl.compiler;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import org.apache.felix.scr.annotations.Activate;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Deactivate;
+import org.apache.felix.scr.annotations.Reference;
+import org.apache.felix.scr.annotations.ReferenceCardinality;
+import org.onlab.util.Frequency;
+import org.onosproject.net.AnnotationKeys;
+import org.onosproject.net.ChannelSpacing;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.DefaultOchSignalComparator;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.Link;
+import org.onosproject.net.OchSignal;
+import org.onosproject.net.OchSignalType;
+import org.onosproject.net.Path;
+import org.onosproject.net.Port;
+import org.onosproject.net.device.DeviceService;
+import org.onosproject.net.intent.Intent;
+import org.onosproject.net.intent.IntentCompiler;
+import org.onosproject.net.intent.IntentExtensionService;
+import org.onosproject.net.intent.OpticalConnectivityIntent;
+import org.onosproject.net.intent.OpticalPathIntent;
+import org.onosproject.net.optical.OchPort;
+import org.onosproject.net.resource.ResourceAllocation;
+import org.onosproject.net.resource.Resource;
+import org.onosproject.net.resource.ResourceService;
+import org.onosproject.net.resource.Resources;
+import org.onosproject.net.topology.LinkWeight;
+import org.onosproject.net.topology.Topology;
+import org.onosproject.net.topology.TopologyEdge;
+import org.onosproject.net.topology.TopologyService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static org.onosproject.net.optical.device.OpticalDeviceServiceView.opticalView;
+
+/**
+ * An intent compiler for {@link org.onosproject.net.intent.OpticalConnectivityIntent}.
+ */
+@Component(immediate = true)
+public class OpticalConnectivityIntentCompiler implements IntentCompiler<OpticalConnectivityIntent> {
+
+    protected static final Logger log = LoggerFactory.getLogger(OpticalConnectivityIntentCompiler.class);
+    // By default, allocate 50 GHz lambdas (4 slots of 12.5 GHz) for each intent.
+    private static final int SLOT_COUNT = 4;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected IntentExtensionService intentManager;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected TopologyService topologyService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected DeviceService deviceService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected ResourceService resourceService;
+
+    @Activate
+    public void activate() {
+        deviceService = opticalView(deviceService);
+        intentManager.registerCompiler(OpticalConnectivityIntent.class, this);
+    }
+
+    @Deactivate
+    public void deactivate() {
+        intentManager.unregisterCompiler(OpticalConnectivityIntent.class);
+    }
+
+    @Override
+    public List<Intent> compile(OpticalConnectivityIntent intent,
+                                List<Intent> installable) {
+        // Check if source and destination are optical OCh ports
+        ConnectPoint src = intent.getSrc();
+        ConnectPoint dst = intent.getDst();
+        Port srcPort = deviceService.getPort(src.deviceId(), src.port());
+        Port dstPort = deviceService.getPort(dst.deviceId(), dst.port());
+        checkArgument(srcPort instanceof OchPort);
+        checkArgument(dstPort instanceof OchPort);
+
+        log.debug("Compiling optical connectivity intent between {} and {}", src, dst);
+
+        // Release of intent resources here is only a temporary solution for handling the
+        // case of recompiling due to intent restoration (when intent state is FAILED).
+        // TODO: try to release intent resources in IntentManager.
+        resourceService.release(intent.id());
+
+        // Check OCh port availability
+        Resource srcPortResource = Resources.discrete(src.deviceId(), src.port()).resource();
+        Resource dstPortResource = Resources.discrete(dst.deviceId(), dst.port()).resource();
+        // If ports are not available, compilation fails
+        if (!Stream.of(srcPortResource, dstPortResource).allMatch(resourceService::isAvailable)) {
+            throw new OpticalIntentCompilationException("Ports for the intent are not available. Intent: " + intent);
+        }
+
+        List<Resource> resources = new ArrayList<>();
+        resources.add(srcPortResource);
+        resources.add(dstPortResource);
+
+        // Calculate available light paths
+        Set<Path> paths = getOpticalPaths(intent);
+
+        if (paths.isEmpty()) {
+            throw new OpticalIntentCompilationException("Unable to find suitable lightpath for intent " + intent);
+        }
+
+        // Static or dynamic lambda allocation
+        String staticLambda = srcPort.annotations().value(AnnotationKeys.STATIC_LAMBDA);
+        OchPort srcOchPort = (OchPort) srcPort;
+        OchPort dstOchPort = (OchPort) dstPort;
+
+        Path firstPath = paths.iterator().next();
+        // FIXME: need to actually reserve the lambda for static lambda's
+        // static lambda case: early return
+        if (staticLambda != null) {
+            allocateResources(intent, resources);
+
+            OchSignal lambda = new OchSignal(Frequency.ofHz(Long.parseLong(staticLambda)),
+                    srcOchPort.lambda().channelSpacing(),
+                    srcOchPort.lambda().slotGranularity());
+            return ImmutableList.of(createIntent(intent, firstPath, lambda));
+        }
+
+        // FIXME: also check destination OCh port
+        // non-tunable case: early return
+        if (!srcOchPort.isTunable() || !dstOchPort.isTunable()) {
+            allocateResources(intent, resources);
+
+            OchSignal lambda = srcOchPort.lambda();
+            return ImmutableList.of(createIntent(intent, firstPath, lambda));
+        }
+
+        // remaining cases
+        // Use first path that the required resources are available
+        Optional<Map.Entry<Path, List<OchSignal>>> found = paths.stream()
+                .map(path -> Maps.immutableEntry(path, findFirstAvailableOch(path)))
+                .filter(entry -> !entry.getValue().isEmpty())
+                .filter(entry -> convertToResources(entry.getKey().links(),
+                        entry.getValue()).stream().allMatch(resourceService::isAvailable))
+                .findFirst();
+
+        if (found.isPresent()) {
+            resources.addAll(convertToResources(found.get().getKey().links(), found.get().getValue()));
+
+            allocateResources(intent, resources);
+
+            OchSignal ochSignal = OchSignal.toFixedGrid(found.get().getValue(), ChannelSpacing.CHL_50GHZ);
+            return ImmutableList.of(createIntent(intent, found.get().getKey(), ochSignal));
+        } else {
+            throw new OpticalIntentCompilationException("Unable to find suitable lightpath for intent " + intent);
+        }
+    }
+
+    private Intent createIntent(OpticalConnectivityIntent parentIntent, Path path, OchSignal lambda) {
+        // Create installable optical path intent
+        // Only support fixed grid for now
+        OchSignalType signalType = OchSignalType.FIXED_GRID;
+
+        return OpticalPathIntent.builder()
+                .appId(parentIntent.appId())
+                .src(parentIntent.getSrc())
+                .dst(parentIntent.getDst())
+                // calling paths.iterator().next() is safe because of non-empty set
+                .path(path)
+                .lambda(lambda)
+                .signalType(signalType)
+                .bidirectional(parentIntent.isBidirectional())
+                .build();
+    }
+
+    private void allocateResources(Intent intent, List<Resource> resources) {
+        // reserve all of required resources
+        List<ResourceAllocation> allocations = resourceService.allocate(intent.id(), resources);
+        if (allocations.isEmpty()) {
+            log.info("Resource allocation for {} failed (resource request: {})", intent, resources);
+            throw new OpticalIntentCompilationException("Unable to allocate resources: " + resources);
+        }
+    }
+
+    private List<OchSignal> findFirstAvailableOch(Path path) {
+        Set<OchSignal> lambdas = findCommonLambdasOverLinks(path.links());
+        if (lambdas.isEmpty()) {
+            return Collections.emptyList();
+        }
+
+        return findFirstLambda(lambdas, slotCount());
+    }
+
+    private List<Resource> convertToResources(List<Link> links, List<OchSignal> lambda) {
+        return links.stream()
+                .flatMap(x -> Stream.of(
+                        Resources.discrete(x.src().deviceId(), x.src().port()).resource(),
+                        Resources.discrete(x.dst().deviceId(), x.dst().port()).resource()
+                ))
+                .flatMap(x -> lambda.stream().map(x::child))
+                .collect(Collectors.toList());
+    }
+
+    /**
+     * Get the number of 12.5 GHz slots required for the path.
+     *
+     * For now this returns a constant value of 4 (i.e., fixed grid 50 GHz slot),
+     * but in the future can depend on optical reach, line rate, transponder port capabilities, etc.
+     *
+     * @return number of slots
+     */
+    private int slotCount() {
+        return SLOT_COUNT;
+    }
+
+    private Set<OchSignal> findCommonLambdasOverLinks(List<Link> links) {
+        return links.stream()
+                .flatMap(x -> Stream.of(
+                        Resources.discrete(x.src().deviceId(), x.src().port()).id(),
+                        Resources.discrete(x.dst().deviceId(), x.dst().port()).id()
+                ))
+                .map(x -> resourceService.getAvailableResourceValues(x, OchSignal.class))
+                .map(x -> (Set<OchSignal>) ImmutableSet.copyOf(x))
+                .reduce(Sets::intersection)
+                .orElse(Collections.emptySet());
+    }
+
+    /**
+     * Returns list of consecutive resources in given set of lambdas.
+     *
+     * @param lambdas list of lambdas
+     * @param count number of consecutive lambdas to return
+     * @return list of consecutive lambdas
+     */
+    private List<OchSignal> findFirstLambda(Set<OchSignal> lambdas, int count) {
+        // Sort available lambdas
+        List<OchSignal> lambdaList = new ArrayList<>(lambdas);
+        lambdaList.sort(new DefaultOchSignalComparator());
+
+        // Look ahead by count and ensure spacing multiplier is as expected (i.e., no gaps)
+        for (int i = 0; i < lambdaList.size() - count; i++) {
+            if (lambdaList.get(i).spacingMultiplier() + 2 * count ==
+                    lambdaList.get(i + count).spacingMultiplier()) {
+                return lambdaList.subList(i, i + count);
+            }
+        }
+
+        return Collections.emptyList();
+    }
+
+    private ConnectPoint staticPort(ConnectPoint connectPoint) {
+        Port port = deviceService.getPort(connectPoint.deviceId(), connectPoint.port());
+
+        String staticPort = port.annotations().value(AnnotationKeys.STATIC_PORT);
+
+        // FIXME: need a better way to match the port
+        if (staticPort != null) {
+            for (Port p : deviceService.getPorts(connectPoint.deviceId())) {
+                if (staticPort.equals(p.number().name())) {
+                    return new ConnectPoint(p.element().id(), p.number());
+                }
+            }
+        }
+
+        return null;
+    }
+
+    /**
+     * Calculates optical paths in WDM topology.
+     *
+     * @param intent optical connectivity intent
+     * @return set of paths in WDM topology
+     */
+    private Set<Path> getOpticalPaths(OpticalConnectivityIntent intent) {
+        // Route in WDM topology
+        Topology topology = topologyService.currentTopology();
+        LinkWeight weight = new LinkWeight() {
+
+            @Override
+            public double weight(TopologyEdge edge) {
+                // Disregard inactive or non-optical links
+                if (edge.link().state() == Link.State.INACTIVE) {
+                    return -1;
+                }
+                if (edge.link().type() != Link.Type.OPTICAL) {
+                    return -1;
+                }
+                // Adhere to static port mappings
+                DeviceId srcDeviceId = edge.link().src().deviceId();
+                if (srcDeviceId.equals(intent.getSrc().deviceId())) {
+                    ConnectPoint srcStaticPort = staticPort(intent.getSrc());
+                    if (srcStaticPort != null) {
+                        return srcStaticPort.equals(edge.link().src()) ? 1 : -1;
+                    }
+                }
+                DeviceId dstDeviceId = edge.link().dst().deviceId();
+                if (dstDeviceId.equals(intent.getDst().deviceId())) {
+                    ConnectPoint dstStaticPort = staticPort(intent.getDst());
+                    if (dstStaticPort != null) {
+                        return dstStaticPort.equals(edge.link().dst()) ? 1 : -1;
+                    }
+                }
+
+                return 1;
+            }
+        };
+
+        ConnectPoint start = intent.getSrc();
+        ConnectPoint end = intent.getDst();
+        Set<Path> paths = topologyService.getPaths(topology, start.deviceId(),
+                end.deviceId(), weight);
+
+        return paths;
+    }
+}
diff --git a/apps/optical-model/src/main/java/org/onosproject/net/optical/intent/impl/compiler/OpticalIntentCompilationException.java b/apps/optical-model/src/main/java/org/onosproject/net/optical/intent/impl/compiler/OpticalIntentCompilationException.java
new file mode 100644
index 0000000..9070b25
--- /dev/null
+++ b/apps/optical-model/src/main/java/org/onosproject/net/optical/intent/impl/compiler/OpticalIntentCompilationException.java
@@ -0,0 +1,38 @@
+/*
+ * 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.net.optical.intent.impl.compiler;
+
+import org.onosproject.net.intent.IntentCompilationException;
+
+/**
+ * An exception thrown when an optical intent compilation fails.
+ */
+public class OpticalIntentCompilationException extends IntentCompilationException {
+
+    private static final long serialVersionUID = 2538096696847181373L;
+
+    public OpticalIntentCompilationException() {
+        super();
+    }
+
+    public OpticalIntentCompilationException(String message) {
+        super(message);
+    }
+
+    public OpticalIntentCompilationException(String message, Throwable cause) {
+        super(message, cause);
+    }
+}
diff --git a/apps/optical-model/src/main/java/org/onosproject/net/optical/intent/impl/compiler/OpticalOduIntentCompiler.java b/apps/optical-model/src/main/java/org/onosproject/net/optical/intent/impl/compiler/OpticalOduIntentCompiler.java
new file mode 100644
index 0000000..2da9a40
--- /dev/null
+++ b/apps/optical-model/src/main/java/org/onosproject/net/optical/intent/impl/compiler/OpticalOduIntentCompiler.java
@@ -0,0 +1,383 @@
+/*
+ * 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.net.optical.intent.impl.compiler;
+
+
+import org.apache.felix.scr.annotations.Activate;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Deactivate;
+import org.apache.felix.scr.annotations.Reference;
+import org.apache.felix.scr.annotations.ReferenceCardinality;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.Link;
+import org.onosproject.net.LinkKey;
+import org.onosproject.net.OduSignalId;
+import org.onosproject.net.OduSignalType;
+import org.onosproject.net.OduSignalUtils;
+import org.onosproject.net.Path;
+import org.onosproject.net.Port;
+import org.onosproject.net.TributarySlot;
+import org.onosproject.net.device.DeviceService;
+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.flow.criteria.Criteria;
+import org.onosproject.net.flow.instructions.Instructions;
+import org.onosproject.net.intent.FlowRuleIntent;
+import org.onosproject.net.intent.Intent;
+import org.onosproject.net.intent.IntentCompiler;
+import org.onosproject.net.intent.IntentExtensionService;
+import org.onosproject.net.intent.OpticalOduIntent;
+import org.onosproject.net.optical.OduCltPort;
+import org.onosproject.net.optical.OtuPort;
+import org.onosproject.net.resource.Resource;
+import org.onosproject.net.resource.ResourceService;
+import org.onosproject.net.resource.ResourceAllocation;
+import org.onosproject.net.resource.Resources;
+import org.onosproject.net.topology.LinkWeight;
+import org.onosproject.net.topology.Topology;
+import org.onosproject.net.topology.TopologyService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static org.onosproject.net.LinkKey.linkKey;
+import static org.onosproject.net.optical.device.OpticalDeviceServiceView.opticalView;
+
+/**
+ * An intent compiler for {@link org.onosproject.net.intent.OpticalOduIntent}.
+ */
+@Component(immediate = true)
+public class OpticalOduIntentCompiler implements IntentCompiler<OpticalOduIntent> {
+
+    private static final Logger log = LoggerFactory.getLogger(OpticalOduIntentCompiler.class);
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected IntentExtensionService intentManager;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected CoreService coreService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected TopologyService topologyService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected DeviceService deviceService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected ResourceService resourceService;
+
+    private ApplicationId appId;
+
+    @Activate
+    public void activate() {
+        deviceService = opticalView(deviceService);
+        appId = coreService.registerApplication("org.onosproject.net.intent");
+        intentManager.registerCompiler(OpticalOduIntent.class, this);
+    }
+
+    @Deactivate
+    public void deactivate() {
+        intentManager.unregisterCompiler(OpticalOduIntent.class);
+    }
+
+    @Override
+    public List<Intent> compile(OpticalOduIntent intent, List<Intent> installable) {
+        // Check if ports are OduClt ports
+        ConnectPoint src = intent.getSrc();
+        ConnectPoint dst = intent.getDst();
+        Port srcPort = deviceService.getPort(src.deviceId(), src.port());
+        Port dstPort = deviceService.getPort(dst.deviceId(), dst.port());
+        checkArgument(srcPort instanceof OduCltPort);
+        checkArgument(dstPort instanceof OduCltPort);
+
+        log.debug("Compiling optical ODU intent between {} and {}", src, dst);
+
+        // Release of intent resources here is only a temporary solution for handling the
+        // case of recompiling due to intent restoration (when intent state is FAILED).
+        // TODO: try to release intent resources in IntentManager.
+        resourceService.release(intent.id());
+
+        // Check OduClt ports availability
+        Resource srcPortResource = Resources.discrete(src.deviceId(), src.port()).resource();
+        Resource dstPortResource = Resources.discrete(dst.deviceId(), dst.port()).resource();
+        // If ports are not available, compilation fails
+        if (!Stream.of(srcPortResource, dstPortResource).allMatch(resourceService::isAvailable)) {
+            throw new OpticalIntentCompilationException("Ports for the intent are not available. Intent: " + intent);
+        }
+        List<Resource> intentResources = new ArrayList<>();
+        intentResources.add(srcPortResource);
+        intentResources.add(dstPortResource);
+
+        // Calculate available light paths
+        Set<Path> paths = getOpticalPaths(intent);
+
+        if (paths.isEmpty()) {
+            throw new OpticalIntentCompilationException("Unable to find suitable lightpath for intent " + intent);
+        }
+
+        // Use first path that can be successfully reserved
+        for (Path path : paths) {
+
+            // Find available Tributary Slots on both directions of path
+            Map<LinkKey, Set<TributarySlot>> slotsMap = findAvailableTributarySlots(intent, path);
+            if (slotsMap.isEmpty()) {
+                continue;
+            }
+            List<Resource> tributarySlotResources = convertToResources(slotsMap);
+            if (!tributarySlotResources.stream().allMatch(resourceService::isAvailable)) {
+                continue;
+            }
+
+            intentResources.addAll(tributarySlotResources);
+
+            allocateResources(intent, intentResources);
+
+            List<FlowRule> rules = new LinkedList<>();
+
+            // Create rules for forward and reverse path
+            rules = createRules(intent, intent.getSrc(), intent.getDst(), path, slotsMap, false);
+            if (intent.isBidirectional()) {
+                rules.addAll(createRules(intent, intent.getDst(), intent.getSrc(), path, slotsMap, true));
+            }
+
+            return Collections.singletonList(new FlowRuleIntent(appId,
+                    rules, ImmutableSet.copyOf(path.links())));
+        }
+
+        throw new OpticalIntentCompilationException("Unable to find suitable lightpath for intent " + intent);
+    }
+
+    /**
+     * Find available TributarySlots across path.
+     *
+     * @param intent
+     * @param path path in OTU topology
+     * @return Map of Linkey and Set of available TributarySlots on its ports
+     */
+    private Map<LinkKey, Set<TributarySlot>> findAvailableTributarySlots(OpticalOduIntent intent, Path path) {
+        Set<LinkKey> linkRequest = Sets.newHashSetWithExpectedSize(path.links().size());
+        for (int i = 0; i < path.links().size(); i++) {
+            LinkKey link = linkKey(path.links().get(i));
+            linkRequest.add(link);
+        }
+
+        return findTributarySlots(intent, linkRequest);
+    }
+
+    private List<Resource> convertToResources(Map<LinkKey, Set<TributarySlot>> slotsMap) {
+       // Same TributarySlots are used for both directions
+        Set<Resource> resources = slotsMap.entrySet().stream()
+                .flatMap(x -> x.getValue()
+                        .stream()
+                        .flatMap(ts-> Stream.of(
+                                Resources.discrete(x.getKey().src().deviceId(), x.getKey().src().port())
+                                        .resource().child(ts),
+                                Resources.discrete(x.getKey().dst().deviceId(), x.getKey().dst().port())
+                                        .resource().child(ts))))
+                .collect(Collectors.toSet());
+        return (ImmutableList.copyOf(resources));
+    }
+
+    private void allocateResources(Intent intent, List<Resource> resources) {
+        // reserve all of required resources
+        List<ResourceAllocation> allocations = resourceService.allocate(intent.id(), resources);
+        if (allocations.isEmpty()) {
+            log.info("Resource allocation for {} failed (resource request: {})", intent, resources);
+            throw new OpticalIntentCompilationException("Unable to allocate resources: " + resources);
+        }
+    }
+
+    private Map<LinkKey, Set<TributarySlot>> findTributarySlots(OpticalOduIntent intent, Set<LinkKey> links) {
+        OduSignalType oduSignalType = OduSignalUtils.mappingCltSignalTypeToOduSignalType(intent.getSignalType());
+        int requestedTsNum = oduSignalType.tributarySlots();
+
+        Map<LinkKey, Set<TributarySlot>> slotsMap = new HashMap<>();
+        for (LinkKey link : links) {
+            Set<TributarySlot> common = findCommonTributarySlotsOnCps(link.src(), link.dst());
+            if (common.isEmpty() || (common.size() < requestedTsNum)) {
+                log.debug("Failed to find TributarySlots on link {} requestedTsNum={}", link, requestedTsNum);
+                return Collections.emptyMap(); // failed to find enough available TributarySlots on a link
+            }
+            slotsMap.put(link, common.stream()
+                                .limit(requestedTsNum)
+                                .collect(Collectors.toSet()));
+        }
+        return slotsMap;
+    }
+
+    /**
+     * Calculates optical paths in OTU topology.
+     *
+     * @param intent optical ODU intent
+     * @return set of paths in OTU topology
+     */
+    private Set<Path> getOpticalPaths(OpticalOduIntent intent) {
+        // Route in OTU topology
+        Topology topology = topologyService.currentTopology();
+
+        LinkWeight weight = edge -> {
+            // Disregard inactive or non-optical links
+            if (edge.link().state() == Link.State.INACTIVE) {
+                return -1;
+            }
+            if (edge.link().type() != Link.Type.OPTICAL) {
+                return -1;
+            }
+            // Find path with available TributarySlots resources
+            if (!isAvailableTributarySlots(intent, edge.link())) {
+                return -1;
+            }
+            return 1;
+        };
+
+        ConnectPoint start = intent.getSrc();
+        ConnectPoint end = intent.getDst();
+
+        return topologyService.getPaths(topology, start.deviceId(), end.deviceId(), weight);
+    }
+
+    private boolean isAvailableTributarySlots(OpticalOduIntent intent, Link link) {
+        OduSignalType oduSignalType = OduSignalUtils.mappingCltSignalTypeToOduSignalType(intent.getSignalType());
+        int requestedTsNum = oduSignalType.tributarySlots();
+
+        Set<TributarySlot> common = findCommonTributarySlotsOnCps(link.src(), link.dst());
+        if (common.isEmpty() || (common.size() < requestedTsNum)) {
+            log.debug("Not enough available TributarySlots on link {} requestedTsNum={}", link, requestedTsNum);
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * Create rules for the forward (or the reverse) path of the intent.
+     *
+     * @param intent OpticalOduIntent intent
+     * @param path path found for intent
+     * @param slotsMap Map of LinkKey and TributarySlots resources
+     * @return list of flow rules
+     */
+    private List<FlowRule> createRules(OpticalOduIntent intent, ConnectPoint src, ConnectPoint dst,
+            Path path, Map<LinkKey, Set<TributarySlot>> slotsMap, boolean reverse) {
+        // Build the ingress OTN rule
+        TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
+        selector.matchInPort(src.port());
+        OduSignalType oduCltPortOduSignalType =
+                OduSignalUtils.mappingCltSignalTypeToOduSignalType(intent.getSignalType());
+        selector.add(Criteria.matchOduSignalType(oduCltPortOduSignalType));
+
+        List<FlowRule> rules = new LinkedList<>();
+        ConnectPoint current = src;
+
+        List<Link> links = ((!reverse) ? path.links() : Lists.reverse(path.links()));
+
+        for (Link link : links) {
+            Set<TributarySlot> slots = slotsMap.get(linkKey(link));
+            OtuPort otuPort = (OtuPort) (deviceService.getPort(link.src().deviceId(), link.src().port()));
+            OduSignalType otuPortOduSignalType =
+                    OduSignalUtils.mappingOtuSignalTypeToOduSignalType(otuPort.signalType());
+
+            TrafficTreatment.Builder treat = DefaultTrafficTreatment.builder();
+            OduSignalId oduSignalId = null;
+            // use Instruction of OduSignalId only in case of ODU Multiplexing
+            if (oduCltPortOduSignalType != otuPortOduSignalType) {
+                oduSignalId = OduSignalUtils.buildOduSignalId(otuPortOduSignalType, slots);
+                treat.add(Instructions.modL1OduSignalId(oduSignalId));
+            }
+            ConnectPoint next = ((!reverse) ? link.src() : link.dst());
+            treat.setOutput(next.port());
+
+            FlowRule rule = createFlowRule(intent, current.deviceId(), selector.build(), treat.build());
+            rules.add(rule);
+
+            current = ((!reverse) ? link.dst() : link.src());
+            selector = DefaultTrafficSelector.builder();
+            selector.matchInPort(current.port());
+            selector.add(Criteria.matchOduSignalType(oduCltPortOduSignalType));
+            // use Criteria of OduSignalId only in case of ODU Multiplexing
+            if (oduCltPortOduSignalType != otuPortOduSignalType) {
+                selector.add(Criteria.matchOduSignalId(oduSignalId));
+            }
+        }
+
+        // Build the egress OTN rule
+        TrafficTreatment.Builder treatLast = DefaultTrafficTreatment.builder();
+        treatLast.setOutput(dst.port());
+
+        FlowRule rule = createFlowRule(intent, dst.deviceId(), selector.build(), treatLast.build());
+        rules.add(rule);
+
+        return rules;
+    }
+
+    private FlowRule createFlowRule(OpticalOduIntent intent, DeviceId deviceId,
+            TrafficSelector selector, TrafficTreatment treat) {
+        return DefaultFlowRule.builder()
+                .forDevice(deviceId)
+                .withSelector(selector)
+                .withTreatment(treat)
+                .withPriority(intent.priority())
+                .fromApp(appId)
+                .makePermanent()
+                .build();
+    }
+
+    /**
+     * Finds the common TributarySlots available on the two connect points.
+     *
+     * @param src source connect point
+     * @param dst dest connect point
+     * @return set of common TributarySlots on both connect points
+     */
+    Set<TributarySlot> findCommonTributarySlotsOnCps(ConnectPoint src, ConnectPoint dst) {
+        Set<TributarySlot> forward = findTributarySlotsOnCp(src);
+        Set<TributarySlot> backward = findTributarySlotsOnCp(dst);
+        return Sets.intersection(forward, backward);
+    }
+
+    /**
+     * Finds the TributarySlots available on the connect point.
+     *
+     * @param cp connect point
+     * @return set of TributarySlots available on the connect point
+     */
+    Set<TributarySlot> findTributarySlotsOnCp(ConnectPoint cp) {
+        return resourceService.getAvailableResourceValues(
+                Resources.discrete(cp.deviceId(), cp.port()).id(),
+                TributarySlot.class);
+    }
+}
\ No newline at end of file
diff --git a/apps/optical-model/src/main/java/org/onosproject/net/optical/intent/impl/compiler/OpticalPathIntentCompiler.java b/apps/optical-model/src/main/java/org/onosproject/net/optical/intent/impl/compiler/OpticalPathIntentCompiler.java
new file mode 100644
index 0000000..3136204
--- /dev/null
+++ b/apps/optical-model/src/main/java/org/onosproject/net/optical/intent/impl/compiler/OpticalPathIntentCompiler.java
@@ -0,0 +1,188 @@
+/*
+ * Copyright 2015-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.net.optical.intent.impl.compiler;
+
+import com.google.common.collect.Lists;
+import org.apache.felix.scr.annotations.Activate;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Deactivate;
+import org.apache.felix.scr.annotations.Reference;
+import org.apache.felix.scr.annotations.ReferenceCardinality;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.Link;
+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.flow.criteria.Criteria;
+import org.onosproject.net.flow.instructions.Instructions;
+import org.onosproject.net.intent.FlowRuleIntent;
+import org.onosproject.net.intent.Intent;
+import org.onosproject.net.intent.IntentCompiler;
+import org.onosproject.net.intent.IntentExtensionService;
+import org.onosproject.net.intent.OpticalPathIntent;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collections;
+import java.util.LinkedList;
+import java.util.List;
+
+@Component(immediate = true)
+public class OpticalPathIntentCompiler implements IntentCompiler<OpticalPathIntent> {
+
+    private static final Logger log = LoggerFactory.getLogger(OpticalPathIntentCompiler.class);
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected IntentExtensionService intentManager;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected CoreService coreService;
+
+    private ApplicationId appId;
+
+    @Activate
+    public void activate() {
+        appId = coreService.registerApplication("org.onosproject.net.intent");
+        intentManager.registerCompiler(OpticalPathIntent.class, this);
+    }
+
+    @Deactivate
+    public void deactivate() {
+        intentManager.unregisterCompiler(OpticalPathIntent.class);
+    }
+
+    @Override
+    public List<Intent> compile(OpticalPathIntent intent, List<Intent> installable) {
+        log.debug("Compiling optical path intent between {} and {}", intent.src(), intent.dst());
+
+        // Create rules for forward and reverse path
+        List<FlowRule> rules = createRules(intent);
+        if (intent.isBidirectional()) {
+            rules.addAll(createReverseRules(intent));
+        }
+
+        return Collections.singletonList(new FlowRuleIntent(appId, rules, intent.resources()));
+    }
+
+    /**
+     * Create rules for the forward path of the intent.
+     *
+     * @param intent the intent
+     * @return list of flow rules
+     */
+    private List<FlowRule> createRules(OpticalPathIntent intent) {
+        TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
+        selectorBuilder.matchInPort(intent.src().port());
+
+        List<FlowRule> rules = new LinkedList<>();
+        ConnectPoint current = intent.src();
+
+        for (Link link : intent.path().links()) {
+            TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
+            treatmentBuilder.add(Instructions.modL0Lambda(intent.lambda()));
+            treatmentBuilder.setOutput(link.src().port());
+
+            FlowRule rule = DefaultFlowRule.builder()
+                    .forDevice(current.deviceId())
+                    .withSelector(selectorBuilder.build())
+                    .withTreatment(treatmentBuilder.build())
+                    .withPriority(intent.priority())
+                    .fromApp(appId)
+                    .makePermanent()
+                    .build();
+
+            rules.add(rule);
+
+            current = link.dst();
+            selectorBuilder.matchInPort(link.dst().port());
+            selectorBuilder.add(Criteria.matchLambda(intent.lambda()));
+            selectorBuilder.add(Criteria.matchOchSignalType(intent.signalType()));
+        }
+
+        // Build the egress ROADM rule
+        TrafficTreatment.Builder treatmentLast = DefaultTrafficTreatment.builder();
+        treatmentLast.setOutput(intent.dst().port());
+
+        FlowRule rule = new DefaultFlowRule.Builder()
+                .forDevice(intent.dst().deviceId())
+                .withSelector(selectorBuilder.build())
+                .withTreatment(treatmentLast.build())
+                .withPriority(intent.priority())
+                .fromApp(appId)
+                .makePermanent()
+                .build();
+        rules.add(rule);
+
+        return rules;
+    }
+
+    /**
+     * Create rules for the reverse path of the intent.
+     *
+     * @param intent the intent
+     * @return list of flow rules
+     */
+    private List<FlowRule> createReverseRules(OpticalPathIntent intent) {
+        TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
+        selectorBuilder.matchInPort(intent.dst().port());
+
+        List<FlowRule> rules = new LinkedList<>();
+        ConnectPoint current = intent.dst();
+
+        for (Link link : Lists.reverse(intent.path().links())) {
+            TrafficTreatment.Builder treatmentBuilder = DefaultTrafficTreatment.builder();
+            treatmentBuilder.add(Instructions.modL0Lambda(intent.lambda()));
+            treatmentBuilder.setOutput(link.dst().port());
+
+            FlowRule rule = DefaultFlowRule.builder()
+                    .forDevice(current.deviceId())
+                    .withSelector(selectorBuilder.build())
+                    .withTreatment(treatmentBuilder.build())
+                    .withPriority(intent.priority())
+                    .fromApp(appId)
+                    .makePermanent()
+                    .build();
+
+            rules.add(rule);
+
+            current = link.src();
+            selectorBuilder.matchInPort(link.src().port());
+            selectorBuilder.add(Criteria.matchLambda(intent.lambda()));
+            selectorBuilder.add(Criteria.matchOchSignalType(intent.signalType()));
+        }
+
+        // Build the egress ROADM rule
+        TrafficTreatment.Builder treatmentLast = DefaultTrafficTreatment.builder();
+        treatmentLast.setOutput(intent.src().port());
+
+        FlowRule rule = new DefaultFlowRule.Builder()
+                .forDevice(intent.src().deviceId())
+                .withSelector(selectorBuilder.build())
+                .withTreatment(treatmentLast.build())
+                .withPriority(intent.priority())
+                .fromApp(appId)
+                .makePermanent()
+                .build();
+        rules.add(rule);
+
+        return rules;
+    }
+}
diff --git a/apps/optical-model/src/main/java/org/onosproject/net/optical/intent/impl/compiler/ResourceHelper.java b/apps/optical-model/src/main/java/org/onosproject/net/optical/intent/impl/compiler/ResourceHelper.java
new file mode 100644
index 0000000..4d1a8d1
--- /dev/null
+++ b/apps/optical-model/src/main/java/org/onosproject/net/optical/intent/impl/compiler/ResourceHelper.java
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2016 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.net.optical.intent.impl.compiler;
+
+import com.google.common.annotations.Beta;
+import org.onosproject.net.intent.IntentId;
+import org.onosproject.net.resource.ResourceConsumerId;
+
+import java.util.Optional;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+// TODO consider moving this to api bundle.
+/**
+ * Helper class for ResourceService related processes.
+ */
+@Beta
+public final class ResourceHelper {
+
+    // To avoid instantiation
+    private ResourceHelper() {
+    }
+
+    /**
+     * Creates IntentId object from given consumer ID.
+     *
+     * @param consumerId ConsumerId object
+     * @return Created IntentId object.  null if failed to create or given consumer is not instance of IntentId.
+     */
+    public static Optional<IntentId> getIntentId(ResourceConsumerId consumerId) {
+        checkNotNull(consumerId);
+
+        if (!consumerId.isClassOf(IntentId.class)) {
+            return Optional.empty();
+        }
+
+        return Optional.of(IntentId.valueOf(consumerId.value()));
+    }
+
+}
diff --git a/apps/optical-model/src/main/java/org/onosproject/net/optical/intent/impl/compiler/package-info.java b/apps/optical-model/src/main/java/org/onosproject/net/optical/intent/impl/compiler/package-info.java
new file mode 100644
index 0000000..7f3011b
--- /dev/null
+++ b/apps/optical-model/src/main/java/org/onosproject/net/optical/intent/impl/compiler/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * 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.
+ */
+
+/**
+ * Implementations of optical intent compilers.
+ */
+package org.onosproject.net.optical.intent.impl.compiler;
\ No newline at end of file