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.");
}
}
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();
}
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;
}
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");
}
}
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);
}
Aggregations