001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.xbean.command;
018
019import java.util.HashMap;
020import java.util.Iterator;
021import java.util.Map;
022
023public class CommandRegistry {
024    
025    protected static final HashMap commands = new HashMap();
026
027    static {
028        loadCommandList();
029    }
030
031    protected static final CommandRegistry unknownCommand = new CommandRegistry();
032
033    public static Map getCommandMap() {
034        HashMap rc = new HashMap();
035        for (Iterator iter = commands.keySet().iterator(); iter.hasNext();) {
036            String name = (String) iter.next();
037            Command command = getCommand(name);
038            rc.put(name, command);
039        }
040        return rc;
041    }
042
043    public static void register(String name, Command cmd) {
044        commands.put(name, cmd);
045    }
046
047    public static void register(String name, Class cmd) {
048        commands.put(name, cmd);
049    }
050
051    public static Command getCommand(String name) {
052        Object cmd = commands.get(name);
053        if (cmd instanceof Class) {
054            cmd = loadCommand((Class) cmd);
055            register(name, (Command) cmd);
056        }
057        return (Command) cmd;
058    }
059
060
061    // - Protected methods - //
062    protected static Command loadCommand(Class commandClass) {
063        Command cmd = null;
064        try {
065            cmd = (Command) commandClass.newInstance();
066        } catch (Exception e) {
067            //throw new IOException("Cannot instantiate command class "+commandClass+"\n"+e.getClass().getName()+":\n"+e.getMessage());
068        }
069        return cmd;
070    }
071
072    /**
073     * TODO: Replace this part with the classpath magic
074     */
075    protected static void loadCommandList() {
076        Exit.register();
077        Help.register();
078        Lookup.register();
079        Version.register();
080        GroovySh.register();
081    }
082}