Search in sources :

Example 6 with CommandSession

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

the class SecuredCommand method execute.

@Override
public Object execute(final CommandSession commandSession, List<Object> arguments) throws Exception {
    // TODO: remove the hack for .session
    Session session = (Session) commandSession.get(".session");
    // When need to translate closures to a compatible type for the command
    for (int i = 0; i < arguments.size(); i++) {
        Object v = arguments.get(i);
        if (v instanceof Closure) {
            final Closure closure = (Closure) v;
            arguments.set(i, new VersatileFunction(closure));
        }
        if (v instanceof Token) {
            arguments.set(i, v.toString());
        }
    }
    return execute(session, arguments);
}
Also used : Closure(org.apache.felix.gogo.runtime.Closure) Token(org.apache.felix.gogo.runtime.Token) Session(org.apache.karaf.shell.api.console.Session) CommandSession(org.apache.felix.service.command.CommandSession)

Example 7 with CommandSession

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

the class ArgumentCompleter 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.karaf.shell.commands.Option) HelpOption(org.apache.karaf.shell.commands.HelpOption)

Example 8 with CommandSession

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

the class CommandWrapper method execute.

@Override
public Object execute(final CommandSession commandSession, List<Object> arguments) throws Exception {
    // TODO: remove the hack for .session
    Session session = (Session) commandSession.get(".session");
    // When need to translate closures to a compatible type for the command
    for (int i = 0; i < arguments.size(); i++) {
        Object v = arguments.get(i);
        if (v instanceof Closure) {
            final Closure closure = (Closure) v;
            arguments.set(i, (org.apache.karaf.shell.api.console.Function) (s, a) -> closure.execute(commandSession, a));
        }
    }
    return command.execute(session, arguments);
}
Also used : Session(org.apache.karaf.shell.api.console.Session) List(java.util.List) Closure(org.apache.felix.gogo.runtime.Closure) Function(org.apache.felix.service.command.Function) CommandSession(org.apache.felix.service.command.CommandSession) Command(org.apache.karaf.shell.api.console.Command) Closure(org.apache.felix.gogo.runtime.Closure) Session(org.apache.karaf.shell.api.console.Session) CommandSession(org.apache.felix.service.command.CommandSession)

Example 9 with CommandSession

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

the class CommandTracker method addingService.

@Override
public Object addingService(final ServiceReference reference) {
    Object service = context.getService(reference);
    if (service instanceof CommandWithAction) {
        final CommandWithAction oldCommand = (CommandWithAction) service;
        final org.apache.karaf.shell.api.console.Command command = new org.apache.karaf.shell.api.console.Command() {

            @Override
            public String getScope() {
                return reference.getProperty(CommandProcessor.COMMAND_SCOPE).toString();
            }

            @Override
            public String getName() {
                return reference.getProperty(CommandProcessor.COMMAND_FUNCTION).toString();
            }

            @Override
            public String getDescription() {
                final Command cmd = oldCommand.getActionClass().getAnnotation(Command.class);
                if (cmd != null) {
                    return cmd.description();
                }
                try {
                    Method method = oldCommand.getActionClass().getMethod("description");
                    method.setAccessible(true);
                    return (String) method.invoke(oldCommand.createNewAction());
                } catch (Throwable ignore) {
                }
                return getName();
            }

            @Override
            public Completer getCompleter(final boolean scoped) {
                final ArgumentCompleter completer = new ArgumentCompleter(oldCommand, getScope(), getName(), scoped);
                return completer::complete;
            }

            @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 oldCommand.execute(commandSession, arguments);
            }
        };
        sessionFactory.getRegistry().register(command);
        return command;
    } else if (service instanceof org.apache.felix.gogo.commands.CommandWithAction) {
        final org.apache.felix.gogo.commands.CommandWithAction oldCommand = (org.apache.felix.gogo.commands.CommandWithAction) service;
        final org.apache.karaf.shell.api.console.Command command = new org.apache.karaf.shell.api.console.Command() {

            @Override
            public String getScope() {
                return reference.getProperty(CommandProcessor.COMMAND_SCOPE).toString();
            }

            @Override
            public String getName() {
                return reference.getProperty(CommandProcessor.COMMAND_FUNCTION).toString();
            }

            @Override
            public String getDescription() {
                final org.apache.felix.gogo.commands.Command cmd = oldCommand.getActionClass().getAnnotation(org.apache.felix.gogo.commands.Command.class);
                if (cmd != null) {
                    return cmd.description();
                }
                try {
                    Method method = oldCommand.getActionClass().getMethod("description");
                    method.setAccessible(true);
                    return (String) method.invoke(oldCommand.createNewAction());
                } catch (Throwable ignore) {
                }
                return getName();
            }

            @Override
            public Completer getCompleter(final boolean scoped) {
                final OldArgumentCompleter completer = new OldArgumentCompleter(oldCommand, getScope(), getName(), scoped);
                return completer::complete;
            }

            @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 oldCommand.execute(commandSession, arguments);
            }
        };
        sessionFactory.getRegistry().register(command);
        return command;
    } else {
        return null;
    }
}
Also used : List(java.util.List) Completer(org.apache.karaf.shell.api.console.Completer) Method(java.lang.reflect.Method) CommandWithAction(org.apache.karaf.shell.commands.CommandWithAction) Parser(org.apache.karaf.shell.api.console.Parser) CommandSession(org.apache.felix.service.command.CommandSession) Command(org.apache.karaf.shell.commands.Command) Session(org.apache.karaf.shell.api.console.Session) CommandSession(org.apache.felix.service.command.CommandSession)

Example 10 with CommandSession

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

the class OSGiShellCommand method execute.

@Override
public void execute(AdminCommandContext context) {
    ActionReport report = context.getActionReport();
    if (instance != null) {
        Server svr = domain.getServerNamed(instance);
        if (svr == null) {
            report.setMessage("No server target found for " + instance);
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
        String host = svr.getAdminHost();
        int port = svr.getAdminPort();
        try {
            ServerRemoteAdminCommand remote = new ServerRemoteAdminCommand(locator, "osgi", host, port, false, "admin", "", log);
            ParameterMap params = new ParameterMap();
            if (commandLine == null) {
                params.set("DEFAULT".toLowerCase(Locale.US), "asadmin-osgi-shell");
            } else if (commandLine instanceof String) {
                params.set("DEFAULT".toLowerCase(Locale.US), (String) commandLine);
            } else if (commandLine instanceof List) {
                params.set("DEFAULT".toLowerCase(Locale.US), (List<String>) commandLine);
            }
            if (sessionOp != null) {
                params.set("session", sessionOp);
            }
            if (sessionId != null) {
                params.set("session-id", sessionId);
            }
            report.setMessage(remote.executeCommand(params));
            report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
            return;
        } catch (CommandException x) {
            report.setMessage("Remote execution failed: " + x.getMessage());
            report.setFailureCause(x);
            report.setActionExitCode(ActionReport.ExitCode.FAILURE);
            return;
        }
    }
    String cmdName = "";
    String cmd = "";
    if (commandLine == null) {
        cmd = "asadmin-osgi-shell";
        cmdName = cmd;
    } else if (commandLine instanceof String) {
        cmd = (String) commandLine;
        cmdName = cmd;
    } else if (commandLine instanceof List) {
        for (Object arg : (List) commandLine) {
            if (cmd.length() == 0) {
                // first arg
                cmd = (String) arg;
                cmdName = cmd;
            } else {
                cmd += " " + (String) arg;
            }
        }
    } else if (commandLine instanceof String[]) {
        for (Object arg : (String[]) commandLine) {
            if (cmd.length() == 0) {
                // first arg
                cmd = (String) arg;
                cmdName = cmd;
            } else {
                cmd += " " + (String) arg;
            }
        }
    } else {
        // shouldn't happen...
        report.setMessage("Unable to deal with argument list of type " + commandLine.getClass().getName());
        report.setActionExitCode(ActionReport.ExitCode.WARNING);
        return;
    }
    // standard output...
    ByteArrayOutputStream bOut = new ByteArrayOutputStream(512);
    PrintStream out = new PrintStream(bOut);
    // error output...
    ByteArrayOutputStream bErr = new ByteArrayOutputStream(512);
    PrintStream err = new PrintStream(bErr);
    try {
        Object shell = null;
        ServiceReference sref = ctx.getServiceReference("org.apache.felix.service.command.CommandProcessor");
        if (sref != null) {
            shell = ctx.getService(sref);
        }
        if (shell == null) {
            // try with felix...
            sref = ctx.getServiceReference("org.apache.felix.shell.ShellService");
            if (sref != null) {
                shell = ctx.getService(sref);
            }
            if (shell == null) {
                report.setMessage("No Shell Service available");
                report.setActionExitCode(ActionReport.ExitCode.WARNING);
                return;
            } else if ("asadmin-osgi-shell".equals(cmdName)) {
                out.println("felix");
            } else {
                ShellService s = (ShellService) shell;
                s.executeCommand(cmd, out, err);
            }
        } else {
            // try with gogo...
            // GLASSFISH-19126 - prepare fake input stream...
            InputStream in = new InputStream() {

                @Override
                public int read() throws IOException {
                    return -1;
                }

                @Override
                public int available() throws IOException {
                    return 0;
                }

                @Override
                public int read(byte[] b) throws IOException {
                    return -1;
                }

                @Override
                public int read(byte[] b, int off, int len) throws IOException {
                    return -1;
                }
            };
            CommandProcessor cp = (CommandProcessor) shell;
            if (sessionOp == null) {
                if ("asadmin-osgi-shell".equals(cmdName)) {
                    out.println("gogo");
                } else {
                    CommandSession session = cp.createSession(in, out, err);
                    session.execute(cmd);
                    session.close();
                }
            } else if ("new".equals(sessionOp)) {
                CommandSession session = cp.createSession(null, null, null);
                RemoteCommandSession remote = new RemoteCommandSession(session);
                log.log(Level.FINE, "Remote session established: {0}", remote.getId());
                sessions.put(remote.getId(), remote);
                out.println(remote.getId());
            } else if ("list".equals(sessionOp)) {
                for (String id : sessions.keySet()) {
                    out.println(id);
                }
            } else if ("execute".equals(sessionOp)) {
                RemoteCommandSession remote = sessions.get(sessionId);
                CommandSession session = remote.attach(in, out, err);
                session.execute(cmd);
                remote.detach();
            } else if ("stop".equals(sessionOp)) {
                RemoteCommandSession remote = sessions.remove(sessionId);
                CommandSession session = remote.attach(in, out, err);
                session.close();
                log.log(Level.FINE, "Remote session closed: {0}", remote.getId());
            }
        }
        out.flush();
        err.flush();
        String output = bOut.toString("UTF-8");
        String errors = bErr.toString("UTF-8");
        report.setMessage(output);
        if (errors.length() > 0) {
            report.setMessage(errors);
            report.setActionExitCode(ActionReport.ExitCode.WARNING);
        } else {
            report.setActionExitCode(ActionReport.ExitCode.SUCCESS);
        }
    } catch (Exception ex) {
        report.setMessage(ex.getMessage());
        report.setActionExitCode(ActionReport.ExitCode.WARNING);
    }
}
Also used : PrintStream(java.io.PrintStream) Server(com.sun.enterprise.config.serverbeans.Server) InputStream(java.io.InputStream) ServerRemoteAdminCommand(com.sun.enterprise.admin.remote.ServerRemoteAdminCommand) ParameterMap(org.glassfish.api.admin.ParameterMap) CommandException(org.glassfish.api.admin.CommandException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ActionReport(org.glassfish.api.ActionReport) RestEndpoint(org.glassfish.api.admin.RestEndpoint) CommandException(org.glassfish.api.admin.CommandException) IOException(java.io.IOException) ServiceReference(org.osgi.framework.ServiceReference) ShellService(org.apache.felix.shell.ShellService) CommandSession(org.apache.felix.service.command.CommandSession) CommandProcessor(org.apache.felix.service.command.CommandProcessor) List(java.util.List)

Aggregations

CommandSession (org.apache.felix.service.command.CommandSession)10 Field (java.lang.reflect.Field)4 List (java.util.List)4 Completer (org.apache.karaf.shell.console.Completer)4 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 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 ServerRemoteAdminCommand (com.sun.enterprise.admin.remote.ServerRemoteAdminCommand)1 Server (com.sun.enterprise.config.serverbeans.Server)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1