GUI -- Refactoring of server-side message handlers (Part One).

Change-Id: I895cef0545f7ba4b78a2adfa2bad9d889ca0104a
diff --git a/core/api/src/main/java/org/onosproject/ui/JsonUtils.java b/core/api/src/main/java/org/onosproject/ui/JsonUtils.java
new file mode 100644
index 0000000..152fc9b
--- /dev/null
+++ b/core/api/src/main/java/org/onosproject/ui/JsonUtils.java
@@ -0,0 +1,107 @@
+/*
+ * Copyright 2015 Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.ui;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+/**
+ * Provides convenience methods for dealing with JSON nodes, arrays etc.
+ */
+public final class JsonUtils {
+
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    // non-instantiable
+    private JsonUtils() { }
+
+    /**
+     * Wraps a message payload into an event structure for the given event
+     * type and sequence ID. Generally, the sequence ID should be a copy of
+     * the ID from the client request event.
+     *
+     * @param type    event type
+     * @param sid     sequence ID
+     * @param payload event payload
+     * @return the object node representation
+     */
+    public static ObjectNode envelope(String type, long sid, ObjectNode payload) {
+        ObjectNode event = MAPPER.createObjectNode();
+        event.put("event", type);
+        if (sid > 0) {
+            event.put("sid", sid);
+        }
+        event.set("payload", payload);
+        return event;
+    }
+
+    /**
+     * Returns the event type from the specified event.
+     * If the node does not have an "event" property, "unknown" is returned.
+     *
+     * @param event message event
+     * @return extracted event type
+     */
+    public static String eventType(ObjectNode event) {
+        return string(event, "event", "unknown");
+    }
+
+    /**
+     * Returns the payload from the specified event.
+     *
+     * @param event message event
+     * @return extracted payload object
+     */
+    public static ObjectNode payload(ObjectNode event) {
+        return (ObjectNode) event.path("payload");
+    }
+
+    /**
+     * Returns the specified node property as a number.
+     *
+     * @param node message event
+     * @param name property name
+     * @return property as number
+     */
+    public static long number(ObjectNode node, String name) {
+        return node.path(name).asLong();
+    }
+
+    /**
+     * Returns the specified node property as a string.
+     *
+     * @param node message event
+     * @param name property name
+     * @return property as a string
+     */
+    public static String string(ObjectNode node, String name) {
+        return node.path(name).asText();
+    }
+
+    /**
+     * Returns the specified node property as a string, with a default fallback.
+     *
+     * @param node         message event
+     * @param name         property name
+     * @param defaultValue fallback value if property is absent
+     * @return property as a string
+     */
+    public static String string(ObjectNode node, String name, String defaultValue) {
+        return node.path(name).asText(defaultValue);
+    }
+
+}
diff --git a/core/api/src/main/java/org/onosproject/ui/UiMessageHandler.java b/core/api/src/main/java/org/onosproject/ui/UiMessageHandler.java
index d9c1510..0482162 100644
--- a/core/api/src/main/java/org/onosproject/ui/UiMessageHandler.java
+++ b/core/api/src/main/java/org/onosproject/ui/UiMessageHandler.java
@@ -138,13 +138,17 @@
      * @return the object node representation
      */
     protected ObjectNode envelope(String type, long sid, ObjectNode payload) {
-        ObjectNode event = mapper.createObjectNode();
-        event.put("event", type);
-        if (sid > 0) {
-            event.put("sid", sid);
-        }
-        event.set("payload", payload);
-        return event;
+        return JsonUtils.envelope(type, sid, payload);
+    }
+
+    /**
+     * Returns the event type from the specified event.
+     *
+     * @param event the event
+     * @return the event type
+     */
+    protected String eventType(ObjectNode event) {
+        return JsonUtils.eventType(event);
     }
 
     /**
@@ -154,7 +158,7 @@
      * @return extracted payload object
      */
     protected ObjectNode payload(ObjectNode event) {
-        return (ObjectNode) event.path("payload");
+        return JsonUtils.payload(event);
     }
 
     /**
@@ -165,7 +169,7 @@
      * @return property as number
      */
     protected long number(ObjectNode node, String name) {
-        return node.path(name).asLong();
+        return JsonUtils.number(node, name);
     }
 
     /**
@@ -176,7 +180,7 @@
      * @return property as a string
      */
     protected String string(ObjectNode node, String name) {
-        return node.path(name).asText();
+        return JsonUtils.string(node, name);
     }
 
     /**
@@ -188,7 +192,21 @@
      * @return property as a string
      */
     protected String string(ObjectNode node, String name, String defaultValue) {
-        return node.path(name).asText(defaultValue);
+        return JsonUtils.string(node, name, defaultValue);
     }
 
+    /**
+     * Concatenates an arbitrary number of objects, using their
+     * toString() methods.
+     *
+     * @param items the items to concatenate
+     * @return a concatenated string
+     */
+    protected static String concat(Object... items) {
+        StringBuilder sb = new StringBuilder();
+        for (Object o : items) {
+            sb.append(o);
+        }
+        return sb.toString();
+    }
 }
diff --git a/core/api/src/main/java/org/onosproject/ui/table/AbstractTableRow.java b/core/api/src/main/java/org/onosproject/ui/table/AbstractTableRow.java
new file mode 100644
index 0000000..32a4396
--- /dev/null
+++ b/core/api/src/main/java/org/onosproject/ui/table/AbstractTableRow.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright 2015 Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.ui.table;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+import java.util.HashMap;
+import java.util.Map;
+
+
+/**
+ * Provides a partial implementation of {@link TableRow}.
+ */
+public abstract class AbstractTableRow implements TableRow {
+
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    private final Map<String, String> cells = new HashMap<>();
+
+    @Override
+    public String get(String key) {
+        return cells.get(key);
+    }
+
+    @Override
+    public ObjectNode toJsonNode() {
+        ObjectNode result = MAPPER.createObjectNode();
+        for (String id : columnIds()) {
+            result.put(id, cells.get(id));
+        }
+        return result;
+    }
+
+    /**
+     * Subclasses must provide the list of column IDs.
+     *
+     * @return array of column IDs
+     */
+    protected abstract String[] columnIds();
+
+    /**
+     * Add a column ID to cell value binding.
+     *
+     * @param id the column ID
+     * @param value the cell value
+     */
+    protected void add(String id, String value) {
+        cells.put(id, value);
+    }
+
+    /**
+     * Add a column ID to cell value binding.
+     * Note that value.toString() is invoked.
+     *
+     * @param id the column ID
+     * @param value the cell value
+     */
+    protected void add(String id, Object value) {
+        cells.put(id, value.toString());
+    }
+}
diff --git a/core/api/src/main/java/org/onosproject/ui/table/RowComparator.java b/core/api/src/main/java/org/onosproject/ui/table/RowComparator.java
new file mode 100644
index 0000000..9859a65
--- /dev/null
+++ b/core/api/src/main/java/org/onosproject/ui/table/RowComparator.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2015 Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.ui.table;
+
+import java.util.Comparator;
+
+/**
+ * Comparator for {@link TableRow}.
+ */
+public class RowComparator implements Comparator<TableRow> {
+    /** Designates the sort direction. */
+    public enum Direction {
+        /** Sort Ascending. */
+        ASC,
+        /** Sort Descending. */
+        DESC
+    }
+
+    public static final String DESC_STR = "desc";
+
+    private final String colId;
+    private final Direction dir;
+
+    /**
+     * Constructs a comparator for table rows that uses the given
+     * column ID and direction.
+     *
+     * @param colId the column to sort on
+     * @param dir the direction to sort in
+     */
+    public RowComparator(String colId, Direction dir) {
+        if (colId == null || dir == null) {
+            throw new NullPointerException("Null parameters not allowed");
+        }
+        this.colId = colId;
+        this.dir = dir;
+    }
+
+    @Override
+    public int compare(TableRow a, TableRow b) {
+        String cellA = a.get(colId);
+        String cellB = b.get(colId);
+
+        if (dir.equals(Direction.ASC)) {
+            return cellA.compareTo(cellB);
+        }
+        return cellB.compareTo(cellA);
+    }
+
+    /**
+     * Returns the sort direction constant for the given string.
+     * The expected strings are "asc" and "desc"; defaults to "asc".
+     *
+     * @param s the direction as a string
+     * @return the constant
+     */
+    public static Direction direction(String s) {
+        return DESC_STR.equals(s) ? Direction.DESC : Direction.ASC;
+    }
+}
diff --git a/core/api/src/main/java/org/onosproject/ui/table/TableRow.java b/core/api/src/main/java/org/onosproject/ui/table/TableRow.java
new file mode 100644
index 0000000..4775687
--- /dev/null
+++ b/core/api/src/main/java/org/onosproject/ui/table/TableRow.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2015 Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.ui.table;
+
+
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+/**
+ * Defines a table row abstraction to support sortable tables on the GUI.
+ */
+public interface TableRow {
+
+    // TODO: Define TableCell interface and return that, rather than String
+    // The hope is that this will allow us to write a generic mechanism for
+    // selecting a comparator based on the cell type for the column, to be
+    // used for sorting the table rows.
+    /**
+     * Returns the value of the cell for the given column ID.
+     *
+     * @param key the column ID
+     * @return the cell value
+     */
+    String get(String key);
+
+    /**
+     * Returns this table row in the form of a JSON object.
+     *
+     * @return the JSON node
+     */
+    ObjectNode toJsonNode();
+}
diff --git a/core/api/src/main/java/org/onosproject/ui/table/TableUtils.java b/core/api/src/main/java/org/onosproject/ui/table/TableUtils.java
new file mode 100644
index 0000000..9f63cba
--- /dev/null
+++ b/core/api/src/main/java/org/onosproject/ui/table/TableUtils.java
@@ -0,0 +1,77 @@
+/*
+ * Copyright 2015 Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.ui.table;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.onosproject.ui.JsonUtils;
+
+/**
+ * Provides static utility methods for dealing with tables.
+ */
+public final class TableUtils {
+
+    private static final ObjectMapper MAPPER = new ObjectMapper();
+
+    // non-instantiable
+    private TableUtils() { }
+
+    /**
+     * Produces a JSON array node from the specified table rows.
+     *
+     * @param rows table rows
+     * @return JSON array
+     */
+    public static ArrayNode generateArrayNode(TableRow[] rows) {
+        ArrayNode array = MAPPER.createArrayNode();
+        for (TableRow r : rows) {
+            array.add(r.toJsonNode());
+        }
+        return array;
+    }
+
+    /**
+     * Creates a row comparator for the given request. The ID of the column
+     * to sort on is the payload's "sortCol" property (defaults to "id").
+     * The direction for the sort is the payload's "sortDir" property
+     * (defaults to "asc").
+     *
+     * @param payload the event payload
+     * @return a row comparator
+     */
+    public static RowComparator createRowComparator(ObjectNode payload) {
+        return createRowComparator(payload, "id");
+    }
+
+    /**
+     * Creates a row comparator for the given request. The ID of the column to
+     * sort on is the payload's "sortCol" property (or the specified default).
+     * The direction for the sort is the payload's "sortDir" property
+     * (defaults to "asc").
+     *
+     * @param payload the event payload
+     * @param defColId the default column ID
+     * @return a row comparator
+     */
+    public static RowComparator createRowComparator(ObjectNode payload,
+                                                    String defColId) {
+        String sortCol = JsonUtils.string(payload, "sortCol", defColId);
+        String sortDir = JsonUtils.string(payload, "sortDir", "asc");
+        return new RowComparator(sortCol, RowComparator.direction(sortDir));
+    }
+}