AdminConsole.java 18.4 KB
Newer Older
Bill Lynch's avatar
Bill Lynch committed
1 2
/**
 * $RCSfile$
Bill Lynch's avatar
Bill Lynch committed
3
 * $Revision$
Bill Lynch's avatar
Bill Lynch committed
4 5
 * $Date$
 *
Bill Lynch's avatar
Bill Lynch committed
6
 * Copyright (C) 2004 Jive Software. All rights reserved.
Bill Lynch's avatar
Bill Lynch committed
7
 *
Bill Lynch's avatar
Bill Lynch committed
8 9
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
Bill Lynch's avatar
Bill Lynch committed
10 11 12 13 14 15
 */

package org.jivesoftware.admin;

import org.jivesoftware.util.ClassUtils;
import org.jivesoftware.util.Log;
16 17 18
import org.jivesoftware.util.XPPReader;
import org.dom4j.Document;
import org.dom4j.Element;
Bill Lynch's avatar
Bill Lynch committed
19 20 21

import java.util.*;
import java.io.InputStream;
22
import java.io.InputStreamReader;
Bill Lynch's avatar
Bill Lynch committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
import java.net.URL;

/**
 * <p>A model for admin tab and sidebar info. This class loads in xml definitions of the data and
 * produces an in-memory model. There is an internal class, {@link Item} which is the main part
 * of the model. Items hold info like name, id, url and description as well as an arbritrary number
 * of sub items. Based on this we can make a tree model of the data.</p>
 *
 * <p>This class loads its data from the <tt>admin-sidebar.xml</tt> file which is assumed to be in
 * the main application jar file. In addition, it will load files from
 * <tt>META-INF/admin-sidebar.xml</tt> if they're found. This allows developers to extend the
 * functionality of the admin console to provide more options. See the main
 * <tt>admin-sidebar.xml</tt> file for documentation of its format.</p>
 *
 * <p>Note: IDs in the XML file must be unique because an internal mapping is kept of IDs to
 * nodes.</p>
 */
public class AdminConsole {

42
    private static Map<String,Item> items;
Bill Lynch's avatar
Bill Lynch committed
43 44
    private static String appName;
    private static String logoImage;
Bill Lynch's avatar
Bill Lynch committed
45 46

    static {
47 48 49 50 51
        init();
    }

    private static void init() {
        items = Collections.synchronizedMap(new LinkedHashMap<String,Item>());
Bill Lynch's avatar
Bill Lynch committed
52 53 54 55 56 57 58
        load();
    }

    /** Not instantiatable */
    private AdminConsole() {
    }

Bill Lynch's avatar
Bill Lynch committed
59 60 61 62 63 64 65 66 67 68
    /**
     * Adds XML stream to the tabs/sidebar model.
     *
     * @param in the XML input stream.
     * @throws Exception if an error occurs when parsing the XML or adding it to the model.
     */
    public static void addXMLSource(InputStream in) throws Exception {
        addToModel(in);
    }

Bill Lynch's avatar
Bill Lynch committed
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
    /**
     * Returns the name of the application.
     */
    public static String getAppName() {
        return appName;
    }

    /**
     * Returns the URL (relative or absolute) of the main logo image for the admin console.
     * @return
     */
    public static String getLogoImage() {
        return logoImage;
    }

Bill Lynch's avatar
Bill Lynch committed
84
    /**
85
     * Returns all root items. Getting the iterator from this collection returns
Bill Lynch's avatar
Bill Lynch committed
86 87 88 89 90
     * all root items (should be used as tabs in the admin tool).
     *
     * @return a collection of all items - the root items are returned by calling the
     *      <tt>iterator()</tt> method.
     */
91 92 93 94 95 96 97 98
    public static Collection<Item> getItems() {
        List<Item> rootItems = new ArrayList<Item>();
        for (Item i : items.values()) {
            if (i.getParent() == null) {
                rootItems.add(i);
            }
        }
        return rootItems;
Bill Lynch's avatar
Bill Lynch committed
99 100 101 102 103 104 105 106 107
    }

    /**
     * Returns an item given its ID or <tt>null</tt> if it can't be found.
     *
     * @param id the ID of the item.
     * @return an item given its ID or <tt>null</tt> if it can't be found.
     */
    public static Item getItem(String id) {
108
        return items.get(id);
Bill Lynch's avatar
Bill Lynch committed
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
    }

    /**
     * Returns the root item given a child item. In other words, a lookup is done on the ID for
     * the corresponding item - that item is assumed to be a leaf and this method returns the
     * root ancestor of it.
     *
     * @param id the ID of the child item.
     * @return the root ancestor of the specified child item.
     */
    public static Item getRootByChildID(String id) {
        if (id == null) {
            return null;
        }
        Item child = getItem(id);
        Item root = null;
        if (child != null) {
            Item parent = child.getParent();
            root = parent;
            while (parent != null) {
                parent = parent.getParent();
                if (parent != null) {
                    root = parent;
                }
            }
        }
        return root;
    }

    /**
     * Returns <tt>true</tt> if the given item is a sub-menu item.
     *
     * @param item the item to test.
     * @return <tt>true</tt> if the given item is a sub-menu item, <tt>false</tt> otherwise.
     */
    public static boolean isSubMenItem(Item item) {
        int parentCount = 0;
        Item parent = item.getParent();
        while (parent != null) {
            parentCount++;
            parent = parent.getParent();
        }
        return parentCount >= 3;
    }

    /**
     * Returns the ID of the page ID associated with this sub page ID.
     * @param subPageID the subPageID to use to look up the page ID.
     * @return the associated pageID or <tt>null</tt> if it can't be found.
     */
    public static String lookupPageID(String subPageID) {
        String pageID = null;
        Item item = getItem(subPageID);
        if (item != null) {
            Item parent = item.getParent();
164
            if (parent != null) {
Bill Lynch's avatar
Bill Lynch committed
165
                parent = parent.getParent();
166 167 168
                if (parent != null) {
                    pageID = parent.getId();
                }
Bill Lynch's avatar
Bill Lynch committed
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
            }
        }
        return pageID;
    }

    /**
     * A simple class to model an item. Each item has attributes used by the admin console to
     * display it like ID, name, URL and description. Also, from each item you can get its parent
     * (because an Item goes in a tree structure) and any children items it has.
     */
    public static class Item {

        private String id;
        private String name;
        private String description;
        private String url;
        private boolean active;
186
        private Map<String,Item> items;
Bill Lynch's avatar
Bill Lynch committed
187
        private Item parent;
188
        private static int idSeq = 0;
Bill Lynch's avatar
Bill Lynch committed
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214

        /**
         * Creates a new item given its main attributes.
         */
        public Item(String id, String name, String description, String url) {
            this.id = id;
            this.name = name;
            this.description = description;
            this.url = url;
            init();
        }

        /**
         * Creates a new item given its main attributes and the parent item (this helps set up
         * the tree structure).
         */
        public Item(String id, String name, String description, String url, Item parent) {
            this.id = id;
            this.name = name;
            this.description = description;
            this.url = url;
            this.parent = parent;
            init();
        }

        private void init() {
215
            items = Collections.synchronizedMap(new LinkedHashMap<String,Item>());
216 217 218
            if (id == null) {
                id = String.valueOf(idSeq++);
            }
Bill Lynch's avatar
Bill Lynch committed
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
        }

        /**
         * Returns the ID of the item.
         */
        public String getId() {
            return id;
        }

        /**
         * Returns the name of the item - this is the display name.
         */
        public String getName() {
            return name;
        }

Bill Lynch's avatar
Bill Lynch committed
235 236 237 238 239 240 241
        /**
         * Sets the name.
         */
        void setName(String name) {
            this.name = name;
        }

Bill Lynch's avatar
Bill Lynch committed
242 243 244 245 246 247 248
        /**
         * Returns the description of the item.
         */
        public String getDescription() {
            return description;
        }

Bill Lynch's avatar
Bill Lynch committed
249 250 251 252 253 254 255
        /**
         * Sets the description.
         */
        void setDescription(String description) {
            this.description = description;
        }

Bill Lynch's avatar
Bill Lynch committed
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
        /**
         * Returns the URL for this item.
         */
        public String getUrl() {
            return url;
        }

        /**
         * Sets the URL for this item.
         */
        public void setUrl(String url) {
            this.url = url;
        }

        /**
         * Returns true if this items is active - in the admin console this would mean it's selected.
         */
        public boolean isActive() {
            return active;
        }

        /**
         * Sets the item as active - in the admin console this would mean it's selected.
         */
        public void setActive(boolean active) {
            this.active = active;
        }

        /**
         * Returns the parent item or <tt>null</tt> if this is a root item.
         */
        public Item getParent() {
            return parent;
        }

        /**
         * Sets the parent item.
         */
        public void setParent(Item parent) {
            this.parent = parent;
        }

298 299 300 301
        public void addItem(Item item) {
            items.put(item.getId(), item);
        }

Bill Lynch's avatar
Bill Lynch committed
302 303 304
        /**
         * Returns the items as a collection. Use the Collection API to get/set/remove items.
         */
305 306
        public Collection<Item> getItems() {
            return items.values();
Bill Lynch's avatar
Bill Lynch committed
307 308 309 310 311 312 313 314 315 316 317 318 319
        }

        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null) {
                return false;
            }
            if (!(o instanceof Item)) {
                return false;
            }
            Item i = (Item) o;
320
            if (id == null || !id.equals(i.id)) {
Bill Lynch's avatar
Bill Lynch committed
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
                return false;
            }
            return true;
        }

        /**
         * Returns the ID of the item.
         */
        public String toString() {
            return id;
        }
    }

    private static void load() {
        // Load the admin-sidebar.xml file from the jiveforums.jar file:
        InputStream in = ClassUtils.getResourceAsStream("/admin-sidebar.xml");
        if (in == null) {
338
            Log.error("Failed to load admin-sidebar.xml file from Jive Messenger classes - admin "
Bill Lynch's avatar
Bill Lynch committed
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
                    + "console will not work correctly.");
            return;
        }
        try {
            addToModel(in);
        }
        catch (Exception e) {
            Log.error("Failure when parsing main admin-sidebar.xml file", e);
        }
        try {
            in.close();
        }
        catch (Exception ignored) {}

        // Load other admin-sidebar.xml files from the classpath
        ClassLoader[] classLoaders = getClassLoaders();
        for (int i=0; i<classLoaders.length; i++) {
            URL url = null;
            try {
                if (classLoaders[i] != null) {
Bill Lynch's avatar
Bill Lynch committed
359
                    Enumeration e = classLoaders[i].getResources("/META-INF/admin-sidebar.xml");
Bill Lynch's avatar
Bill Lynch committed
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
                    while (e.hasMoreElements()) {
                        url = (URL)e.nextElement();
                        in = url.openStream();
                        addToModel(in);
                        try {
                            in.close();
                        }
                        catch (Exception ignored) {}
                    }
                }
            }
            catch (Exception e) {
                String msg = "Failed to load admin-sidebar.xml";
                if (url != null) {
                    msg += " from resource: " + url.toString();
                }
                Log.warn(msg, e);
            }
        }
    }

    private static void addToModel(InputStream in) throws Exception {
382 383

        Document doc = XPPReader.parseDocument(new InputStreamReader(in), AdminConsole.class);
Bill Lynch's avatar
Bill Lynch committed
384
        // Set any global properties
385 386 387
        String globalAppname = getProperty(doc, "global.appname");
        if (globalAppname != null) {
            appName = globalAppname;
Bill Lynch's avatar
Bill Lynch committed
388
        }
389 390 391
        String globalLogoImage = getProperty(doc, "global.logo-image");
        if (globalLogoImage != null) {
            logoImage = globalLogoImage;
Bill Lynch's avatar
Bill Lynch committed
392
        }
393

Bill Lynch's avatar
Bill Lynch committed
394
        // Get all children of the 'tabs' element - should be 'tab' items:
395 396 397 398
        List tabs = doc.getRootElement().elements("tab");
        for (int i=0; i<tabs.size(); i++) {
            Element tab = (Element)tabs.get(i);

Bill Lynch's avatar
Bill Lynch committed
399
            // Create a new top level item with data from the xml file:
400 401 402
            String id = tab.attributeValue("id");
            String name = tab.attributeValue("name");
            String description = tab.attributeValue("description");
Bill Lynch's avatar
Bill Lynch committed
403 404
            Item item = new Item(id, name, description, null);
            // Add that item to the item collection
405 406
            items.put(id, item);

Bill Lynch's avatar
Bill Lynch committed
407 408
            // Delve down into this item's sidebars - build up a model of these then add into
            // the item above.
409 410 411 412 413
            List sidebars = tab.elements("sidebar");
            for (int j=0; j<sidebars.size(); j++) {
                Element sidebar = (Element)sidebars.get(j);

                name = sidebar.attributeValue("name");
Bill Lynch's avatar
Bill Lynch committed
414
                // Create a new item, set its name
415 416 417 418 419
                Item sidebarItem = new Item(null, name, null, null);
                // Get all items of this sidebar:
                List subitems = sidebar.elements("item");
                for (int k=0; k<subitems.size(); k++) {
                    Element subitem = (Element)subitems.get(k);
Bill Lynch's avatar
Bill Lynch committed
420
                    // Get the id, name, descr and url attributes:
421 422 423 424
                    String subID = subitem.attributeValue("id");
                    String subName = subitem.attributeValue("name");
                    String subDescr = subitem.attributeValue("description");
                    String subURL = subitem.attributeValue("url");
Bill Lynch's avatar
Bill Lynch committed
425
                    // Build an item with this, add it to the subItem we made above
426 427 428
                    Item kItem = new Item(subID, subName, subDescr, subURL, sidebarItem);
                    items.put(kItem.getId(), kItem);
                    sidebarItem.addItem(kItem);
Bill Lynch's avatar
Bill Lynch committed
429
                    // Build any sub-sub menus:
430
                    subAddtoModel(subitem, kItem);
Bill Lynch's avatar
Bill Lynch committed
431 432 433 434 435 436
                    // If this is the first item, set the root menu item's URL as this URL:
                    if (j==0 && k == 0) {
                        item.setUrl(subURL);
                    }
                }
                // Add the subItem to the item created above
437 438 439
                sidebarItem.setParent(item);
                items.put(sidebarItem.getId(), sidebarItem);
                item.addItem(sidebarItem);
Bill Lynch's avatar
Bill Lynch committed
440 441 442 443
            }
        }
    }

444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
    private static String getProperty(Document doc, String propName) {
        String[] name = parsePropertyName(propName);
        String value = null;
        // Search for this property by traversing down the XML heirarchy.
        Element element = doc.getRootElement();
        for (int i = 0; i < name.length; i++) {
            element = element.element(name[i]);
            if (element == null) {
                value = null;
                break;
            }
        }
        // At this point, we found a matching property, so return its value.
        // Empty strings are returned as null.
        if (element != null) {
            value = element.getTextTrim();
            if ("".equals(value)) {
                value = null;
Bill Lynch's avatar
Bill Lynch committed
462 463
            }
        }
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
        return value;
    }

    private static String getAttribute(Document doc, String propName, String attribute) {
        String[] name = parsePropertyName(propName);
        String value = null;
        // Search for this property by traversing down the XML heirarchy.
        Element element = doc.getRootElement();
        for (int i = 0; i < name.length; i++) {
            element = element.element(name[i]);
            if (element == null) {
                value = null;
                break;
            }
        }
        // At this point, we found a matching property, so return its value.
        // Empty strings are returned as null.
        value = element.attributeValue(attribute);
        if ("".equals(value)) {
            value = null;
        }
        return value;
    }

    private static Element[] getChildElements(Document doc, String propName) {
        String[] name = parsePropertyName(propName);
        // Search for this property by traversing down the XML heirarchy.
        Element element = doc.getRootElement();
        for (int i = 0; i < name.length; i++) {
            element = element.element(name[i]);
            if (element == null) {
                // This node doesn't match this part of the property name which
                // indicates this property doesn't exist so return empty array.
                return new Element[]{};
            }
        }
        // We found matching property, return names of children.
        List children = element.elements();
        int childCount = children.size();
        Element[] elements = new Element[childCount];
        for (int i=0; i<childCount; i++) {
            elements[i] = (Element)children.get(i);
        }
        return elements;
    }

    private static String[] parsePropertyName(String name) {
        List propName = new ArrayList(5);
        // Use a StringTokenizer to tokenize the property name.
        StringTokenizer tokenizer = new StringTokenizer(name, ".");
        while (tokenizer.hasMoreTokens()) {
            propName.add(tokenizer.nextToken());
        }
        return (String[])propName.toArray(new String[propName.size()]);
    }

    private static void subAddtoModel(Element parentElement, Item parentItem) {

        List subsidebars = parentElement.elements("subsidebar");
        for (int i=0; i<subsidebars.size(); i++) {
            Element subsidebar = (Element)subsidebars.get(i);
            String subsidebarName = subsidebar.attributeValue("name");
            Item subsidebarItem = new Item(null, subsidebarName, null, null, parentItem);
            // Get the items under it
            List subitems = subsidebar.elements("item");
            for (int j=0; j<subitems.size(); j++) {
                Element item = (Element)subitems.get(j);
                String id = item.attributeValue("id");
                String name = item.attributeValue("name");
                String url = item.attributeValue("url");
                String descr = item.attributeValue("description");
                Item newItem = new Item(id, name, descr, url, subsidebarItem);
                subsidebarItem.addItem(newItem);
                items.put(id, newItem);
            }
            parentItem.addItem(subsidebarItem);
        }
Bill Lynch's avatar
Bill Lynch committed
541 542 543 544 545 546 547 548 549 550 551 552
    }

    /**
     * Returns an array of class loaders to load resources from.
     */
    private static ClassLoader[] getClassLoaders() {
        ClassLoader[] classLoaders = new ClassLoader[3];
        classLoaders[0] = AdminConsole.class.getClass().getClassLoader();
        classLoaders[1] = Thread.currentThread().getContextClassLoader();
        classLoaders[2] = ClassLoader.getSystemClassLoader();
        return classLoaders;
    }
Bill Lynch's avatar
Bill Lynch committed
553

554
    // Called by test classes to wipe and reload the internal data
Bill Lynch's avatar
Bill Lynch committed
555
    private static void clear() {
556
        init();
Bill Lynch's avatar
Bill Lynch committed
557
    }
Bill Lynch's avatar
Bill Lynch committed
558
}