Search in sources :

Example 1 with Command

use of org.apache.karaf.shell.commands.Command in project karaf by apache.

the class NamespaceHandler method getScope.

public static String getScope(Class<?> action) {
    Command command = action.getAnnotation(Command.class);
    if (command != null) {
        return command.scope();
    }
    org.apache.felix.gogo.commands.Command command2 = action.getAnnotation(org.apache.felix.gogo.commands.Command.class);
    if (command2 != null) {
        return command2.scope();
    }
    return null;
}
Also used : Command(org.apache.karaf.shell.commands.Command)

Example 2 with Command

use of org.apache.karaf.shell.commands.Command in project karaf by apache.

the class NamespaceHandler method getName.

public static String getName(Class<?> action) {
    Command command = action.getAnnotation(Command.class);
    if (command != null) {
        return command.name();
    }
    org.apache.felix.gogo.commands.Command command2 = action.getAnnotation(org.apache.felix.gogo.commands.Command.class);
    if (command2 != null) {
        return command2.name();
    }
    return null;
}
Also used : Command(org.apache.karaf.shell.commands.Command)

Example 3 with Command

use of org.apache.karaf.shell.commands.Command in project karaf by apache.

the class SimpleCommand method export.

public static ServiceRegistration export(BundleContext context, Class<? extends Action> actionClass) {
    Command cmd = actionClass.getAnnotation(Command.class);
    if (cmd == null) {
        throw new IllegalArgumentException("Action class is not annotated with @Command");
    }
    Hashtable<String, String> props = new Hashtable<>();
    props.put("osgi.command.scope", cmd.scope());
    props.put("osgi.command.function", cmd.name());
    SimpleCommand command = new SimpleCommand(actionClass);
    return context.registerService(new String[] { Function.class.getName(), CommandWithAction.class.getName() }, command, props);
}
Also used : Function(org.apache.felix.service.command.Function) Command(org.apache.karaf.shell.commands.Command) Hashtable(java.util.Hashtable) CommandWithAction(org.apache.karaf.shell.commands.CommandWithAction)

Example 4 with Command

use of org.apache.karaf.shell.commands.Command in project karaf by apache.

the class DefaultActionPreparator method prepare.

public boolean prepare(Action action, CommandSession session, List<Object> params) throws Exception {
    ActionMetaData actionMetaData = new ActionMetaDataFactory().create(action.getClass());
    Map<Option, Field> options = actionMetaData.getOptions();
    Map<Argument, Field> arguments = actionMetaData.getArguments();
    List<Argument> orderedArguments = actionMetaData.getOrderedArguments();
    Command command2 = actionMetaData.getCommand();
    if (command2 == null) {
        // to avoid NPE with subshell
        return true;
    }
    String commandErrorSt = (command2 != null) ? COLOR_RED + "Error executing command " + command2.scope() + ":" + INTENSITY_BOLD + command2.name() + INTENSITY_NORMAL + COLOR_DEFAULT + ": " : "";
    for (Object param : params) {
        if (HelpOption.HELP.name().equals(param)) {
            int termWidth = getWidth(session);
            boolean globalScope = NameScoping.isGlobalScope(session, actionMetaData.getCommand().scope());
            actionMetaData.printUsage(action, System.out, globalScope, termWidth);
            return false;
        }
    }
    // Populate
    Map<Option, Object> optionValues = new HashMap<>();
    Map<Argument, Object> argumentValues = new HashMap<>();
    boolean processOptions = true;
    int argIndex = 0;
    for (Iterator<Object> it = params.iterator(); it.hasNext(); ) {
        Object param = it.next();
        if (processOptions && param instanceof String && ((String) param).startsWith("-")) {
            boolean isKeyValuePair = ((String) param).indexOf('=') != -1;
            String name;
            Object value = null;
            if (isKeyValuePair) {
                name = ((String) param).substring(0, ((String) param).indexOf('='));
                value = ((String) param).substring(((String) param).indexOf('=') + 1);
            } else {
                name = (String) param;
            }
            Option option = null;
            for (Option opt : options.keySet()) {
                if (name.equals(opt.name()) || Arrays.asList(opt.aliases()).contains(name)) {
                    option = opt;
                    break;
                }
            }
            if (option == null) {
                throw new CommandException(commandErrorSt + "undefined option " + INTENSITY_BOLD + param + INTENSITY_NORMAL + "\n" + "Try <command> --help' for more information.", "Undefined option: " + param);
            }
            Field field = options.get(option);
            if (value == null && (field.getType() == boolean.class || field.getType() == Boolean.class)) {
                value = Boolean.TRUE;
            }
            if (value == null && it.hasNext()) {
                value = it.next();
            }
            if (value == null) {
                throw new CommandException(commandErrorSt + "missing value for option " + INTENSITY_BOLD + param + INTENSITY_NORMAL, "Missing value for option: " + param);
            }
            if (option.multiValued()) {
                @SuppressWarnings("unchecked") List<Object> l = (List<Object>) optionValues.get(option);
                if (l == null) {
                    l = new ArrayList<>();
                    optionValues.put(option, l);
                }
                l.add(value);
            } else {
                optionValues.put(option, value);
            }
        } else {
            processOptions = false;
            if (argIndex >= orderedArguments.size()) {
                throw new CommandException(commandErrorSt + "too many arguments specified", "Too many arguments specified");
            }
            Argument argument = orderedArguments.get(argIndex);
            if (!argument.multiValued()) {
                argIndex++;
            }
            if (argument.multiValued()) {
                @SuppressWarnings("unchecked") List<Object> l = (List<Object>) argumentValues.get(argument);
                if (l == null) {
                    l = new ArrayList<>();
                    argumentValues.put(argument, l);
                }
                l.add(param);
            } else {
                argumentValues.put(argument, param);
            }
        }
    }
    // Check required arguments / options
    for (Option option : options.keySet()) {
        if (option.required() && optionValues.get(option) == null) {
            throw new CommandException(commandErrorSt + "option " + INTENSITY_BOLD + option.name() + INTENSITY_NORMAL + " is required", "Option " + option.name() + " is required");
        }
    }
    for (Argument argument : orderedArguments) {
        if (argument.required() && argumentValues.get(argument) == null) {
            throw new CommandException(commandErrorSt + "argument " + INTENSITY_BOLD + argument.name() + INTENSITY_NORMAL + " is required", "Argument " + argument.name() + " is required");
        }
    }
    // Convert and inject values
    for (Map.Entry<Option, Object> entry : optionValues.entrySet()) {
        Field field = options.get(entry.getKey());
        Object value;
        try {
            value = convert(action, session, entry.getValue(), field.getGenericType());
        } catch (Exception e) {
            throw new CommandException(commandErrorSt + "unable to convert option " + INTENSITY_BOLD + entry.getKey().name() + INTENSITY_NORMAL + " with value '" + entry.getValue() + "' to type " + new GenericType(field.getGenericType()).toString(), "Unable to convert option " + entry.getKey().name() + " with value '" + entry.getValue() + "' to type " + new GenericType(field.getGenericType()).toString(), e);
        }
        field.setAccessible(true);
        field.set(action, value);
    }
    for (Map.Entry<Argument, Object> entry : argumentValues.entrySet()) {
        Field field = arguments.get(entry.getKey());
        Object value;
        try {
            value = convert(action, session, entry.getValue(), field.getGenericType());
        } catch (Exception e) {
            throw new CommandException(commandErrorSt + "unable to convert argument " + INTENSITY_BOLD + entry.getKey().name() + INTENSITY_NORMAL + " with value '" + entry.getValue() + "' to type " + new GenericType(field.getGenericType()).toString(), "Unable to convert argument " + entry.getKey().name() + " with value '" + entry.getValue() + "' to type " + new GenericType(field.getGenericType()).toString(), e);
        }
        field.setAccessible(true);
        field.set(action, value);
    }
    return true;
}
Also used : ActionMetaDataFactory(org.apache.karaf.shell.commands.meta.ActionMetaDataFactory) ActionMetaData(org.apache.karaf.shell.commands.meta.ActionMetaData) Argument(org.apache.karaf.shell.commands.Argument) HashMap(java.util.HashMap) Field(java.lang.reflect.Field) ArrayList(java.util.ArrayList) List(java.util.List) GenericType(org.apache.karaf.shell.commands.converter.GenericType) CommandException(org.apache.karaf.shell.commands.CommandException) CommandException(org.apache.karaf.shell.commands.CommandException) Command(org.apache.karaf.shell.commands.Command) Option(org.apache.karaf.shell.commands.Option) HelpOption(org.apache.karaf.shell.commands.HelpOption) HashMap(java.util.HashMap) Map(java.util.Map)

Example 5 with Command

use of org.apache.karaf.shell.commands.Command in project karaf by apache.

the class ActionMetaDataFactory method create.

public ActionMetaData create(Class<? extends Action> actionClass) {
    Command command = getCommand(actionClass);
    Map<Option, Field> options = new HashMap<>();
    Map<Argument, Field> arguments = new HashMap<>();
    List<Argument> orderedArguments = new ArrayList<>();
    for (Class<?> type = actionClass; type != null; type = type.getSuperclass()) {
        for (Field field : type.getDeclaredFields()) {
            Option option = field.getAnnotation(Option.class);
            if (option == null) {
                option = getAndConvertDeprecatedOption(field);
            }
            if (option != null) {
                options.put(option, field);
            }
            Argument argument = field.getAnnotation(Argument.class);
            if (argument == null) {
                argument = getAndConvertDeprecatedArgument(field);
            }
            if (argument != null) {
                argument = replaceDefaultArgument(field, argument);
                arguments.put(argument, field);
                int index = argument.index();
                while (orderedArguments.size() <= index) {
                    orderedArguments.add(null);
                }
                if (orderedArguments.get(index) != null) {
                    throw new IllegalArgumentException("Duplicate argument index: " + index + " on Action " + actionClass.getName());
                }
                orderedArguments.set(index, argument);
            }
        }
    }
    assertIndexesAreCorrect(actionClass, orderedArguments);
    return new ActionMetaData(actionClass, command, options, arguments, orderedArguments, null);
}
Also used : Argument(org.apache.karaf.shell.commands.Argument) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Field(java.lang.reflect.Field) Command(org.apache.karaf.shell.commands.Command) Option(org.apache.karaf.shell.commands.Option)

Aggregations

Command (org.apache.karaf.shell.commands.Command)6 Field (java.lang.reflect.Field)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Argument (org.apache.karaf.shell.commands.Argument)2 CommandWithAction (org.apache.karaf.shell.commands.CommandWithAction)2 Option (org.apache.karaf.shell.commands.Option)2 Method (java.lang.reflect.Method)1 Hashtable (java.util.Hashtable)1 Map (java.util.Map)1 CommandSession (org.apache.felix.service.command.CommandSession)1 Function (org.apache.felix.service.command.Function)1 Completer (org.apache.karaf.shell.api.console.Completer)1 Parser (org.apache.karaf.shell.api.console.Parser)1 Session (org.apache.karaf.shell.api.console.Session)1 CommandException (org.apache.karaf.shell.commands.CommandException)1 HelpOption (org.apache.karaf.shell.commands.HelpOption)1 GenericType (org.apache.karaf.shell.commands.converter.GenericType)1 ActionMetaData (org.apache.karaf.shell.commands.meta.ActionMetaData)1