org.bidib.wizard.common.script.AbstractScriptCommandFactory Maven / Gradle / Ivy
package org.bidib.wizard.common.script;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import org.bidib.wizard.api.script.ScriptCommand;
import org.bidib.wizard.api.script.Scripting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractScriptCommandFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractScriptCommandFactory.class);
protected final Map>> scriptCommands =
new HashMap>>();
public AbstractScriptCommandFactory() {
}
public abstract void registerCommands();
public ScriptCommand parse(String line) {
Scanner scanner = new Scanner(line);
String key = scanner.next();
ScriptCommand command = getScriptCommand(key);
if (command != null) {
command.parse(line);
}
scanner.close();
return command;
}
private ScriptCommand getScriptCommand(String key) {
Class> clazz = scriptCommands.get(key);
if (clazz == null) {
LOGGER.warn("Command is not registered: {}", key);
return null;
}
try {
return (ScriptCommand) clazz.getDeclaredConstructor().newInstance();
}
catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
LOGGER.warn("Create script command class failed.", e);
}
return null;
}
}