Search in sources :

Example 1 with SessionFactory

use of org.apache.karaf.shell.api.console.SessionFactory in project ddf by codice.

the class CommandJob method doExecute.

private void doExecute(final String commandString) {
    final SessionFactory sessionFactory = getSessionFactory();
    if (sessionFactory != null) {
        try (final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            final PrintStream output = createPrintStream(byteArrayOutputStream);
            // parameter from a SessionFactory
            final InputStream emptyInputStream = new InputStream() {

                @Override
                public int read() throws IOException {
                    LOGGER.error("This method implementation of an InputStream is just a work-around for a Karaf bug and should never be called. There is an issue with the Platform Command Scheduler implementation.");
                    return -1;
                }
            };
            final Session session = sessionFactory.create(emptyInputStream, output, output)) {
            if (session != null) {
                LOGGER.trace("Executing command \"{}\"", LogSanitizer.sanitize(commandString));
                try {
                    session.execute(commandString);
                    try {
                        final String commandOutput = byteArrayOutputStream.toString(StandardCharsets.UTF_8.name());
                        LOGGER.info("Execution output for command \"{}\": {}", LogSanitizer.sanitize(commandString), LogSanitizer.sanitize(commandOutput));
                    } catch (UnsupportedEncodingException e) {
                        LOGGER.debug("Unable to get command output.", e);
                    }
                } catch (Exception e) {
                    logWarningMessage(commandString);
                    LOGGER.debug("Unable to execute command.", e);
                }
            } else {
                logWarningMessage(commandString);
                LOGGER.debug("Unable to create session.");
            }
        } catch (IOException e) {
            logWarningMessage(commandString);
            LOGGER.debug("Unable to create session.", e);
        }
    } else {
        logWarningMessage(commandString);
        LOGGER.debug("Unable to create session factory.");
    }
}
Also used : SessionFactory(org.apache.karaf.shell.api.console.SessionFactory) PrintStream(java.io.PrintStream) InputStream(java.io.InputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) IOException(java.io.IOException) ExecutionException(org.apache.shiro.subject.ExecutionException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Session(org.apache.karaf.shell.api.console.Session)

Example 2 with SessionFactory

use of org.apache.karaf.shell.api.console.SessionFactory in project ddf by codice.

the class CommandJobTest method testSimpleCommand.

/**
 * Tests the simplest command will be executed
 */
@Test
public void testSimpleCommand() throws Exception {
    FirstArgumentAnswer captureInput = new FirstArgumentAnswer();
    Session session = mock(Session.class);
    when(session.execute(isA(CharSequence.class))).then(captureInput);
    CommandJob commandJob = new CommandJob(new Security()) {

        @Override
        public Subject getSystemSubject() {
            return createMockSubject();
        }

        @Override
        protected SessionFactory getSessionFactory() {
            SessionFactory sessionFactory = mock(SessionFactory.class);
            when(sessionFactory.create(notNull(), any(), any())).thenReturn(session);
            return sessionFactory;
        }
    };
    String command = VALID_COMMAND;
    // when
    commandJob.execute(createMockJobExecutionContext(command));
    // then
    assertThat(captureInput.getInputArg(), is(command));
    verify(session, times(1)).execute(command);
    verify(session, times(1)).close();
}
Also used : SessionFactory(org.apache.karaf.shell.api.console.SessionFactory) Security(org.codice.ddf.security.impl.Security) Session(org.apache.karaf.shell.api.console.Session) Test(org.junit.Test)

Example 3 with SessionFactory

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

the class KarafTestSupport method executeCommand.

/**
 * Executes a shell command or alias and returns output as a String.
 *
 * @param command    The command to execute.
 * @param timeout    The amount of time in millis to wait for the command to execute.
 * @param silent     Specifies if the command should be displayed in the screen.
 * @param principals The principals (e.g. RolePrincipal objects) to run the command under
 * @return the result of executing the command/alias
 */
private String executeCommand(final String command, final Long timeout, final Long commandServiceTimeout, final Boolean silent, final Principal... principals) {
    waitForCommandService(command, commandServiceTimeout);
    String response;
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    final PrintStream printStream = new PrintStream(byteArrayOutputStream);
    final SessionFactory sessionFactory = getOsgiService(SessionFactory.class);
    final Session session = sessionFactory.create(System.in, printStream, System.err);
    final Callable<String> commandCallable = () -> {
        try {
            if (!silent) {
                System.err.println(command);
            }
            // load all aliases defined in the init script in the session
            executeInitScript(session);
            Object result = session.execute(command);
            if (result != null) {
                session.getConsole().println(result.toString());
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        printStream.flush();
        return byteArrayOutputStream.toString();
    };
    FutureTask<String> commandFuture;
    if (principals.length == 0) {
        commandFuture = new FutureTask<>(commandCallable);
    } else {
        // If principals are defined, run the command callable via Subject.doAs()
        commandFuture = new FutureTask<>(() -> {
            Subject subject = new Subject();
            subject.getPrincipals().addAll(Arrays.asList(principals));
            return Subject.doAs(subject, (PrivilegedExceptionAction<String>) commandCallable::call);
        });
    }
    try {
        executor.submit(commandFuture);
        response = commandFuture.get(timeout, TimeUnit.MILLISECONDS);
    } catch (TimeoutException e) {
        e.printStackTrace(System.err);
        response = "SHELL COMMAND TIMED OUT: ";
    } catch (ExecutionException e) {
        Throwable cause = e.getCause() != null ? (e.getCause().getCause() != null ? e.getCause().getCause() : e.getCause()) : e;
        throw new RuntimeException(cause.getMessage(), cause);
    } catch (InterruptedException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    return response;
}
Also used : SessionFactory(org.apache.karaf.shell.api.console.SessionFactory) PrintStream(java.io.PrintStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) PrivilegedExceptionAction(java.security.PrivilegedExceptionAction) TimeoutException(java.util.concurrent.TimeoutException) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) RerunTestException(org.ops4j.pax.exam.RerunTestException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) Subject(javax.security.auth.Subject) ExecutionException(java.util.concurrent.ExecutionException) Session(org.apache.karaf.shell.api.console.Session) TimeoutException(java.util.concurrent.TimeoutException)

Example 4 with SessionFactory

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

the class Activator method start.

@Override
public void start(final BundleContext context) throws Exception {
    threadIO = new ThreadIOImpl();
    threadIO.start();
    sessionFactory = new SecuredSessionFactoryImpl(context, threadIO);
    sessionFactory.getCommandProcessor().addConverter(new Converters(context));
    sessionFactory.getCommandProcessor().addConstant(".context", context.getBundle(0).getBundleContext());
    final CopyOnWriteArraySet<CommandLoggingFilter> listeners = new CopyOnWriteArraySet<>();
    filterTracker = new ServiceTracker<>(context, CommandLoggingFilter.class, new ServiceTrackerCustomizer<CommandLoggingFilter, CommandLoggingFilter>() {

        @Override
        public CommandLoggingFilter addingService(ServiceReference<CommandLoggingFilter> reference) {
            CommandLoggingFilter service = context.getService(reference);
            listeners.add(service);
            return service;
        }

        @Override
        public void modifiedService(ServiceReference<CommandLoggingFilter> reference, CommandLoggingFilter service) {
        }

        @Override
        public void removedService(ServiceReference<CommandLoggingFilter> reference, CommandLoggingFilter service) {
            listeners.remove(service);
            context.ungetService(reference);
        }
    });
    filterTracker.open();
    LoggingCommandSessionListener loggingCommandSessionListener = new LoggingCommandSessionListener();
    loggingCommandSessionListener.setFilters(listeners);
    sessionFactory.getCommandProcessor().addListener(loggingCommandSessionListener);
    try {
        EventAdminListener listener = new EventAdminListener(context);
        sessionFactory.getCommandProcessor().addListener(listener);
        eventAdminListener = listener;
    } catch (NoClassDefFoundError error) {
    // Ignore the listener if EventAdmin package isn't present
    }
    sessionFactory.register(new ManagerImpl(sessionFactory, sessionFactory));
    sessionFactoryRegistration = context.registerService(SessionFactory.class, sessionFactory, null);
    commandProcessorRegistration = context.registerService(CommandProcessor.class, sessionFactory.getCommandProcessor(), null);
    actionExtender = new CommandExtender(sessionFactory);
    actionExtender.start(context);
    commandTracker = new CommandTracker(sessionFactory, context);
    commandTracker.open();
    converterTracker = new ConverterTracker(sessionFactory, context);
    converterTracker.open();
    listenerTracker = new ListenerTracker(sessionFactory, context);
    listenerTracker.open();
    if (Boolean.parseBoolean(context.getProperty(START_CONSOLE))) {
        localConsoleManager = new LocalConsoleManager(context, sessionFactory);
        localConsoleManager.start();
    } else {
        LOGGER.info("Not starting local console. To activate set " + START_CONSOLE + "=true");
    }
}
Also used : SessionFactory(org.apache.karaf.shell.api.console.SessionFactory) SecuredSessionFactoryImpl(org.apache.karaf.shell.impl.console.osgi.secured.SecuredSessionFactoryImpl) ThreadIOImpl(org.apache.felix.gogo.runtime.threadio.ThreadIOImpl) ServiceTrackerCustomizer(org.osgi.util.tracker.ServiceTrackerCustomizer) CopyOnWriteArraySet(java.util.concurrent.CopyOnWriteArraySet) ServiceReference(org.osgi.framework.ServiceReference) CommandExtender(org.apache.karaf.shell.impl.action.osgi.CommandExtender) ManagerImpl(org.apache.karaf.shell.impl.action.command.ManagerImpl) CommandLoggingFilter(org.apache.karaf.shell.api.console.CommandLoggingFilter) CommandProcessor(org.apache.felix.service.command.CommandProcessor)

Example 5 with SessionFactory

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

the class Main method run.

private void run(ThreadIO threadio, String[] args, InputStream in, PrintStream out, PrintStream err) throws Exception {
    StringBuilder sb = new StringBuilder();
    String classpath = null;
    boolean batch = false;
    String file = null;
    for (int i = 0; i < args.length; i++) {
        String arg = args[i];
        if (arg.startsWith("--classpath=")) {
            classpath = arg.substring("--classpath=".length());
        } else if (arg.startsWith("-c=")) {
            classpath = arg.substring("-c=".length());
        } else if (arg.equals("--classpath") || arg.equals("-c")) {
            classpath = args[++i];
        } else if (arg.equals("-b") || arg.equals("--batch")) {
            batch = true;
        } else if (arg.startsWith("--file=")) {
            file = arg.substring("--file=".length());
        } else if (arg.startsWith("-f=")) {
            file = arg.substring("-f=".length());
        } else if (arg.equals("--file") || arg.equals("-f")) {
            file = args[++i];
        } else {
            sb.append(arg);
            sb.append(' ');
        }
    }
    if (file != null) {
        try (Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
            sb.setLength(0);
            for (int c = reader.read(); c >= 0; c = reader.read()) {
                sb.append((char) c);
            }
        }
    } else if (batch) {
        Reader reader = new BufferedReader(new InputStreamReader(System.in));
        sb.setLength(0);
        for (int c = reader.read(); c >= 0; reader.read()) {
            sb.append((char) c);
        }
    }
    ClassLoader cl = Main.class.getClassLoader();
    if (classpath != null) {
        List<URL> urls = getFiles(new File(classpath));
        // Load jars in class path to be able to load jars inside them
        ClassLoader tmpClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), cl);
        URL.setURLStreamHandlerFactory(new JarInJarURLStreamHandlerFactory(tmpClassLoader));
        List<URL> jarsInJars = getJarsInJars(urls);
        // Create ClassLoader with jars in jars and parent main ClassLoader
        cl = new URLClassLoader(jarsInJars.toArray(new URL[jarsInJars.size()]), cl);
        // Load original Jars with jarsInJars ClassLoader as parent.
        // This is needed cause if you load Class from main jar which depends on class in inner jar.
        // The loaded class has its class loader and resolve dependant classes in its or parent classloaders
        // which exclude jarInJar classloader.
        cl = new URLClassLoader(urls.toArray(new URL[urls.size()]), cl);
    }
    SessionFactory sessionFactory = createSessionFactory(threadio);
    run(sessionFactory, sb.toString(), in, out, err, cl);
}
Also used : SessionFactory(org.apache.karaf.shell.api.console.SessionFactory) InputStreamReader(java.io.InputStreamReader) JarInJarURLStreamHandlerFactory(org.apache.karaf.shell.impl.console.loader.JarInJarURLStreamHandlerFactory) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) FileInputStream(java.io.FileInputStream) URL(java.net.URL) URLClassLoader(java.net.URLClassLoader) BufferedReader(java.io.BufferedReader) URLClassLoader(java.net.URLClassLoader) JarFile(java.util.jar.JarFile) File(java.io.File)

Aggregations

SessionFactory (org.apache.karaf.shell.api.console.SessionFactory)9 PrintStream (java.io.PrintStream)5 Session (org.apache.karaf.shell.api.console.Session)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 IOException (java.io.IOException)3 InputStream (java.io.InputStream)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 ThreadIOImpl (org.apache.felix.gogo.runtime.threadio.ThreadIOImpl)2 CommandProcessor (org.apache.felix.service.command.CommandProcessor)2 ThreadIO (org.apache.felix.service.threadio.ThreadIO)2 SessionFactoryImpl (org.apache.karaf.shell.impl.console.SessionFactoryImpl)2 Test (org.junit.Test)2 BufferedReader (java.io.BufferedReader)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 InputStreamReader (java.io.InputStreamReader)1 Reader (java.io.Reader)1 URL (java.net.URL)1 URLClassLoader (java.net.URLClassLoader)1