Search in sources :

Example 1 with CommandException

use of org.apache.felix.gogo.commands.CommandException in project karaf by apache.

the class DefaultActionPreparator method prepare.

public boolean prepare(Action action, CommandSession session, List<Object> params) throws Exception {
    Map<Option, Field> options = new HashMap<>();
    Map<Argument, Field> arguments = new HashMap<>();
    List<Argument> orderedArguments = new ArrayList<>();
    // Introspect
    for (Class type = action.getClass(); type != null; type = type.getSuperclass()) {
        for (Field field : type.getDeclaredFields()) {
            Option option = field.getAnnotation(Option.class);
            if (option != null) {
                options.put(option, field);
            }
            Argument argument = field.getAnnotation(Argument.class);
            if (argument != null) {
                if (Argument.DEFAULT.equals(argument.name())) {
                    final Argument delegate = argument;
                    final String name = field.getName();
                    argument = new Argument() {

                        public String name() {
                            return name;
                        }

                        public String description() {
                            return delegate.description();
                        }

                        public boolean required() {
                            return delegate.required();
                        }

                        public int index() {
                            return delegate.index();
                        }

                        public boolean multiValued() {
                            return delegate.multiValued();
                        }

                        public String valueToShowInHelp() {
                            return delegate.valueToShowInHelp();
                        }

                        public Class<? extends Annotation> annotationType() {
                            return delegate.annotationType();
                        }
                    };
                }
                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);
                }
                orderedArguments.set(index, argument);
            }
        }
    }
    // Check indexes are correct
    for (int i = 0; i < orderedArguments.size(); i++) {
        if (orderedArguments.get(i) == null) {
            throw new IllegalArgumentException("Missing argument for index: " + i);
        }
    }
    // 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();
        // Check for help
        if (HELP.name().equals(param) || Arrays.asList(HELP.aliases()).contains(param)) {
            printUsage(session, action, options, arguments, System.out);
            return false;
        }
        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) {
                Command command = action.getClass().getAnnotation(Command.class);
                if (command != null) {
                    throw new CommandException(COLOR_RED + "Error executing command " + command.scope() + ":" + INTENSITY_BOLD + command.name() + INTENSITY_NORMAL + " undefined option " + INTENSITY_BOLD + param + INTENSITY_NORMAL + COLOR_DEFAULT, "Undefined option: " + param);
                } else {
                    throw new CommandException("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) {
                Command command = action.getClass().getAnnotation(Command.class);
                if (command != null) {
                    throw new CommandException(COLOR_RED + "Error executing command " + command.scope() + ":" + INTENSITY_BOLD + command.name() + INTENSITY_NORMAL + " missing value for option " + INTENSITY_BOLD + param + INTENSITY_NORMAL + COLOR_DEFAULT, "Missing value for option: " + param);
                } else {
                    throw new CommandException("Missing value for option: " + param);
                }
            }
            if (option.multiValued()) {
                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()) {
                Command command = action.getClass().getAnnotation(Command.class);
                if (command != null) {
                    throw new CommandException(COLOR_RED + "Error executing command " + command.scope() + ":" + INTENSITY_BOLD + command.name() + INTENSITY_NORMAL + ": too many arguments specified" + INTENSITY_BOLD + param + INTENSITY_NORMAL + COLOR_DEFAULT, "Too many arguments specified");
                } else {
                    throw new CommandException("Too many arguments specified");
                }
            }
            Argument argument = orderedArguments.get(argIndex);
            if (!argument.multiValued()) {
                argIndex++;
            }
            if (argument.multiValued()) {
                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) {
            Command command = action.getClass().getAnnotation(Command.class);
            if (command != null) {
                throw new CommandException(COLOR_RED + "Error executing command " + command.scope() + ":" + INTENSITY_BOLD + command.name() + INTENSITY_NORMAL + ": option " + INTENSITY_BOLD + option.name() + INTENSITY_NORMAL + " is required" + COLOR_DEFAULT, "Option " + option.name() + " is required");
            } else {
                throw new CommandException("Option " + option.name() + " is required");
            }
        }
    }
    for (Argument argument : orderedArguments) {
        if (argument.required() && argumentValues.get(argument) == null) {
            Command command = action.getClass().getAnnotation(Command.class);
            if (command != null) {
                throw new CommandException(COLOR_RED + "Error executing command " + command.scope() + ":" + INTENSITY_BOLD + command.name() + INTENSITY_NORMAL + ": argument " + INTENSITY_BOLD + argument.name() + INTENSITY_NORMAL + " is required" + COLOR_DEFAULT, "Argument " + argument.name() + " is required");
            } else {
                throw new CommandException("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) {
            Command command = action.getClass().getAnnotation(Command.class);
            if (command != null) {
                throw new CommandException(COLOR_RED + "Error executing command " + command.scope() + ":" + INTENSITY_BOLD + command.name() + INTENSITY_NORMAL + ": unable to convert option " + INTENSITY_BOLD + entry.getKey().name() + INTENSITY_NORMAL + " with value '" + entry.getValue() + "' to type " + new GenericType(field.getGenericType()).toString() + COLOR_DEFAULT, "Unable to convert option " + entry.getKey().name() + " with value '" + entry.getValue() + "' to type " + new GenericType(field.getGenericType()).toString(), e);
            } else {
                throw new CommandException("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) {
            Command command = action.getClass().getAnnotation(Command.class);
            if (command != null) {
                throw new CommandException(COLOR_RED + "Error executing command " + command.scope() + ":" + INTENSITY_BOLD + command.name() + INTENSITY_NORMAL + ": unable to convert argument " + INTENSITY_BOLD + entry.getKey().name() + INTENSITY_NORMAL + " with value '" + entry.getValue() + "' to type " + new GenericType(field.getGenericType()).toString() + COLOR_DEFAULT, "Unable to convert argument " + entry.getKey().name() + " with value '" + entry.getValue() + "' to type " + new GenericType(field.getGenericType()).toString(), e);
            } else {
                throw new CommandException("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 : Argument(org.apache.felix.gogo.commands.Argument) Field(java.lang.reflect.Field) GenericType(org.apache.felix.gogo.commands.converter.GenericType) CommandException(org.apache.felix.gogo.commands.CommandException) Annotation(java.lang.annotation.Annotation) IOException(java.io.IOException) CommandException(org.apache.felix.gogo.commands.CommandException) Command(org.apache.felix.gogo.commands.Command) Option(org.apache.felix.gogo.commands.Option)

Aggregations

IOException (java.io.IOException)1 Annotation (java.lang.annotation.Annotation)1 Field (java.lang.reflect.Field)1 Argument (org.apache.felix.gogo.commands.Argument)1 Command (org.apache.felix.gogo.commands.Command)1 CommandException (org.apache.felix.gogo.commands.CommandException)1 Option (org.apache.felix.gogo.commands.Option)1 GenericType (org.apache.felix.gogo.commands.converter.GenericType)1