Patch Panel Application with Ui

Change-Id: I0906983cf494ce82de233e8bfbd66b60d0792c89
diff --git a/apps/patchpanel/src/main/java/org/onosproject/patchpanel/cli/PatchPanelCommand.java b/apps/patchpanel/src/main/java/org/onosproject/patchpanel/cli/PatchPanelCommand.java
new file mode 100644
index 0000000..bac3221
--- /dev/null
+++ b/apps/patchpanel/src/main/java/org/onosproject/patchpanel/cli/PatchPanelCommand.java
@@ -0,0 +1,74 @@
+/*
+ * 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.
+ */
+
+/**
+ * This class defines the cli command for the PatchPanel class. It creates
+ * an instance of the PatchPanelService class to call it's method addPatch().
+ * The command takes 2 parameters, 2 connectPoints.
+ */
+package org.onosproject.patchpanel.cli;
+
+import org.apache.karaf.shell.commands.Argument;
+import org.apache.karaf.shell.commands.Command;
+import org.onosproject.cli.AbstractShellCommand;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.DeviceId;
+import org.onosproject.patchpanel.impl.PatchPanelService;
+
+//name of command and description
+@Command(scope = "onos", name = "patch",
+         description = "Gets the 2 ports of one ConnectPoint that will be patched")
+
+public class PatchPanelCommand extends AbstractShellCommand {
+    //the 2 arguments, both connect points
+    @Argument(index = 0, name = "switch/portNumber", description = "ConnectPoint and first port number",
+            required = true, multiValued = false)
+    String port1 = null;
+    @Argument (index = 1, name = "switch/portNumber2", description = "ConnectPoint and second port number",
+            required = true, multiValued = false)
+    String port2 = null;
+
+    private ConnectPoint cp1, cp2;
+    private PatchPanelService patchPanelService;
+    private DeviceId deviceId, deviceId2;
+
+    /**
+     * This method creates an instance of the Service class and then uses the user
+     * input to call the addPatch method in PatchPanel. It also
+     * @throws IllegalArgumentException if the 2 connectpoints are of different devices
+     */
+    @Override
+    protected void execute() {
+        patchPanelService = get(PatchPanelService.class);
+        boolean done = false;
+        cp1 = ConnectPoint.deviceConnectPoint(port1);
+        cp2 = ConnectPoint.deviceConnectPoint(port2);
+        deviceId = cp1.deviceId();
+        deviceId2 = cp2.deviceId();
+        if (!(deviceId.equals(deviceId2))) {
+            throw new IllegalArgumentException("ERROR: Two Different Device Id's");
+        } else {
+            done = patchPanelService.addPatch(cp1, cp2);
+        }
+        if (done) {
+            log.info("This patch has been created");
+        } else {
+            log.info("This patch was NOT created");
+        }
+
+    }
+
+}
diff --git a/apps/patchpanel/src/main/java/org/onosproject/patchpanel/cli/package-info.java b/apps/patchpanel/src/main/java/org/onosproject/patchpanel/cli/package-info.java
new file mode 100644
index 0000000..85a7842
--- /dev/null
+++ b/apps/patchpanel/src/main/java/org/onosproject/patchpanel/cli/package-info.java
@@ -0,0 +1,21 @@
+/*
+ * 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.
+ */
+
+/**
+ * patch panel-related CLI commands(in cli folder).
+ */
+package org.onosproject.patchpanel.cli;
+
diff --git a/apps/patchpanel/src/main/java/org/onosproject/patchpanel/impl/AppUiComponent.java b/apps/patchpanel/src/main/java/org/onosproject/patchpanel/impl/AppUiComponent.java
new file mode 100644
index 0000000..8402cb1
--- /dev/null
+++ b/apps/patchpanel/src/main/java/org/onosproject/patchpanel/impl/AppUiComponent.java
@@ -0,0 +1,75 @@
+/*
+ * 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.patchpanel.impl;
+
+import com.google.common.collect.ImmutableList;
+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.ui.UiExtension;
+import org.onosproject.ui.UiExtensionService;
+import org.onosproject.ui.UiMessageHandlerFactory;
+import org.onosproject.ui.UiView;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+
+/**
+ *  ONOS UI Custom-View application component for the Patch Panel Application.
+ */
+@Component(immediate = true)
+public class AppUiComponent {
+
+    private static final String VIEW_ID = "sampleCustom";
+    private static final String VIEW_TEXT = "Patch Panel Application";
+
+    private final Logger log = LoggerFactory.getLogger(getClass());
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected UiExtensionService uiExtensionService;
+
+    // List of application views
+    private final List<UiView> uiViews = ImmutableList.of(
+            new UiView(UiView.Category.OTHER, VIEW_ID, VIEW_TEXT)
+    );
+
+    // Factory for UI message handlers
+    private final UiMessageHandlerFactory messageHandlerFactory =
+            () -> ImmutableList.of(new AppUiMessageHandler());
+
+    // Application UI extension
+    protected UiExtension extension =
+            new UiExtension.Builder(getClass().getClassLoader(), uiViews)
+                    .resourcePath(VIEW_ID)
+                    .messageHandlerFactory(messageHandlerFactory)
+                    .build();
+
+    @Activate
+    protected void activate() {
+        uiExtensionService.register(extension);
+        log.info("Started");
+    }
+
+    @Deactivate
+    protected void deactivate() {
+        uiExtensionService.unregister(extension);
+        log.info("Stopped");
+    }
+
+}
diff --git a/apps/patchpanel/src/main/java/org/onosproject/patchpanel/impl/AppUiMessageHandler.java b/apps/patchpanel/src/main/java/org/onosproject/patchpanel/impl/AppUiMessageHandler.java
new file mode 100644
index 0000000..431f4d0
--- /dev/null
+++ b/apps/patchpanel/src/main/java/org/onosproject/patchpanel/impl/AppUiMessageHandler.java
@@ -0,0 +1,139 @@
+/*
+ * 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.patchpanel.impl;
+
+
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.google.common.collect.ImmutableSet;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.ui.RequestHandler;
+import org.onosproject.ui.UiMessageHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.onosproject.net.Device;
+import org.onosproject.net.Port;
+import org.onosproject.net.device.DeviceService;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ *  ONOS UI Custom-View message handler.
+ *
+ *  This class contains the request handlers that handle the response
+ *  to each event. In this particular implementation the second message
+ *  handler creates the patch and the first message handler loads the data
+ */
+public class AppUiMessageHandler extends UiMessageHandler {
+
+    private static final String SAMPLE_CUSTOM_DATA_REQ = "sampleCustomDataRequest";
+    private static final String SAMPLE_CUSTOM_DATA_RESP = "sampleCustomDataResponse";
+    private static final String SAMPLE_CUSTOM_DATA_REQ2 = "sampleCustomDataRequest2";
+    private static final String SAMPLE_CUSTOM_DATA_RESP2 = "sampleCustomDataResponse2";
+    private static final String SAMPLE_CUSTOM_DATA_REQ3 = "sampleCustomDataRequest3";
+    private static final String SAMPLE_CUSTOM_DATA_RESP3 = "sampleCustomDataResponse3";
+    private String message = "";
+    private String cpoints = "";
+    private List<ConnectPoint> previous = new ArrayList<>();
+    private static ConnectPoint cp1;
+    private static ConnectPoint cp2;
+    private final Logger log = LoggerFactory.getLogger(getClass());
+
+    @Override
+    protected Collection<RequestHandler> createRequestHandlers() {
+        return ImmutableSet.of(new DataRequestHandler(), new SecondDataRequestHandler(), new ThirdDataRequestHandler());
+    }
+
+    // handler for data requests/events
+    private final class DataRequestHandler extends RequestHandler {
+
+        private DataRequestHandler() {
+            super(SAMPLE_CUSTOM_DATA_REQ);
+        }
+
+        @Override
+        public void process(long sid, ObjectNode payload) {
+            DeviceService service = get(DeviceService.class);
+            ObjectNode result = objectNode();
+            ArrayNode cps = arrayNode();
+            result.set("cps", cps);
+
+            for (Device device : service.getDevices()) {
+                cps.add(device.id().toString());
+                for (Port port : service.getPorts(device.id())) {
+                    if (!port.number().isLogical()) {
+                        cps.add(port.number().toString());
+                        log.info(device.id().toString() + "/" + port.number());
+                    }
+                }
+            }
+            sendMessage(SAMPLE_CUSTOM_DATA_RESP, 0, result);
+        }
+    }
+
+    private final class SecondDataRequestHandler extends RequestHandler {
+
+        private SecondDataRequestHandler() {
+            super(SAMPLE_CUSTOM_DATA_REQ2);
+        }
+
+        @Override
+        public void process(long sid, ObjectNode payload) {
+            boolean done;
+            String deviceId = payload.get("result").get(0).asText();
+            cp1 = ConnectPoint.deviceConnectPoint(deviceId + "/" + payload.get("result").get(1).asText());
+            cp2 = ConnectPoint.deviceConnectPoint(deviceId + "/" + payload.get("result").get(2).asText());
+            PatchPanelService patchPanelService;
+            patchPanelService = get(PatchPanelService.class);
+            done = patchPanelService.addPatch(cp1, cp2);
+            if (done) {
+                message = "Patch has been created";
+                previous.add(cp1);
+                previous.add(cp2);
+            } else {
+                message = "One or both of these ports are already in use";
+                if (cp1.port().equals(cp2.port())) {
+                    message = "Both ports can not be the same";
+                }
+            }
+            payload.put("message", message);
+            sendMessage(SAMPLE_CUSTOM_DATA_RESP2, sid, payload);
+
+        }
+    }
+    private final class ThirdDataRequestHandler extends RequestHandler {
+        private ThirdDataRequestHandler() {
+            super(SAMPLE_CUSTOM_DATA_REQ3);
+        }
+
+        @Override
+        public void process(long sid, ObjectNode payload) {
+            cpoints = "";
+            for (int i = 0; i < previous.size(); i++) {
+                if (i % 2 == 1) {
+                    cpoints += previous.get(i) + "\n";
+                } else {
+                    cpoints += previous.get(i) + " with ";
+                }
+            }
+            payload.put("cpoints", cpoints);
+            sendMessage(SAMPLE_CUSTOM_DATA_RESP3, sid, payload);
+        }
+    }
+}
\ No newline at end of file
diff --git a/apps/patchpanel/src/main/java/org/onosproject/patchpanel/impl/PatchPanel.java b/apps/patchpanel/src/main/java/org/onosproject/patchpanel/impl/PatchPanel.java
new file mode 100644
index 0000000..068ae00
--- /dev/null
+++ b/apps/patchpanel/src/main/java/org/onosproject/patchpanel/impl/PatchPanel.java
@@ -0,0 +1,111 @@
+/*
+ * 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.
+ */
+
+/**
+ * This class acts as a software patch panel application.
+ * The user specifies 2 connectpoint on the same device that he/she would like to patch.
+ * Using a flow rule, the 2 connectpoints are patched.
+ *
+ * @author Parvahti Meyyappan
+ * @version %I%, %G%
+ */
+
+package org.onosproject.patchpanel.impl;
+
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Reference;
+import org.apache.felix.scr.annotations.Service;
+import org.apache.felix.scr.annotations.ReferenceCardinality;
+import org.apache.felix.scr.annotations.Activate;
+import org.apache.felix.scr.annotations.Deactivate;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.flow.DefaultFlowRule;
+import org.onosproject.net.flow.FlowRuleService;
+import org.onosproject.net.flow.FlowRule;
+import org.onosproject.net.flow.DefaultTrafficSelector;
+import org.onosproject.net.flow.DefaultTrafficTreatment;
+import org.onosproject.net.packet.PacketPriority;
+import org.onosproject.net.ConnectPoint;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import java.util.ArrayList;
+import java.util.List;
+
+
+@Component(immediate = true)
+@Service
+public class PatchPanel implements PatchPanelService {
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected FlowRuleService flowRuleService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected CoreService coreService;
+
+    private List<ConnectPoint> previous = new ArrayList<>();
+    private final Logger log = LoggerFactory.getLogger(getClass());
+    private ApplicationId appId;
+    private ConnectPoint cp1, cp2;
+
+
+    @Activate
+    protected void activate() throws NullPointerException {
+        log.info("Started");
+        try {
+            appId = coreService.getAppId("org.onosproject.patchPanel");
+        } catch (NullPointerException e) {
+            throw new NullPointerException("ERROR:App Id is null");
+        }
+    }
+
+    @Deactivate
+    protected void deactivate() {
+        log.info("Stopped");
+    }
+
+    @Override
+    public boolean addPatch(ConnectPoint num, ConnectPoint num2) {
+        cp1 = num;
+        cp2 = num2;
+        if ((cp1.port().equals(cp2.port())) || (previous.contains(cp1) || previous.contains(cp2))) {
+            log.info("One or both of these ports are already in use, NO FLOW");
+            return false;
+        } else {
+            previous.add(cp1);
+            previous.add(cp2);
+            setFlowRuleService();
+            return true;
+        }
+    }
+
+    public void setFlowRuleService() {
+        PortNumber outPort = cp2.port();
+        PortNumber inPort = cp1.port();
+        FlowRule fr = DefaultFlowRule.builder()
+                .forDevice(cp1.deviceId())
+                .withSelector(DefaultTrafficSelector.builder().matchInPort(inPort).build())
+                .withTreatment(DefaultTrafficTreatment.builder().setOutput(outPort).build())
+                .withPriority(PacketPriority.REACTIVE.priorityValue())
+                .makeTemporary(5)
+                .fromApp(appId).build();
+
+        flowRuleService.applyFlowRules(fr);
+
+    }
+
+}
diff --git a/apps/patchpanel/src/main/java/org/onosproject/patchpanel/impl/PatchPanelService.java b/apps/patchpanel/src/main/java/org/onosproject/patchpanel/impl/PatchPanelService.java
new file mode 100644
index 0000000..64754c0
--- /dev/null
+++ b/apps/patchpanel/src/main/java/org/onosproject/patchpanel/impl/PatchPanelService.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2014 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.patchpanel.impl;
+import org.onosproject.net.ConnectPoint;
+
+/**
+ * A service for the patch panel application to
+ * export and use with the cli .
+ */
+public interface PatchPanelService {
+
+    /**
+     * Get the connectPoints that need to be patched.
+     * @param cp    the first connect point
+     * @param cp2   the second connect point
+     * @return void
+     */
+    public boolean addPatch(ConnectPoint cp, ConnectPoint cp2);
+
+}
\ No newline at end of file
diff --git a/apps/patchpanel/src/main/java/org/onosproject/patchpanel/impl/package-info.java b/apps/patchpanel/src/main/java/org/onosproject/patchpanel/impl/package-info.java
new file mode 100644
index 0000000..6bee0e2
--- /dev/null
+++ b/apps/patchpanel/src/main/java/org/onosproject/patchpanel/impl/package-info.java
@@ -0,0 +1,21 @@
+
+/*
+ * 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.
+ */
+
+/**
+ * patch panel-related CLI commands(in implementation folder).
+ */
+package org.onosproject.patchpanel.impl;