Search in sources :

Example 11 with Session

use of org.apache.karaf.shell.api.console.Session in project karaf by apache.

the class ShellCommand method run.

public void run() {
    int exitStatus = 0;
    try {
        final Session session = sessionFactory.create(in, new PrintStream(out), new PrintStream(err));
        for (Map.Entry<String, String> e : env.getEnv().entrySet()) {
            session.put(e.getKey(), e.getValue());
        }
        try {
            Subject subject = this.session != null ? this.session.getAttribute(KarafJaasAuthenticator.SUBJECT_ATTRIBUTE_KEY) : null;
            Object result;
            if (subject != null) {
                try {
                    result = JaasHelper.doAs(subject, (PrivilegedExceptionAction<Object>) () -> {
                        String scriptFileName = System.getProperty(EXEC_INIT_SCRIPT);
                        if (scriptFileName == null) {
                            scriptFileName = System.getProperty(SHELL_INIT_SCRIPT);
                        }
                        executeScript(scriptFileName, session);
                        return session.execute(command);
                    });
                } catch (PrivilegedActionException e) {
                    throw e.getException();
                }
            } else {
                String scriptFileName = System.getProperty(EXEC_INIT_SCRIPT);
                if (scriptFileName == null) {
                    scriptFileName = System.getProperty(SHELL_INIT_SCRIPT);
                }
                executeScript(scriptFileName, session);
                result = session.execute(command);
            }
            if (result != null) {
            // TODO: print the result of the command ?
            //                    session.getConsole().println(session.format(result, Converter.INSPECT));
            }
        } catch (Throwable t) {
            exitStatus = 1;
            ShellUtil.logException(session, t);
        }
    } catch (Exception e) {
        exitStatus = 1;
        LOGGER.error("Unable to start shell", e);
    } finally {
        StreamUtils.close(in, out, err);
        callback.onExit(exitStatus);
    }
}
Also used : PrintStream(java.io.PrintStream) PrivilegedActionException(java.security.PrivilegedActionException) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) Map(java.util.Map) Subject(javax.security.auth.Subject) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) Session(org.apache.karaf.shell.api.console.Session) ServerSession(org.apache.sshd.server.session.ServerSession)

Example 12 with Session

use of org.apache.karaf.shell.api.console.Session in project karaf by apache.

the class SuCommand method execute.

@Override
public Object execute() throws Exception {
    Subject subject = new Subject();
    LoginContext loginContext = new LoginContext(realm, subject, callbacks -> {
        for (Callback callback : callbacks) {
            if (callback instanceof NameCallback) {
                ((NameCallback) callback).setName(user);
            } else if (callback instanceof PasswordCallback) {
                String password = SuCommand.this.session.readLine("Password: ", '*');
                ((PasswordCallback) callback).setPassword(password.toCharArray());
            } else {
                throw new UnsupportedCallbackException(callback);
            }
        }
    });
    loginContext.login();
    JaasHelper.doAs(subject, (PrivilegedExceptionAction<Object>) () -> {
        final Session newSession = session.getFactory().create(System.in, System.out, System.err, SuCommand.this.session.getTerminal(), null, null);
        Object oldIgnoreInterrupts = session.get(Session.IGNORE_INTERRUPTS);
        try {
            session.put(Session.IGNORE_INTERRUPTS, Boolean.TRUE);
            String name = "Karaf local console user " + ShellUtil.getCurrentUserName();
            Thread thread = new Thread(newSession, name);
            thread.start();
            thread.join();
        } finally {
            session.put(Session.IGNORE_INTERRUPTS, oldIgnoreInterrupts);
        }
        return null;
    });
    loginContext.logout();
    return null;
}
Also used : LoginContext(javax.security.auth.login.LoginContext) PasswordCallback(javax.security.auth.callback.PasswordCallback) NameCallback(javax.security.auth.callback.NameCallback) Callback(javax.security.auth.callback.Callback) NameCallback(javax.security.auth.callback.NameCallback) PasswordCallback(javax.security.auth.callback.PasswordCallback) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) Subject(javax.security.auth.Subject) Session(org.apache.karaf.shell.api.console.Session)

Example 13 with Session

use of org.apache.karaf.shell.api.console.Session in project karaf by apache.

the class HelpCommand method getCompleter.

@Override
public Completer getCompleter(final boolean scoped) {
    return new Completer() {

        @Override
        public int complete(Session session, CommandLine commandLine, List<String> candidates) {
            String[] args = commandLine.getArguments();
            int argIndex = commandLine.getCursorArgumentIndex();
            StringsCompleter completer = new StringsCompleter(Collections.singletonList(getName()));
            if (argIndex == 0) {
                return completer.complete(session, new ArgumentCommandLine(args[argIndex], commandLine.getArgumentPosition()), candidates);
            } else if (!verifyCompleter(session, completer, args[0])) {
                return -1;
            }
            // TODO: use CommandNamesCompleter and better completion wrt parsing etc...
            completer = new StringsCompleter();
            for (Command command : session.getRegistry().getCommands()) {
                if (!Session.SCOPE_GLOBAL.equals(command.getScope())) {
                    completer.getStrings().add(command.getScope() + ":" + command.getName());
                }
                completer.getStrings().add(command.getName());
            }
            completer.getStrings().add("--help");
            if (argIndex == 1) {
                int res;
                if (argIndex < args.length) {
                    res = completer.complete(session, new ArgumentCommandLine(args[argIndex], commandLine.getArgumentPosition()), candidates);
                } else {
                    res = completer.complete(session, new ArgumentCommandLine("", 0), candidates);
                }
                return res + (commandLine.getBufferPosition() - commandLine.getArgumentPosition());
            } else if (!verifyCompleter(session, completer, args[1])) {
                return -1;
            }
            return -1;
        }

        protected boolean verifyCompleter(Session session, Completer completer, String argument) {
            List<String> candidates = new ArrayList<>();
            return completer.complete(session, new ArgumentCommandLine(argument, argument.length()), candidates) != -1 && !candidates.isEmpty();
        }
    };
}
Also used : ArgumentCommandLine(org.apache.karaf.shell.support.completers.ArgumentCommandLine) CommandLine(org.apache.karaf.shell.api.console.CommandLine) ArgumentCommandLine(org.apache.karaf.shell.support.completers.ArgumentCommandLine) StringsCompleter(org.apache.karaf.shell.support.completers.StringsCompleter) Command(org.apache.karaf.shell.api.console.Command) ArrayList(java.util.ArrayList) Completer(org.apache.karaf.shell.api.console.Completer) StringsCompleter(org.apache.karaf.shell.support.completers.StringsCompleter) ArrayList(java.util.ArrayList) List(java.util.List) Session(org.apache.karaf.shell.api.console.Session)

Example 14 with Session

use of org.apache.karaf.shell.api.console.Session in project karaf by apache.

the class SingleCommandHelpProvider method getHelp.

public String getHelp(Session session, String path) {
    if (path.indexOf('|') > 0) {
        if (path.startsWith("command|")) {
            path = path.substring("command|".length());
        } else {
            return null;
        }
    }
    ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos, true);
    Session s = session.getFactory().create(bais, ps, ps, session);
    s.put(Session.SCOPE, session.get(Session.SCOPE));
    s.put(Session.SUBSHELL, session.get(Session.SUBSHELL));
    try {
        s.execute(path + " --help");
    } catch (Throwable t) {
        return null;
    } finally {
        s.close();
    }
    return baos.toString();
}
Also used : PrintStream(java.io.PrintStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Session(org.apache.karaf.shell.api.console.Session)

Example 15 with Session

use of org.apache.karaf.shell.api.console.Session 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)

Aggregations

Session (org.apache.karaf.shell.api.console.Session)18 PrintStream (java.io.PrintStream)7 Test (org.junit.Test)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 Subject (javax.security.auth.Subject)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 IOException (java.io.IOException)3 List (java.util.List)3 CommandSession (org.apache.felix.service.command.CommandSession)3 PrivilegedExceptionAction (java.security.PrivilegedExceptionAction)2 Closure (org.apache.felix.gogo.runtime.Closure)2 ThreadIOImpl (org.apache.felix.gogo.runtime.threadio.ThreadIOImpl)2 Command (org.apache.karaf.shell.api.console.Command)2 Completer (org.apache.karaf.shell.api.console.Completer)2 SessionFactory (org.apache.karaf.shell.api.console.SessionFactory)2 ActionCommand (org.apache.karaf.shell.impl.action.command.ActionCommand)2 ManagerImpl (org.apache.karaf.shell.impl.action.command.ManagerImpl)2 HeadlessSessionImpl (org.apache.karaf.shell.impl.console.HeadlessSessionImpl)2 JLineTerminal (org.apache.karaf.shell.impl.console.JLineTerminal)2 SessionFactoryImpl (org.apache.karaf.shell.impl.console.SessionFactoryImpl)2