Search in sources :

Example 1 with CommandSession

use of org.apache.felix.service.command.CommandSession in project opennms by OpenNMS.

the class KarafTestCase method executeCommand.

/**
     * Executes a shell command and returns output as a String.
     * Commands have a default timeout of 10 seconds.
     *
     * @param command
     * @return
     */
protected String executeCommand(final String command) {
    try (final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        final PrintStream printStream = new PrintStream(byteArrayOutputStream)) {
        Subject subject = new Subject();
        subject.getPrincipals().add(new RolePrincipal("admin"));
        return Subject.doAs(subject, new PrivilegedExceptionAction<String>() {

            @Override
            public String run() throws Exception {
                final CommandProcessor commandProcessor = getOsgiService(CommandProcessor.class);
                final CommandSession commandSession = commandProcessor.createSession(System.in, printStream, System.err);
                LOG.info("{}", command);
                Object response = commandSession.execute(command);
                LOG.info("Response: {}", response);
                printStream.flush();
                return byteArrayOutputStream.toString();
            }
        });
    } catch (Exception e) {
        LOG.error("Error while executing command", e);
        throw new RuntimeException(e);
    }
}
Also used : PrintStream(java.io.PrintStream) CommandSession(org.apache.felix.service.command.CommandSession) CommandProcessor(org.apache.felix.service.command.CommandProcessor) ByteArrayOutputStream(java.io.ByteArrayOutputStream) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) Subject(javax.security.auth.Subject)

Example 2 with CommandSession

use of org.apache.felix.service.command.CommandSession in project karaf by apache.

the class CommandTracker method addingService.

@Override
public List<Command> addingService(final ServiceReference<Object> reference) {
    final String scope = reference.getProperty(CommandProcessor.COMMAND_SCOPE).toString();
    final Object function = reference.getProperty(CommandProcessor.COMMAND_FUNCTION);
    final List<String> names = new ArrayList<>();
    if (function.getClass().isArray()) {
        for (final Object f : ((Object[]) function)) {
            names.add(f.toString());
        }
    } else {
        names.add(function.toString());
    }
    List<Command> commands = new ArrayList<>();
    for (String name : names) {
        final Function target = new CommandProxy(context, reference, name);
        Command command = new Command() {

            @Override
            public String getScope() {
                return scope;
            }

            @Override
            public String getName() {
                return name;
            }

            @Override
            public String getDescription() {
                Object property = reference.getProperty("osgi.command.description");
                if (property != null) {
                    return property.toString();
                } else {
                    return getName();
                }
            }

            @Override
            public Completer getCompleter(final boolean scoped) {
                return null;
            }

            @Override
            public Parser getParser() {
                return null;
            }

            @Override
            public Object execute(Session session, List<Object> arguments) throws Exception {
                // TODO: remove not really nice cast
                CommandSession commandSession = (CommandSession) session.get(".commandSession");
                return target.execute(commandSession, arguments);
            }
        };
        sessionFactory.getRegistry().register(command);
        commands.add(command);
    }
    return commands;
}
Also used : Function(org.apache.felix.service.command.Function) CommandProxy(org.apache.felix.gogo.runtime.CommandProxy) CommandSession(org.apache.felix.service.command.CommandSession) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) CommandSession(org.apache.felix.service.command.CommandSession)

Example 3 with CommandSession

use of org.apache.felix.service.command.CommandSession in project karaf by apache.

the class ArgumentCompleter method complete.

public int complete(final String buffer, final int cursor, final List<String> candidates) {
    ArgumentList list = delimit(buffer, cursor);
    int argpos = list.getArgumentPosition();
    int argIndex = list.getCursorArgumentIndex();
    //Store the argument list so that it can be used by completers.
    CommandSession commandSession = CommandSessionHolder.getSession();
    if (commandSession != null) {
        commandSession.put(ARGUMENTS_LIST, list);
    }
    Completer comp = null;
    String[] args = list.getArguments();
    int index = 0;
    // First argument is command name
    if (index < argIndex) {
        // Verify command name
        if (!verifyCompleter(commandCompleter, args[index])) {
            return -1;
        }
        // - we have a session
        if (!args[index].contains(":") && commandSession != null) {
            Function f1 = unProxy((Function) commandSession.get("*:" + args[index]));
            Function f2 = unProxy(this.function);
            if (f1 != null && f1 != f2) {
                return -1;
            }
        }
        index++;
    } else {
        comp = commandCompleter;
    }
    // Now, check options
    if (comp == null) {
        while (index < argIndex && args[index].startsWith("-")) {
            if (!verifyCompleter(optionsCompleter, args[index])) {
                return -1;
            }
            Option option = options.get(args[index]);
            if (option == null) {
                return -1;
            }
            Field field = fields.get(option);
            if (field != null && field.getType() != boolean.class && field.getType() != Boolean.class) {
                if (++index == argIndex) {
                    comp = NullCompleter.INSTANCE;
                }
            }
            index++;
        }
        if (comp == null && index >= argIndex && index < args.length && args[index].startsWith("-")) {
            comp = optionsCompleter;
        }
    }
    //Now check for if last Option has a completer
    int lastAgurmentIndex = argIndex - 1;
    if (lastAgurmentIndex >= 1) {
        Option lastOption = options.get(args[lastAgurmentIndex]);
        if (lastOption != null) {
            Field lastField = fields.get(lastOption);
            if (lastField != null && lastField.getType() != boolean.class && lastField.getType() != Boolean.class) {
                Option option = lastField.getAnnotation(Option.class);
                if (option != null) {
                    Completer optionValueCompleter = null;
                    String name = option.name();
                    if (optionalCompleters != null && name != null) {
                        optionValueCompleter = optionalCompleters.get(name);
                        if (optionValueCompleter == null) {
                            String[] aliases = option.aliases();
                            if (aliases.length > 0) {
                                for (int i = 0; i < aliases.length && optionValueCompleter == null; i++) {
                                    optionValueCompleter = optionalCompleters.get(option.aliases()[i]);
                                }
                            }
                        }
                    }
                    if (optionValueCompleter != null) {
                        comp = optionValueCompleter;
                    }
                }
            }
        }
    }
    // Check arguments
    if (comp == null) {
        int indexArg = 0;
        while (index < argIndex) {
            Completer sub = argsCompleters.get(indexArg >= argsCompleters.size() ? argsCompleters.size() - 1 : indexArg);
            if (!verifyCompleter(sub, args[index])) {
                return -1;
            }
            index++;
            indexArg++;
        }
        comp = argsCompleters.get(indexArg >= argsCompleters.size() ? argsCompleters.size() - 1 : indexArg);
    }
    int ret = comp.complete(list.getCursorArgument(), argpos, candidates);
    if (ret == -1) {
        return -1;
    }
    int pos = ret + (list.getBufferPosition() - argpos);
    if ((buffer != null) && (cursor != buffer.length()) && isDelimiter(buffer, cursor)) {
        for (int i = 0; i < candidates.size(); i++) {
            String val = candidates.get(i);
            while ((val.length() > 0) && isDelimiter(val, val.length() - 1)) {
                val = val.substring(0, val.length() - 1);
            }
            candidates.set(i, val);
        }
    }
    return pos;
}
Also used : CompletableFunction(org.apache.karaf.shell.console.CompletableFunction) Function(org.apache.felix.service.command.Function) Field(java.lang.reflect.Field) CommandSession(org.apache.felix.service.command.CommandSession) Completer(org.apache.karaf.shell.console.Completer) Option(org.apache.karaf.shell.commands.Option) HelpOption(org.apache.karaf.shell.commands.HelpOption)

Example 4 with CommandSession

use of org.apache.felix.service.command.CommandSession in project karaf by apache.

the class OldArgumentCompleter method complete.

public int complete(final String buffer, final int cursor, final List<String> candidates) {
    ArgumentList list = delimit(buffer, cursor);
    int argpos = list.getArgumentPosition();
    int argIndex = list.getCursorArgumentIndex();
    //Store the argument list so that it can be used by completers.
    CommandSession commandSession = CommandSessionHolder.getSession();
    if (commandSession != null) {
        commandSession.put(ARGUMENTS_LIST, list);
    }
    Completer comp = null;
    String[] args = list.getArguments();
    int index = 0;
    // First argument is command name
    if (index < argIndex) {
        // Verify command name
        if (!verifyCompleter(commandCompleter, args[index])) {
            return -1;
        }
        index++;
    } else {
        comp = commandCompleter;
    }
    // Now, check options
    if (comp == null) {
        while (index < argIndex && args[index].startsWith("-")) {
            if (!verifyCompleter(optionsCompleter, args[index])) {
                return -1;
            }
            Option option = options.get(args[index]);
            if (option == null) {
                return -1;
            }
            Field field = fields.get(option);
            if (field != null && field.getType() != boolean.class && field.getType() != Boolean.class) {
                if (++index == argIndex) {
                    comp = NullCompleter.INSTANCE;
                }
            }
            index++;
        }
        if (comp == null && index >= argIndex && index < args.length && args[index].startsWith("-")) {
            comp = optionsCompleter;
        }
    }
    //Now check for if last Option has a completer
    int lastAgurmentIndex = argIndex - 1;
    if (lastAgurmentIndex >= 1) {
        Option lastOption = options.get(args[lastAgurmentIndex]);
        if (lastOption != null) {
            Field lastField = fields.get(lastOption);
            if (lastField != null && lastField.getType() != boolean.class && lastField.getType() != Boolean.class) {
                Option option = lastField.getAnnotation(Option.class);
                if (option != null) {
                    Completer optionValueCompleter = null;
                    String name = option.name();
                    if (optionalCompleters != null && name != null) {
                        optionValueCompleter = optionalCompleters.get(name);
                        if (optionValueCompleter == null) {
                            String[] aliases = option.aliases();
                            if (aliases.length > 0) {
                                for (int i = 0; i < aliases.length && optionValueCompleter == null; i++) {
                                    optionValueCompleter = optionalCompleters.get(option.aliases()[i]);
                                }
                            }
                        }
                    }
                    if (optionValueCompleter != null) {
                        comp = optionValueCompleter;
                    }
                }
            }
        }
    }
    // Check arguments
    if (comp == null) {
        int indexArg = 0;
        while (index < argIndex) {
            Completer sub = argsCompleters.get(indexArg >= argsCompleters.size() ? argsCompleters.size() - 1 : indexArg);
            if (!verifyCompleter(sub, args[index])) {
                return -1;
            }
            index++;
            indexArg++;
        }
        comp = argsCompleters.get(indexArg >= argsCompleters.size() ? argsCompleters.size() - 1 : indexArg);
    }
    int ret = comp.complete(list.getCursorArgument(), argpos, candidates);
    if (ret == -1) {
        return -1;
    }
    int pos = ret + (list.getBufferPosition() - argpos);
    if ((buffer != null) && (cursor != buffer.length()) && isDelimiter(buffer, cursor)) {
        for (int i = 0; i < candidates.size(); i++) {
            String val = candidates.get(i);
            while ((val.length() > 0) && isDelimiter(val, val.length() - 1)) {
                val = val.substring(0, val.length() - 1);
            }
            candidates.set(i, val);
        }
    }
    return pos;
}
Also used : Field(java.lang.reflect.Field) CommandSession(org.apache.felix.service.command.CommandSession) Completer(org.apache.karaf.shell.console.Completer) Option(org.apache.felix.gogo.commands.Option)

Example 5 with CommandSession

use of org.apache.felix.service.command.CommandSession in project karaf by apache.

the class OldArgumentCompleter method complete.

public int complete(final Session session, final CommandLine list, final List<String> candidates) {
    int argpos = list.getArgumentPosition();
    int argIndex = list.getCursorArgumentIndex();
    //Store the argument list so that it can be used by completers.
    CommandSession commandSession = CommandSessionHolder.getSession();
    if (commandSession != null) {
        commandSession.put(ARGUMENTS_LIST, list);
    }
    Completer comp = null;
    String[] args = list.getArguments();
    int index = 0;
    // First argument is command name
    if (index < argIndex) {
        // Verify scope
        if (!Session.SCOPE_GLOBAL.equals(scope) && !session.resolveCommand(args[index]).equals(scope + ":" + name)) {
            return -1;
        }
        // Verify command name
        if (!verifyCompleter(commandCompleter, args[index])) {
            return -1;
        }
        index++;
    } else {
        comp = commandCompleter;
    }
    // Now, check options
    if (comp == null) {
        while (index < argIndex && args[index].startsWith("-")) {
            if (!verifyCompleter(optionsCompleter, args[index])) {
                return -1;
            }
            Option option = options.get(args[index]);
            if (option == null) {
                return -1;
            }
            Field field = fields.get(option);
            if (field != null && field.getType() != boolean.class && field.getType() != Boolean.class) {
                if (++index == argIndex) {
                    comp = NullCompleter.INSTANCE;
                }
            }
            index++;
        }
        if (comp == null && index >= argIndex && index < args.length && args[index].startsWith("-")) {
            comp = optionsCompleter;
        }
    }
    //Now check for if last Option has a completer
    int lastAgurmentIndex = argIndex - 1;
    if (lastAgurmentIndex >= 1) {
        Option lastOption = options.get(args[lastAgurmentIndex]);
        if (lastOption != null) {
            Field lastField = fields.get(lastOption);
            if (lastField != null && lastField.getType() != boolean.class && lastField.getType() != Boolean.class) {
                Option option = lastField.getAnnotation(Option.class);
                if (option != null) {
                    Completer optionValueCompleter = null;
                    String name = option.name();
                    if (optionalCompleters != null && name != null) {
                        optionValueCompleter = optionalCompleters.get(name);
                        if (optionValueCompleter == null) {
                            String[] aliases = option.aliases();
                            if (aliases.length > 0) {
                                for (int i = 0; i < aliases.length && optionValueCompleter == null; i++) {
                                    optionValueCompleter = optionalCompleters.get(option.aliases()[i]);
                                }
                            }
                        }
                    }
                    if (optionValueCompleter != null) {
                        comp = optionValueCompleter;
                    }
                }
            }
        }
    }
    // Check arguments
    if (comp == null) {
        int indexArg = 0;
        while (index < argIndex) {
            Completer sub = argsCompleters.get(indexArg >= argsCompleters.size() ? argsCompleters.size() - 1 : indexArg);
            if (!verifyCompleter(sub, args[index])) {
                return -1;
            }
            index++;
            indexArg++;
        }
        comp = argsCompleters.get(indexArg >= argsCompleters.size() ? argsCompleters.size() - 1 : indexArg);
    }
    int ret = comp.complete(list.getCursorArgument(), argpos, candidates);
    if (ret == -1) {
        return -1;
    }
    int pos = ret + (list.getBufferPosition() - argpos);
    /**
         *  Special case: when completing in the middle of a line, and the
         *  area under the cursor is a delimiter, then trim any delimiters
         *  from the candidates, since we do not need to have an extra
         *  delimiter.
         *
         *  E.g., if we have a completion for "foo", and we
         *  enter "f bar" into the buffer, and move to after the "f"
         *  and hit TAB, we want "foo bar" instead of "foo  bar".
         */
    String buffer = list.getBuffer();
    int cursor = list.getBufferPosition();
    if ((buffer != null) && (cursor != buffer.length()) && isDelimiter(buffer, cursor)) {
        for (int i = 0; i < candidates.size(); i++) {
            String val = candidates.get(i);
            while ((val.length() > 0) && isDelimiter(val, val.length() - 1)) {
                val = val.substring(0, val.length() - 1);
            }
            candidates.set(i, val);
        }
    }
    return pos;
}
Also used : Field(java.lang.reflect.Field) CommandSession(org.apache.felix.service.command.CommandSession) FileCompleter(org.apache.karaf.shell.console.completer.FileCompleter) Completer(org.apache.karaf.shell.console.Completer) StringsCompleter(org.apache.karaf.shell.console.completer.StringsCompleter) NullCompleter(org.apache.karaf.shell.console.completer.NullCompleter) Option(org.apache.felix.gogo.commands.Option)

Aggregations

CommandSession (org.apache.felix.service.command.CommandSession)10 Field (java.lang.reflect.Field)4 Completer (org.apache.karaf.shell.console.Completer)4 List (java.util.List)3 Function (org.apache.felix.service.command.Function)3 Session (org.apache.karaf.shell.api.console.Session)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 PrintStream (java.io.PrintStream)2 Subject (javax.security.auth.Subject)2 Option (org.apache.felix.gogo.commands.Option)2 Closure (org.apache.felix.gogo.runtime.Closure)2 CommandProcessor (org.apache.felix.service.command.CommandProcessor)2 HelpOption (org.apache.karaf.shell.commands.HelpOption)2 Option (org.apache.karaf.shell.commands.Option)2 FileCompleter (org.apache.karaf.shell.console.completer.FileCompleter)2 NullCompleter (org.apache.karaf.shell.console.completer.NullCompleter)2 StringsCompleter (org.apache.karaf.shell.console.completer.StringsCompleter)2 Method (java.lang.reflect.Method)1 ArrayList (java.util.ArrayList)1 Callable (java.util.concurrent.Callable)1