Karaf 在 java 控制台中执行命令
Karaf executing commands in java console
以下代码在控制台中执行 karaf 命令。这在 karaf 版本 3.0.3 中工作正常。它在 4.0.0 或更高版本中失败
@Inject
CommandProcessor commandProcessor;
private class dummyCallable implements Callable{
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final PrintStream printStream = new PrintStream(byteArrayOutputStream);
final CommandSession commandSession = commandProcessor.createSession(System.in, printStream, System.err);
String[] commands;
dummyCallable( String[] commands){
this.commands = commands;
}
public String call() {
try {
for(String command:commands) {
System.err.println(command);
commandSession.execute(command);
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
return byteArrayOutputStream.toString();
}
}
protected String executeCommands(final String ...commands) {
String response;
dummyCallable dd = new dummyCallable(commands);
ExecutorService executor = Executors.newFixedThreadPool(1);
FutureTask<String> futureTask2 = new FutureTask<String>(dd);
try {
executor.submit(futureTask2);
response = futureTask2.get();
} catch (Exception e) {
e.printStackTrace(System.err);
response = "SHELL COMMAND TIMED OUT: ";
}
return response;
}
任何人都可以向我提供可以在 karaf 4.0.0 上运行的代码吗
在 Karaf 4 中,您应该向您的服务中注入一个 SessionFactory
并调用 sessionFactory.createSession(System.in, printStream, System.err)
Karaf3和Karaf4的方法是一样的,class和包有变化:
- CommandProcessor => SessionFactory
- CommandSession => 会话
以下代码在控制台中执行 karaf 命令。这在 karaf 版本 3.0.3 中工作正常。它在 4.0.0 或更高版本中失败
@Inject
CommandProcessor commandProcessor;
private class dummyCallable implements Callable{
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final PrintStream printStream = new PrintStream(byteArrayOutputStream);
final CommandSession commandSession = commandProcessor.createSession(System.in, printStream, System.err);
String[] commands;
dummyCallable( String[] commands){
this.commands = commands;
}
public String call() {
try {
for(String command:commands) {
System.err.println(command);
commandSession.execute(command);
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
return byteArrayOutputStream.toString();
}
}
protected String executeCommands(final String ...commands) {
String response;
dummyCallable dd = new dummyCallable(commands);
ExecutorService executor = Executors.newFixedThreadPool(1);
FutureTask<String> futureTask2 = new FutureTask<String>(dd);
try {
executor.submit(futureTask2);
response = futureTask2.get();
} catch (Exception e) {
e.printStackTrace(System.err);
response = "SHELL COMMAND TIMED OUT: ";
}
return response;
}
任何人都可以向我提供可以在 karaf 4.0.0 上运行的代码吗
在 Karaf 4 中,您应该向您的服务中注入一个 SessionFactory
并调用 sessionFactory.createSession(System.in, printStream, System.err)
Karaf3和Karaf4的方法是一样的,class和包有变化:
- CommandProcessor => SessionFactory
- CommandSession => 会话