Search in sources :

Example 1 with Command

use of org.apache.karaf.shell.api.action.Command in project karaf by apache.

the class DocBookCommandHelpPrinter method printHelp.

@Override
public void printHelp(Action action, PrintStream out, boolean includeHelpOption) {
    Command command = action.getClass().getAnnotation(Command.class);
    Set<Option> options = new HashSet<>();
    List<Argument> arguments = new ArrayList<>();
    Map<Argument, Field> argFields = new HashMap<>();
    Map<Option, Field> optFields = new HashMap<>();
    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.add(option);
            }
            Argument argument = field.getAnnotation(Argument.class);
            if (argument != null) {
                argument = replaceDefaultArgument(field, argument);
                argFields.put(argument, field);
                int index = argument.index();
                while (arguments.size() <= index) {
                    arguments.add(null);
                }
                if (arguments.get(index) != null) {
                    throw new IllegalArgumentException("Duplicate argument index: " + index + " on Action " + action.getClass().getName());
                }
                arguments.set(index, argument);
            }
        }
    }
    if (includeHelpOption)
        options.add(HelpOption.HELP);
    out.println("<section>");
    out.println("  <title>" + command.scope() + ":" + command.name() + "</title>");
    out.println("  <section>");
    out.println("    <title>Description</title>");
    out.println("    <para>");
    out.println(command.description());
    out.println("    </para>");
    out.println("  </section>");
    StringBuffer syntax = new StringBuffer();
    syntax.append(String.format("%s:%s", command.scope(), command.name()));
    if (options.size() > 0) {
        syntax.append(" [options]");
    }
    if (arguments.size() > 0) {
        syntax.append(' ');
        for (Argument argument : arguments) {
            syntax.append(String.format(argument.required() ? "%s " : "[%s] ", argument.name()));
        }
    }
    out.println("  <section>");
    out.println("    <title>Syntax</title>");
    out.println("    <para>");
    out.println(syntax.toString());
    out.println("    </para>");
    out.println("  </section>");
    if (arguments.size() > 0) {
        out.println("  <section>");
        out.println("    <title>Arguments</title>");
        out.println("    <informaltable>");
        for (Argument argument : arguments) {
            out.println("    <tr>");
            out.println("      <td>" + argument.name() + "</td>");
            String description = argument.description();
            if (!argument.required()) {
                if (argument.valueToShowInHelp() != null && argument.valueToShowInHelp().length() != 0) {
                    if (Argument.DEFAULT_STRING.equals(argument.valueToShowInHelp())) {
                        Object o = getDefaultValue(action, argFields.get(argument));
                        String defaultValue = getDefaultValueString(o);
                        if (defaultValue != null) {
                            description += " (defaults to " + o.toString() + ")";
                        }
                    }
                }
            }
            out.println("      <td>" + description + "</td>");
            out.println("    </tr>");
        }
        out.println("    </informaltable>");
        out.println("  </section>");
    }
    if (options.size() > 0) {
        out.println("  <section>");
        out.println("    <title>Options</title>");
        out.println("    <informaltable>");
        for (Option option : options) {
            String opt = option.name();
            String description = option.description();
            for (String alias : option.aliases()) {
                opt += ", " + alias;
            }
            Object o = getDefaultValue(action, optFields.get(option));
            String defaultValue = getDefaultValueString(o);
            if (defaultValue != null) {
                description += " (defaults to " + o.toString() + ")";
            }
            out.println("    <tr>");
            out.println("      <td>" + opt + "</td>");
            out.println("      <td>" + description + "</td>");
            out.println("    </tr>");
        }
        out.println("    </informaltable>");
        out.println("  </section>");
    }
    if (command.detailedDescription().length() > 0) {
        out.println("  <section>");
        out.println("    <title>Details</title>");
        out.println("    <para>");
        out.println(command.detailedDescription());
        out.println("    </para>");
        out.println("  </section>");
    }
    out.println("</section>");
}
Also used : Argument(org.apache.karaf.shell.api.action.Argument) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Field(java.lang.reflect.Field) Command(org.apache.karaf.shell.api.action.Command) HelpOption(org.apache.karaf.shell.impl.action.command.HelpOption) Option(org.apache.karaf.shell.api.action.Option) HashSet(java.util.HashSet)

Example 2 with Command

use of org.apache.karaf.shell.api.action.Command in project karaf by apache.

the class DefaultActionPreparator method prepare.

public boolean prepare(Action action, Session session, List<Object> params) throws Exception {
    Command command = action.getClass().getAnnotation(Command.class);
    Map<Option, Field> options = new HashMap<>();
    Map<Argument, Field> arguments = new HashMap<>();
    List<Argument> orderedArguments = new ArrayList<>();
    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) {
                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 " + action.getClass().getName());
                }
                orderedArguments.set(index, argument);
            }
        }
    }
    assertIndexesAreCorrect(action.getClass(), orderedArguments);
    String commandErrorSt = COLOR_RED + "Error executing command " + command.scope() + ":" + INTENSITY_BOLD + command.name() + INTENSITY_NORMAL + COLOR_DEFAULT + ": ";
    for (Object param : params) {
        if (HelpOption.HELP.name().equals(param)) {
            int termWidth = session.getTerminal() != null ? session.getTerminal().getWidth() : 80;
            boolean globalScope = NameScoping.isGlobalScope(session, command.scope());
            printUsage(action, options, arguments, System.out, globalScope, termWidth);
            return false;
        }
    }
    // Populate
    Map<Option, Object> optionValues = new HashMap<Option, Object>();
    Map<Argument, Object> argumentValues = new HashMap<Argument, Object>();
    boolean processOptions = true;
    int argIndex = 0;
    for (Iterator<Object> it = params.iterator(); it.hasNext(); ) {
        Object param = it.next();
        String paramValue = null;
        if (param instanceof String) {
            paramValue = (String) param;
        }
        if (param instanceof Token) {
            paramValue = param.toString();
        }
        if (processOptions && paramValue != null && paramValue.startsWith("-")) {
            boolean isKeyValuePair = paramValue.indexOf('=') != -1;
            String name;
            Object value = null;
            if (isKeyValuePair) {
                name = paramValue.substring(0, paramValue.indexOf('='));
                value = paramValue.substring(paramValue.indexOf('=') + 1);
            } else {
                name = paramValue;
            }
            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 + paramValue + INTENSITY_NORMAL + "\n" + "Try <command> --help' for more information.", "Undefined option: " + paramValue);
            }
            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 + paramValue + INTENSITY_NORMAL, "Missing value for option: " + paramValue);
            }
            if (option.multiValued()) {
                @SuppressWarnings("unchecked") List<Object> l = (List<Object>) optionValues.get(option);
                if (l == null) {
                    l = new ArrayList<Object>();
                    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<Object>();
                    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, 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, 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 : Argument(org.apache.karaf.shell.api.action.Argument) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Token(org.apache.felix.gogo.runtime.Token) Field(java.lang.reflect.Field) ArrayList(java.util.ArrayList) List(java.util.List) GenericType(org.apache.karaf.shell.support.converter.GenericType) CommandException(org.apache.karaf.shell.support.CommandException) IOException(java.io.IOException) CommandException(org.apache.karaf.shell.support.CommandException) Command(org.apache.karaf.shell.api.action.Command) Option(org.apache.karaf.shell.api.action.Option) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with Command

use of org.apache.karaf.shell.api.action.Command in project karaf by apache.

the class ManagerImpl method register.

@SuppressWarnings("unchecked")
@Override
public void register(Class<?> clazz) {
    if (!allowCustomServices) {
        Service reg = clazz.getAnnotation(Service.class);
        if (reg == null) {
            throw new IllegalArgumentException("Class " + clazz.getName() + " is not annotated with @Service");
        }
    }
    if (Action.class.isAssignableFrom(clazz)) {
        final Command cmd = clazz.getAnnotation(Command.class);
        if (cmd == null) {
            throw new IllegalArgumentException("Command " + clazz.getName() + " is not annotated with @Command");
        }
        Object command = new ActionCommand(this, (Class<? extends Action>) clazz);
        synchronized (instances) {
            instances.put(clazz, command);
        }
        registrations.register(command);
    }
    if (allowCustomServices || Completer.class.isAssignableFrom(clazz) || Parser.class.isAssignableFrom(clazz)) {
        try {
            // Create completer
            Object completer = instantiate(clazz);
            synchronized (instances) {
                instances.put(clazz, completer);
            }
            registrations.register(completer);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
Also used : Command(org.apache.karaf.shell.api.action.Command) Service(org.apache.karaf.shell.api.action.lifecycle.Service) Parser(org.apache.karaf.shell.api.console.Parser)

Example 4 with Command

use of org.apache.karaf.shell.api.action.Command in project karaf by apache.

the class AsciiDoctorCommandHelpPrinter method printHelp.

@Override
public void printHelp(Action action, PrintStream out, boolean includeHelpOption) {
    Command command = action.getClass().getAnnotation(Command.class);
    Set<Option> options = new HashSet<>();
    List<Argument> arguments = new ArrayList<>();
    Map<Argument, Field> argFields = new HashMap<>();
    Map<Option, Field> optFields = new HashMap<>();
    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.add(option);
            }
            Argument argument = field.getAnnotation(Argument.class);
            if (argument != null) {
                argument = replaceDefaultArgument(field, argument);
                argFields.put(argument, field);
                int index = argument.index();
                while (arguments.size() <= index) {
                    arguments.add(null);
                }
                if (arguments.get(index) != null) {
                    throw new IllegalArgumentException("Duplicate argument index: " + index + " on Action " + action.getClass().getName());
                }
                arguments.set(index, argument);
            }
        }
    }
    if (includeHelpOption)
        options.add(HelpOption.HELP);
    out.println("= " + command.scope() + ":" + command.name());
    out.println();
    out.println("== Description");
    out.println();
    out.println(command.description());
    out.println();
    StringBuffer syntax = new StringBuffer();
    syntax.append(String.format("%s:%s", command.scope(), command.name()));
    if (options.size() > 0) {
        syntax.append(" [options]");
    }
    if (arguments.size() > 0) {
        syntax.append(' ');
        for (Argument argument : arguments) {
            syntax.append(String.format(argument.required() ? "%s " : "[%s] ", argument.name()));
        }
    }
    out.println("== Syntax");
    out.println();
    out.println(syntax.toString());
    out.println();
    if (arguments.size() > 0) {
        out.println("== Arguments");
        out.println();
        out.println("|===");
        out.println("|Name |Description");
        for (Argument argument : arguments) {
            String description = argument.description();
            if (!argument.required()) {
                Object o = getDefaultValue(action, argFields.get(argument));
                String defaultValue = getDefaultValueString(o);
                if (defaultValue != null) {
                    description += " (defaults to " + o.toString() + ")";
                }
            }
            out.println();
            out.println("| " + argument.name());
            out.println("| " + description);
        }
        out.println("|===");
        out.println();
    }
    if (options.size() > 0) {
        out.println("== Options");
        out.println();
        out.println("|===");
        out.println("|Name |Description");
        for (Option option : options) {
            String opt = option.name();
            String desc = option.description();
            for (String alias : option.aliases()) {
                opt += ", " + alias;
            }
            Object o = getDefaultValue(action, optFields.get(option));
            String defaultValue = getDefaultValueString(o);
            if (defaultValue != null) {
                desc += " (defaults to " + defaultValue + ")";
            }
            out.println();
            out.println("|" + opt);
            out.println("|" + desc);
        }
        out.println("|===");
        out.println();
    }
    if (command.detailedDescription().length() > 0) {
        out.println("== Details");
        out.println();
        out.println(command.detailedDescription());
    }
    out.println();
}
Also used : Argument(org.apache.karaf.shell.api.action.Argument) Field(java.lang.reflect.Field) Command(org.apache.karaf.shell.api.action.Command) HelpOption(org.apache.karaf.shell.impl.action.command.HelpOption) Option(org.apache.karaf.shell.api.action.Option)

Example 5 with Command

use of org.apache.karaf.shell.api.action.Command in project ddf by codice.

the class RemoveCommand method executeRemoveFromStore.

private Object executeRemoveFromStore() throws Exception {
    CatalogFacade catalogProvider = getCatalog();
    if (hasFilter()) {
        QueryImpl query = new QueryImpl(getFilter());
        query.setRequestsTotalResultsCount(true);
        query.setPageSize(-1);
        Map<String, Serializable> properties = new HashMap<>();
        properties.put("mode", "native");
        SourceResponse queryResponse = catalogProvider.query(new QueryRequestImpl(query, properties));
        final List<String> idsFromFilteredQuery = queryResponse.getResults().stream().map(result -> result.getMetacard().getId()).collect(Collectors.toList());
        if (ids == null) {
            ids = idsFromFilteredQuery;
        } else {
            ids = ids.stream().filter(id -> idsFromFilteredQuery.contains(id)).collect(Collectors.toList());
        }
    }
    final int numberOfMetacardsToRemove = ids.size();
    if (numberOfMetacardsToRemove > 0) {
        printSuccessMessage("Found " + numberOfMetacardsToRemove + " metacards to remove.");
    } else {
        printErrorMessage("No records found meeting filter criteria.");
        return null;
    }
    DeleteRequestImpl request = new DeleteRequestImpl(ids.toArray(new String[numberOfMetacardsToRemove]));
    DeleteResponse response = catalogProvider.delete(request);
    if (response.getDeletedMetacards().size() > 0) {
        printSuccessMessage(ids + " successfully deleted.");
        LOGGER.info(ids + " removed using catalog:remove command");
    } else {
        printErrorMessage(ids + " could not be deleted.");
        LOGGER.info(ids + " could not be deleted using catalog:remove command");
    }
    return null;
}
Also used : QueryRequestImpl(ddf.catalog.operation.impl.QueryRequestImpl) Arrays(java.util.Arrays) QueryImpl(ddf.catalog.operation.impl.QueryImpl) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) Argument(org.apache.karaf.shell.api.action.Argument) DeleteResponse(ddf.catalog.operation.DeleteResponse) Collectors(java.util.stream.Collectors) Serializable(java.io.Serializable) Command(org.apache.karaf.shell.api.action.Command) List(java.util.List) SourceResponse(ddf.catalog.operation.SourceResponse) CollectionUtils(org.apache.commons.collections.CollectionUtils) Map(java.util.Map) Service(org.apache.karaf.shell.api.action.lifecycle.Service) CatalogFacade(org.codice.ddf.commands.catalog.facade.CatalogFacade) DeleteRequestImpl(ddf.catalog.operation.impl.DeleteRequestImpl) Option(org.apache.karaf.shell.api.action.Option) Serializable(java.io.Serializable) SourceResponse(ddf.catalog.operation.SourceResponse) HashMap(java.util.HashMap) DeleteRequestImpl(ddf.catalog.operation.impl.DeleteRequestImpl) QueryImpl(ddf.catalog.operation.impl.QueryImpl) DeleteResponse(ddf.catalog.operation.DeleteResponse) QueryRequestImpl(ddf.catalog.operation.impl.QueryRequestImpl) CatalogFacade(org.codice.ddf.commands.catalog.facade.CatalogFacade)

Aggregations

Command (org.apache.karaf.shell.api.action.Command)9 Argument (org.apache.karaf.shell.api.action.Argument)6 Option (org.apache.karaf.shell.api.action.Option)6 ArrayList (java.util.ArrayList)5 Field (java.lang.reflect.Field)4 HashMap (java.util.HashMap)4 Map (java.util.Map)4 HashSet (java.util.HashSet)3 List (java.util.List)3 HelpOption (org.apache.karaf.shell.impl.action.command.HelpOption)3 TreeMap (java.util.TreeMap)2 Service (org.apache.karaf.shell.api.action.lifecycle.Service)2 DeleteResponse (ddf.catalog.operation.DeleteResponse)1 SourceResponse (ddf.catalog.operation.SourceResponse)1 DeleteRequestImpl (ddf.catalog.operation.impl.DeleteRequestImpl)1 QueryImpl (ddf.catalog.operation.impl.QueryImpl)1 QueryRequestImpl (ddf.catalog.operation.impl.QueryRequestImpl)1 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1