View Javadoc
1   package org.cyclopsgroup.jmxterm.cc;
2   
3   import org.apache.commons.lang3.Validate;
4   import org.cyclopsgroup.jmxterm.Command;
5   import org.cyclopsgroup.jmxterm.CommandFactory;
6   
7   import java.util.Collections;
8   import java.util.Map;
9   
10  /**
11   * CommandFactory implementation based on a Map of command types
12   * 
13   * @author <a href="mailto:jiaqi.guo@gmail.com">Jiaqi Guo</a>
14   */
15  public class TypeMapCommandFactory implements CommandFactory {
16    private final Map<String, Class<? extends Command>> commandTypes;
17  
18    /**
19     * @param commandTypes Map of command types
20     */
21    public TypeMapCommandFactory(Map<String, Class<? extends Command>> commandTypes) {
22      Validate.notNull(commandTypes, "Command type can't be NULL");
23      this.commandTypes = Collections.unmodifiableMap(commandTypes);
24    }
25  
26    @Override
27    public Command createCommand(String commandName) {
28      Validate.notNull(commandName, "commandName can't be NULL");
29      Class<? extends Command> commandType = commandTypes.get(commandName);
30      if (commandType == null) {
31        throw new IllegalArgumentException(
32            "Command " + commandName + " isn't valid, run help to see available commands");
33      }
34      try {
35        return commandType.newInstance();
36      } catch (InstantiationException e) {
37        throw new RuntimeException("Can't instantiate instance", e);
38      } catch (IllegalAccessException e) {
39        throw new RuntimeException("Illegal access", e);
40      }
41    }
42  
43    @Override
44    public Map<String, Class<? extends Command>> getCommandTypes() {
45      return commandTypes;
46    }
47  }