UI-Lion: Migrate BundleStitcher and LionConfig to web.gui module.

Change-Id: Id744e8a3a33621d69379b2286d1cd29770f16e57
diff --git a/web/gui/src/main/java/org/onosproject/ui/impl/UiExtensionManager.java b/web/gui/src/main/java/org/onosproject/ui/impl/UiExtensionManager.java
index 85935de..83af0d7 100644
--- a/web/gui/src/main/java/org/onosproject/ui/impl/UiExtensionManager.java
+++ b/web/gui/src/main/java/org/onosproject/ui/impl/UiExtensionManager.java
@@ -225,7 +225,7 @@
         return new UiExtension.Builder(CL, coreViews)
                 // TODO: currently broken, until BundleStitcher & LionConfig
                 //        have been moved to web.gui module...
-//                .lionBundles(generateLionBundles(LION_BASE, LION_TAGS))
+//                .lionBundles(generateBundles(LION_BASE, LION_TAGS))
                 .messageHandlerFactory(messageHandlerFactory)
                 .topoOverlayFactory(topoOverlayFactory)
                 .topo2OverlayFactory(topo2OverlayFactory)
diff --git a/web/gui/src/main/java/org/onosproject/ui/impl/lion/BundleStitcher.java b/web/gui/src/main/java/org/onosproject/ui/impl/lion/BundleStitcher.java
new file mode 100644
index 0000000..aaeab93
--- /dev/null
+++ b/web/gui/src/main/java/org/onosproject/ui/impl/lion/BundleStitcher.java
@@ -0,0 +1,166 @@
+/*
+ * Copyright 2017-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.ui.impl.lion;
+
+import com.google.common.collect.ImmutableList;
+import org.onosproject.ui.lion.LionBundle;
+import org.onosproject.ui.lion.LionUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.ResourceBundle;
+import java.util.Set;
+
+/**
+ * Gathers and stitches together a localization bundle according to a
+ * "lion" configuration file.
+ */
+public class BundleStitcher {
+
+    private static final Logger log =
+            LoggerFactory.getLogger(BundleStitcher.class);
+
+    private static final String CONFIG_DIR = "_config";
+    private static final String SUFFIX = ".lioncfg";
+    private static final String SLASH = "/";
+    private static final String DOT = ".";
+
+
+    private final String base;
+
+    /**
+     * Creates a bundle stitcher, configured with the specified base resource
+     * path.
+     *
+     * @param base the base resource path
+     */
+    public BundleStitcher(String base) {
+        this.base = base;
+    }
+
+    @Override
+    public String toString() {
+        return "BundleStitcher{base=\"" + base + "\"}";
+    }
+
+    /**
+     * Stitches together a LionBundle, based on the bundle configuration data
+     * for the given bundle ID.
+     *
+     * @param id the bundle ID
+     * @return a corresponding lion bundle
+     * @throws IllegalArgumentException if the bundle config cannot be loaded
+     */
+    public LionBundle stitch(String id) {
+        String source = base + SLASH + CONFIG_DIR + SLASH + id + SUFFIX;
+        LionConfig cfg = new LionConfig().load(source);
+        LionBundle.Builder builder = new LionBundle.Builder(id);
+
+        for (LionConfig.CmdFrom from : cfg.entries()) {
+            addItemsToBuilder(builder, from);
+        }
+
+        return builder.build();
+    }
+
+    private void addItemsToBuilder(LionBundle.Builder builder,
+                                   LionConfig.CmdFrom from) {
+        String resBundleName = base + SLASH + from.res();
+        String resFqbn = convertToFqbn(resBundleName);
+        ResourceBundle bundle = LionUtils.getBundledResource(resFqbn);
+
+        if (from.starred()) {
+            addAllItems(builder, bundle);
+        } else {
+            addItems(builder, bundle, from.keys());
+        }
+    }
+
+    // to fully-qualified-bundle-name
+    private String convertToFqbn(String path) {
+        if (!path.startsWith(SLASH)) {
+            throw new IllegalArgumentException("path should start with '/'");
+        }
+        return path.substring(1).replaceAll(SLASH, DOT);
+    }
+
+    private void addAllItems(LionBundle.Builder builder, ResourceBundle bundle) {
+        addItems(builder, bundle, bundle.keySet());
+    }
+
+    private void addItems(LionBundle.Builder builder, ResourceBundle bundle,
+                          Set<String> keys) {
+        keys.forEach(k -> builder.addItem(k, bundle.getString(k)));
+    }
+
+    /**
+     * Generates an immutable list of localization bundles, using the specified
+     * resource tree (base) and localization configuration file names (tags).
+     * <p>
+     * As an example, you might invoke:
+     * <pre>
+     * private static final String LION_BASE = "/org/onosproject/ui/lion";
+     *
+     * private static final String[] LION_TAGS = {
+     *     "core.view.App",
+     *     "core.view.Settings",
+     *     "core.view.Cluster",
+     *     "core.view.Processor",
+     *     "core.view.Partition",
+     * };
+     *
+     * List&lt;LionBundle&gt; bundles =
+     *      LionUtils.generateBundles(LION_BASE, LION_TAGS);
+     * </pre>
+     * It is expected that in the "LION_BASE" directory there is a subdirectory
+     * named "_config" which contains the configuration files listed in the
+     * "LION_TAGS" array, each with a ".lioncfg" suffix...
+     * <pre>
+     * /org/onosproject/ui/lion/
+     *   |
+     *   +-- _config
+     *         |
+     *         +-- core.view.App.lioncfg
+     *         +-- core.view.Settings.lioncfg
+     *         :
+     * </pre>
+     * These files collate a localization bundle for their particular view
+     * by referencing resource bundles and their keys.
+     *
+     * @param base the base resource directory path
+     * @param tags the list of bundles to generate
+     * @return a list of generated localization bundles
+     */
+    public static List<LionBundle> generateBundles(String base,
+                                                   String... tags) {
+        List<LionBundle> result = new ArrayList<>(tags.length);
+        BundleStitcher stitcher = new BundleStitcher(base);
+        for (String tag : tags) {
+            try {
+                LionBundle b = stitcher.stitch(tag);
+                result.add(b);
+
+            } catch (IllegalArgumentException e) {
+                log.warn("Unable to generate bundle: {} / {}", base, tag);
+            }
+        }
+        return ImmutableList.copyOf(result);
+    }
+}
diff --git a/web/gui/src/main/java/org/onosproject/ui/impl/lion/LionConfig.java b/web/gui/src/main/java/org/onosproject/ui/impl/lion/LionConfig.java
new file mode 100644
index 0000000..0fa520a
--- /dev/null
+++ b/web/gui/src/main/java/org/onosproject/ui/impl/lion/LionConfig.java
@@ -0,0 +1,413 @@
+/*
+ * Copyright 2017-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.ui.impl.lion;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSortedSet;
+import org.apache.commons.io.IOUtils;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+
+/**
+ * A Java representation of a lion configuration file. You can create one with
+ * something like the following:
+ * <pre>
+ *     String filepath = "/path/to/some/file.lioncfg";
+ *     LionConfig cfg = new LionConfig().load(filepath);
+ * </pre>
+ */
+public class LionConfig {
+    private static final Pattern RE_COMMENT = Pattern.compile("^\\s*#.*");
+    private static final Pattern RE_BLANK = Pattern.compile("^\\s*$");
+
+    static final Pattern RE_IMPORT =
+            Pattern.compile("^(\\S+)\\s+import\\s+(.*)$");
+
+    private static final String BUNDLE = "bundle";
+    private static final String ALIAS = "alias";
+    private static final String FROM = "from";
+    private static final String STAR = "*";
+    private static final char SPC = ' ';
+    private static final char DOT = '.';
+
+    private List<String> lines;
+    private List<String> badLines;
+
+    private CmdBundle bundle;
+    private final Set<CmdAlias> aliases = new TreeSet<>();
+    private final Set<CmdFrom> froms = new TreeSet<>();
+
+    private Map<String, String> aliasMap;
+    private Map<String, Set<String>> fromMap;
+
+    /**
+     * Loads in the specified file and attempts to parse it as a
+     * {@code .lioncfg} format file.
+     *
+     * @param source path to .lioncfg file
+     * @return the instance
+     * @throws IllegalArgumentException if there is a problem reading the file
+     */
+    public LionConfig load(String source) {
+        InputStream is = getClass().getResourceAsStream(source);
+        try {
+            lines = IOUtils.readLines(is, UTF_8);
+        } catch (NullPointerException | IOException e) {
+            throw new IllegalArgumentException("Failed to read: " + source, e);
+        }
+
+        stripCommentsAndWhitespace();
+        parse();
+        processAliases();
+        processFroms();
+
+        return this;
+    }
+
+
+    private boolean isCommentOrBlank(String s) {
+        return RE_COMMENT.matcher(s).matches() || RE_BLANK.matcher(s).matches();
+    }
+
+
+    private void stripCommentsAndWhitespace() {
+        if (lines != null) {
+            lines.removeIf(this::isCommentOrBlank);
+        }
+    }
+
+    private void parse() {
+        badLines = new ArrayList<>();
+
+        lines.forEach(l -> {
+            int i = l.indexOf(SPC);
+            if (i < 1) {
+                badLines.add(l);
+                return;
+            }
+            String keyword = l.substring(0, i);
+            String params = l.substring(i + 1);
+
+            switch (keyword) {
+                case BUNDLE:
+                    CmdBundle cb = new CmdBundle(l, params);
+
+                    if (bundle != null) {
+                        // we can only declare the bundle once
+                        badLines.add(l);
+                    } else {
+                        bundle = cb;
+                    }
+                    break;
+
+                case ALIAS:
+                    CmdAlias ca = new CmdAlias(l, params);
+                    if (ca.malformed) {
+                        badLines.add(l);
+                    } else {
+                        aliases.add(ca);
+                    }
+                    break;
+
+                case FROM:
+                    CmdFrom cf = new CmdFrom(l, params);
+                    if (cf.malformed) {
+                        badLines.add(l);
+                    } else {
+                        froms.add(cf);
+                    }
+                    break;
+
+                default:
+                    badLines.add(l);
+                    break;
+            }
+        });
+    }
+
+    private void processAliases() {
+        aliasMap = new HashMap<>(aliasCount());
+        aliases.forEach(a -> aliasMap.put(a.alias, a.subst));
+    }
+
+    private void processFroms() {
+        fromMap = new HashMap<>(fromCount());
+        froms.forEach(f -> {
+            f.expandAliasIfAny(aliasMap);
+            if (singleStarCheck(f)) {
+                fromMap.put(f.expandedRes, f.keys);
+            } else {
+                badLines.add(f.orig);
+            }
+        });
+    }
+
+    private boolean singleStarCheck(CmdFrom from) {
+        from.starred = false;
+        Set<String> keys = from.keys();
+        for (String k : keys) {
+            if (STAR.equals(k)) {
+                from.starred = true;
+            }
+        }
+        return !from.starred || keys.size() == 1;
+    }
+
+    @Override
+    public String toString() {
+        int nlines = lines == null ? 0 : lines.size();
+        return String.format("LionConfig{#lines=%d}", nlines);
+    }
+
+    /**
+     * Returns the configured bundle ID for this config.
+     *
+     * @return the bundle ID
+     */
+    String id() {
+        return bundle == null ? null : bundle.id;
+    }
+
+    /**
+     * Returns the number of aliases configured in this config.
+     *
+     * @return the alias count
+     */
+    int aliasCount() {
+        return aliases.size();
+    }
+
+    /**
+     * Returns the number of from...import lines configured in this config.
+     *
+     * @return the number of from...import lines
+     */
+    int fromCount() {
+        return froms.size();
+    }
+
+    /**
+     * Returns the substitution string for the given alias.
+     *
+     * @param a the alias
+     * @return the substitution
+     */
+    String alias(String a) {
+        return aliasMap.get(a);
+    }
+
+    /**
+     * Returns the number of keys imported from the specified resource.
+     *
+     * @param res the resource
+     * @return number of keys imported from that resource
+     */
+    int fromKeyCount(String res) {
+        Set<String> keys = fromMap.get(res);
+        return keys == null ? 0 : keys.size();
+    }
+
+    /**
+     * Returns true if the specified resource exists and contains the
+     * given key.
+     *
+     * @param res the resource
+     * @param key the key
+     * @return true, if resource exists and contains the key; false otherwise
+     */
+    boolean fromContains(String res, String key) {
+        Set<String> keys = fromMap.get(res);
+        return keys != null && keys.contains(key);
+    }
+
+    /**
+     * Returns the set of (expanded) "from" entries in this configuration.
+     *
+     * @return the entries
+     */
+    public Set<CmdFrom> entries() {
+        return froms;
+    }
+
+    /**
+     * Returns the number of parse errors detected.
+     *
+     * @return number of bad lines
+     */
+    public int errorCount() {
+        return badLines.size();
+    }
+
+    /**
+     * Returns the lines that failed the parser.
+     *
+     * @return the erroneous lines in the config
+     */
+    public List<String> errorLines() {
+        return ImmutableList.copyOf(badLines);
+    }
+
+    // ==== Mini class hierarchy of command types
+
+    private abstract static class Cmd {
+        final String orig;
+        boolean malformed = false;
+
+        Cmd(String orig) {
+            this.orig = orig;
+        }
+    }
+
+    private static final class CmdBundle extends Cmd {
+        private final String id;
+
+        private CmdBundle(String orig, String params) {
+            super(orig);
+            id = params;
+        }
+
+        @Override
+        public String toString() {
+            return "CmdBundle{id=\"" + id + "\"}";
+        }
+    }
+
+    private static final class CmdAlias extends Cmd
+            implements Comparable<CmdAlias> {
+        private final String alias;
+        private final String subst;
+
+        private CmdAlias(String orig, String params) {
+            super(orig);
+            int i = params.indexOf(SPC);
+            if (i < 1) {
+                malformed = true;
+                alias = null;
+                subst = null;
+            } else {
+                alias = params.substring(0, i);
+                subst = params.substring(i + 1);
+            }
+        }
+
+        @Override
+        public String toString() {
+            return "CmdAlias{alias=\"" + alias + "\", subst=\"" + subst + "\"}";
+        }
+
+        @Override
+        public int compareTo(CmdAlias o) {
+            return alias.compareTo(o.alias);
+        }
+    }
+
+    /**
+     * Represents a "from {res} import {stuff}" command in the configuration.
+     */
+    public static final class CmdFrom extends Cmd
+            implements Comparable<CmdFrom> {
+        private final String rawRes;
+        private final Set<String> keys;
+        private String expandedRes;
+        private boolean starred = false;
+
+        private CmdFrom(String orig, String params) {
+            super(orig);
+            Matcher m = RE_IMPORT.matcher(params);
+            if (!m.matches()) {
+                malformed = true;
+                rawRes = null;
+                keys = null;
+            } else {
+                rawRes = m.group(1);
+                keys = genKeys(m.group(2));
+            }
+        }
+
+        private Set<String> genKeys(String keys) {
+            String[] k = keys.split("\\s*,\\s*");
+            Set<String> allKeys = new HashSet<>();
+            Collections.addAll(allKeys, k);
+            return ImmutableSortedSet.copyOf(allKeys);
+        }
+
+        private void expandAliasIfAny(Map<String, String> aliases) {
+            String expanded = rawRes;
+            int i = rawRes.indexOf(DOT);
+            if (i > 0) {
+                String alias = rawRes.substring(0, i);
+                String sub = aliases.get(alias);
+                if (sub != null) {
+                    expanded = sub + rawRes.substring(i);
+                }
+            }
+            expandedRes = expanded;
+        }
+
+        @Override
+        public String toString() {
+            return "CmdFrom{res=\"" + rawRes + "\", keys=" + keys + "}";
+        }
+
+        @Override
+        public int compareTo(CmdFrom o) {
+            return rawRes.compareTo(o.rawRes);
+        }
+
+        /**
+         * Returns the resource bundle name from which to import things.
+         *
+         * @return the resource bundle name
+         */
+        public String res() {
+            return expandedRes;
+        }
+
+        /**
+         * Returns the set of keys which should be imported.
+         *
+         * @return the keys to import
+         */
+        public Set<String> keys() {
+            return keys;
+        }
+
+        /**
+         * Returns true if this "from" command is importing ALL keys from
+         * the specified resource; false otherwise.
+         *
+         * @return true, if importing ALL keys; false otherwise
+         */
+        public boolean starred() {
+            return starred;
+        }
+    }
+}
diff --git a/web/gui/src/main/java/org/onosproject/ui/impl/lion/package-info.java b/web/gui/src/main/java/org/onosproject/ui/impl/lion/package-info.java
new file mode 100644
index 0000000..f8566fa
--- /dev/null
+++ b/web/gui/src/main/java/org/onosproject/ui/impl/lion/package-info.java
@@ -0,0 +1,21 @@
+/*
+ * Copyright 2017-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.
+ *
+ */
+
+/**
+ * Set of resources providing localization utilities for the ONOS GUI.
+ */
+package org.onosproject.ui.impl.lion;
diff --git a/web/gui/src/test/java/org/onosproject/ui/impl/lion/BundleStitcherTest.java b/web/gui/src/test/java/org/onosproject/ui/impl/lion/BundleStitcherTest.java
new file mode 100644
index 0000000..e5ae6a6
--- /dev/null
+++ b/web/gui/src/test/java/org/onosproject/ui/impl/lion/BundleStitcherTest.java
@@ -0,0 +1,148 @@
+/*
+ * Copyright 2017-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.ui.impl.lion;
+
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.onosproject.ui.AbstractUiTest;
+import org.onosproject.ui.lion.LionBundle;
+
+import java.util.List;
+import java.util.Locale;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Unit tests for {@link BundleStitcher}.
+ */
+public class BundleStitcherTest extends AbstractUiTest {
+
+    private static final String LION_BASE = "/org/onosproject/ui/lion";
+
+    private static final String[] LION_TAGS = {"CardGame1"};
+
+
+    private static final String[] CARD_GAME_1_KEYS = {
+            "of", "flush", "full_house", "pair", "three_oak",
+            "ace", "king", "queen", "jack", "ten",
+            "spades", "clubs",
+    };
+
+    private static final String[] CARD_GAME_1_ENGLISH = {
+            "of", "Flush", "Full House", "Pair", "Three of a Kind",
+            "Ace", "King", "Queen", "Jack", "Ten",
+            "Spades", "Clubs",
+    };
+
+    // TODO: Andrea to Localize to Italian
+    private static final String[] CARD_GAME_1_ITALIAN = {
+            "of", "Flush", "Full House", "Pair", "Three of a Kind",
+            "Ace", "King", "Queen", "Jack", "Ten",
+            "Spades", "Clubs",
+    };
+
+    private static Locale systemLocale;
+
+    private LionBundle lion;
+
+    @BeforeClass
+    public static void classSetup() {
+        systemLocale = Locale.getDefault();
+    }
+
+    @AfterClass
+    public static void classTeardown() {
+        Locale.setDefault(systemLocale);
+    }
+
+    @Before
+    public void testSetup() {
+        // reset to a known default locale before starting each test
+        Locale.setDefault(Locale.US);
+    }
+
+
+    private BundleStitcher testStitcher() {
+        return new BundleStitcher(LION_BASE);
+    }
+
+    private void verifyItems(LionBundle lion, String[] values) {
+        final int max = values.length;
+        for (int i = 0; i < max; i++) {
+            String key = CARD_GAME_1_KEYS[i];
+            String expValue = values[i];
+            String actValue = lion.getValue(key);
+            assertEquals("wrong mapping", expValue, actValue);
+        }
+    }
+
+    // -- Testing generateLionBundles(...)
+
+    @Test
+    public void generateBundles() {
+        title("generateBundles");
+        List<LionBundle> bundles =
+                BundleStitcher.generateBundles(LION_BASE, LION_TAGS);
+        print(bundles);
+        assertEquals("missing the bundle", 1, bundles.size());
+
+        LionBundle b = bundles.get(0);
+        assertEquals("wrong id", "CardGame1", b.id());
+        assertEquals("unexpected item count", 12, b.size());
+        assertEquals("missing 3oak", "Three of a Kind", b.getValue("three_oak"));
+        assertEquals("missing queen", "Queen", b.getValue("queen"));
+        assertEquals("missing clubs", "Clubs", b.getValue("clubs"));
+    }
+
+    @Test
+    public void cardGame1English() {
+        title("cardGame1English");
+        // use default locale (en_US)
+
+        lion = testStitcher().stitch("CardGame1");
+        print(lion);
+        assertEquals("wrong key", "CardGame1", lion.id());
+        assertEquals("bad key count", 12, lion.size());
+        verifyItems(lion, CARD_GAME_1_ENGLISH);
+    }
+
+    /*
+     * TODO: Andrea to localize
+     * Under: ${ONOS_ROOT}/web/gui/src/test/resources/
+     *
+     * Bundles to Localize:
+     *    org/onosproject/ui/lion/app/Cards.properties
+     *    org/onosproject/ui/lion/core/stuff/Rank.properties
+     *    org/onosproject/ui/lion/core/stuff/Suit.properties
+     */
+    @Ignore("Andrea to localize bundles to Italian")
+    @Test
+    public void cardGame1Italian() {
+        title("cardGame1Italian");
+        Locale.setDefault(Locale.ITALIAN);
+
+        lion = testStitcher().stitch("CardGame1");
+        print(lion);
+        assertEquals("wrong key", "CardGame1", lion.id());
+        assertEquals("bad key count", 12, lion.size());
+        verifyItems(lion, CARD_GAME_1_ITALIAN);
+    }
+}
diff --git a/web/gui/src/test/java/org/onosproject/ui/impl/lion/LionConfigTest.java b/web/gui/src/test/java/org/onosproject/ui/impl/lion/LionConfigTest.java
new file mode 100644
index 0000000..5e4f1dc
--- /dev/null
+++ b/web/gui/src/test/java/org/onosproject/ui/impl/lion/LionConfigTest.java
@@ -0,0 +1,177 @@
+/*
+ * Copyright 2017-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.ui.impl.lion;
+
+import org.junit.Test;
+import org.onosproject.ui.AbstractUiTest;
+
+import java.util.regex.Matcher;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Unit tests for {@link LionConfig}.
+ */
+public class LionConfigTest extends AbstractUiTest {
+
+    private static final String ROOT = "/org/onosproject/ui/lion/";
+    private static final String CMD_ROOT = ROOT + "_cmd/";
+    private static final String CONFIG_ROOT = ROOT + "_config/";
+
+    private static final String SUFFIX = ".lioncfg";
+
+    private static final String CARD_GAME_1 = CONFIG_ROOT + "CardGame1" + SUFFIX;
+
+    private LionConfig cfg;
+    private LionConfig.CmdFrom from;
+
+
+    private String cmdPath(String name) {
+        return CMD_ROOT + name + SUFFIX;
+    }
+
+    private String configPath(String name) {
+        return CONFIG_ROOT + name + SUFFIX;
+    }
+
+    private LionConfig cfg() {
+        return new LionConfig();
+    }
+
+    private void verifyStats(String expId, int expAliases, int expFroms) {
+        assertEquals("wrong bundle ID", expId, cfg.id());
+        assertEquals("wrong alias count", expAliases, cfg.aliasCount());
+        assertEquals("wrong from count", expFroms, cfg.fromCount());
+    }
+
+    private void verifyKeys(String res, String... keys) {
+        int nkeys = keys.length;
+        for (String k: keys) {
+            assertEquals("key not found: " + k, true, cfg.fromContains(res, k));
+        }
+        assertEquals("wrong key count", nkeys, cfg.fromKeyCount(res));
+    }
+
+    @Test
+    public void importMatch() {
+        title("importMatch");
+        String fromParams = "cs.rank import *";
+        Matcher m = LionConfig.RE_IMPORT.matcher(fromParams);
+        assertEquals("no match", true, m.matches());
+        assertEquals("bad group 1", "cs.rank", m.group(1));
+        assertEquals("bad group 2", "*", m.group(2));
+    }
+
+    @Test
+    public void basic() {
+        title("basic");
+        cfg = cfg().load(CARD_GAME_1);
+        print(cfg);
+        verifyStats("CardGame1", 1, 3);
+    }
+
+    @Test
+    public void cmd01GoodBundle() {
+        title("cmd01GoodBundle");
+        cfg = cfg().load(cmdPath("01-bundle"));
+        verifyStats("foo.bar", 0, 0);
+        assertEquals("wrong ID", "foo.bar", cfg.id());
+    }
+
+    @Test
+    public void cmd02GoodAlias() {
+        title("cmd02GoodAlias");
+        cfg = cfg().load(cmdPath("02-alias"));
+        verifyStats(null, 1, 0);
+        assertEquals("alias/subst not found", "xyzzy.wizard", cfg.alias("xy"));
+    }
+
+    @Test
+    public void cmd03GoodFrom() {
+        title("cmd03GoodFrom");
+        cfg = cfg().load(cmdPath("03-from"));
+        verifyStats(null, 0, 1);
+        assertEquals("from/keys bad count", 0, cfg.fromKeyCount("non.exist"));
+        assertEquals("from/keys bad count", 1, cfg.fromKeyCount("foo.bar"));
+        assertEquals("from/keys not found", true,
+                     cfg.fromContains("foo.bar", "fizzbuzz"));
+
+        from = cfg.entries().iterator().next();
+        assertFalse("expected no star", from.starred());
+    }
+
+    @Test
+    public void cmd04GoodFromFour() {
+        title("cmd04GoodFromFour");
+        cfg = cfg().load(cmdPath("04-from-four"));
+        assertEquals("from/keys bad count", 4, cfg.fromKeyCount("hooray"));
+        verifyKeys("hooray", "ford", "arthur", "joe", "henry");
+    }
+
+    @Test
+    public void cmd05FromExpand() {
+        title("cmd05FromExpand");
+        cfg = cfg().load(cmdPath("05-from-expand"));
+        assertEquals("no expand 1", 0, cfg.fromKeyCount("xy.spell"));
+        assertEquals("no expand 2", 0, cfg.fromKeyCount("xy.learn"));
+        verifyKeys("xyzzy.wizard.spell", "zonk", "zip", "zuffer");
+        verifyKeys("xyzzy.wizard.learn", "zap", "zigzag");
+    }
+
+    @Test
+    public void cmd06FromStar() {
+        title("cmd06FromStar");
+        cfg = cfg().load(cmdPath("06-from-star"));
+        print(cfg);
+        assertEquals("bad from count", 1, cfg.fromCount());
+
+        from = cfg.entries().iterator().next();
+        assertTrue("expected a star", from.starred());
+    }
+
+    @Test
+    public void cmd07StarIsSpecial() {
+        title("cmd06StarIsSpecial");
+        cfg = cfg().load(cmdPath("07-star-is-special"));
+        print(cfg);
+        assertEquals("no error detected", 3, cfg.errorCount());
+
+        int iBad = 0;
+        for (String line: cfg.errorLines()) {
+            print(line);
+            iBad++;
+            String prefix = "from star.bad" + iBad + " import ";
+            assertTrue("unexpected bad line", line.startsWith(prefix));
+        }
+    }
+
+    @Test
+    public void cardGameConfig() {
+        title("cardGameConfig");
+        cfg = cfg().load(configPath("CardGame1"));
+        assertEquals("wrong id", "CardGame1", cfg.id());
+        assertEquals("wrong alias count", 1, cfg.aliasCount());
+        assertEquals("wrong from count", 3, cfg.fromCount());
+
+        verifyKeys("app.Cards", "*");
+        verifyKeys("core.stuff.Rank", "ten", "jack", "queen", "king", "ace");
+        verifyKeys("core.stuff.Suit", "spades", "clubs");
+    }
+}
diff --git a/web/gui/src/test/resources/org/onosproject/ui/lion/_cmd/01-bundle.lioncfg b/web/gui/src/test/resources/org/onosproject/ui/lion/_cmd/01-bundle.lioncfg
new file mode 100644
index 0000000..127de70
--- /dev/null
+++ b/web/gui/src/test/resources/org/onosproject/ui/lion/_cmd/01-bundle.lioncfg
@@ -0,0 +1,2 @@
+# 01. test the bundle command
+bundle foo.bar
\ No newline at end of file
diff --git a/web/gui/src/test/resources/org/onosproject/ui/lion/_cmd/02-alias.lioncfg b/web/gui/src/test/resources/org/onosproject/ui/lion/_cmd/02-alias.lioncfg
new file mode 100644
index 0000000..1bdba86
--- /dev/null
+++ b/web/gui/src/test/resources/org/onosproject/ui/lion/_cmd/02-alias.lioncfg
@@ -0,0 +1,2 @@
+# 02. good alias
+alias xy xyzzy.wizard
diff --git a/web/gui/src/test/resources/org/onosproject/ui/lion/_cmd/03-from.lioncfg b/web/gui/src/test/resources/org/onosproject/ui/lion/_cmd/03-from.lioncfg
new file mode 100644
index 0000000..d856ebd
--- /dev/null
+++ b/web/gui/src/test/resources/org/onosproject/ui/lion/_cmd/03-from.lioncfg
@@ -0,0 +1,2 @@
+# 03. good from
+from foo.bar import fizzbuzz
diff --git a/web/gui/src/test/resources/org/onosproject/ui/lion/_cmd/04-from-four.lioncfg b/web/gui/src/test/resources/org/onosproject/ui/lion/_cmd/04-from-four.lioncfg
new file mode 100644
index 0000000..ec13545
--- /dev/null
+++ b/web/gui/src/test/resources/org/onosproject/ui/lion/_cmd/04-from-four.lioncfg
@@ -0,0 +1,2 @@
+# 04. good from with 4 keys
+from hooray import henry, joe, arthur, ford
diff --git a/web/gui/src/test/resources/org/onosproject/ui/lion/_cmd/05-from-expand.lioncfg b/web/gui/src/test/resources/org/onosproject/ui/lion/_cmd/05-from-expand.lioncfg
new file mode 100644
index 0000000..920d701
--- /dev/null
+++ b/web/gui/src/test/resources/org/onosproject/ui/lion/_cmd/05-from-expand.lioncfg
@@ -0,0 +1,4 @@
+# 05. from expanding alias
+alias xy xyzzy.wizard
+from xy.spell import zonk, zip, zuffer
+from xy.learn import zap, zigzag
diff --git a/web/gui/src/test/resources/org/onosproject/ui/lion/_cmd/06-from-star.lioncfg b/web/gui/src/test/resources/org/onosproject/ui/lion/_cmd/06-from-star.lioncfg
new file mode 100644
index 0000000..3019c2f
--- /dev/null
+++ b/web/gui/src/test/resources/org/onosproject/ui/lion/_cmd/06-from-star.lioncfg
@@ -0,0 +1,2 @@
+# 06. from star
+from star.singular import *
diff --git a/web/gui/src/test/resources/org/onosproject/ui/lion/_cmd/07-star-is-special.lioncfg b/web/gui/src/test/resources/org/onosproject/ui/lion/_cmd/07-star-is-special.lioncfg
new file mode 100644
index 0000000..9a72010
--- /dev/null
+++ b/web/gui/src/test/resources/org/onosproject/ui/lion/_cmd/07-star-is-special.lioncfg
@@ -0,0 +1,6 @@
+# 07. star is special
+from abc import foo, bar
+from star.bad1 import *, foo
+from star.good import *
+from star.bad2 import foo, *, bar
+from star.bad3 import xanth, *
diff --git a/web/gui/src/test/resources/org/onosproject/ui/lion/_config/CardGame1.lioncfg b/web/gui/src/test/resources/org/onosproject/ui/lion/_config/CardGame1.lioncfg
new file mode 100644
index 0000000..00135cc
--- /dev/null
+++ b/web/gui/src/test/resources/org/onosproject/ui/lion/_config/CardGame1.lioncfg
@@ -0,0 +1,10 @@
+# test configuration
+
+bundle CardGame1
+
+alias cs core.stuff
+
+from app.Cards import *
+
+from cs.Rank import ace, king, queen, jack, ten
+from cs.Suit import spades, clubs
diff --git a/web/gui/src/test/resources/org/onosproject/ui/lion/app/Cards.properties b/web/gui/src/test/resources/org/onosproject/ui/lion/app/Cards.properties
new file mode 100644
index 0000000..23f8766
--- /dev/null
+++ b/web/gui/src/test/resources/org/onosproject/ui/lion/app/Cards.properties
@@ -0,0 +1,23 @@
+#
+# Copyright 2017-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.
+#
+#
+# --- more properties for a card game
+of=of
+flush=Flush
+full_house=Full House
+pair=Pair
+three_oak=Three of a Kind
+
diff --git a/web/gui/src/test/resources/org/onosproject/ui/lion/core/stuff/Rank.properties b/web/gui/src/test/resources/org/onosproject/ui/lion/core/stuff/Rank.properties
new file mode 100644
index 0000000..a6b35f0
--- /dev/null
+++ b/web/gui/src/test/resources/org/onosproject/ui/lion/core/stuff/Rank.properties
@@ -0,0 +1,30 @@
+#
+# Copyright 2017-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.
+#
+#
+# --- Card Ranks
+two=Two
+three=Three
+four=Four
+five=Five
+six=Six
+seven=Seven
+eight=Eight
+nine=Nine
+ten=Ten
+jack=Jack
+queen=Queen
+king=King
+ace=Ace
diff --git a/web/gui/src/test/resources/org/onosproject/ui/lion/core/stuff/Suit.properties b/web/gui/src/test/resources/org/onosproject/ui/lion/core/stuff/Suit.properties
new file mode 100644
index 0000000..dab0e22
--- /dev/null
+++ b/web/gui/src/test/resources/org/onosproject/ui/lion/core/stuff/Suit.properties
@@ -0,0 +1,21 @@
+#
+# Copyright 2017-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.
+#
+#
+# --- Card Suits
+clubs=Clubs
+hearts=Hearts
+spades=Spades
+diamonds=Diamonds