在 java 中执行 Karaf 命令

Executing Karaf commands in java

以下代码在控制台中执行 karaf 命令,

public class DummyCallable {
    @Inject
    protected SessionFactory sessionFactory;
    private Session session;
    private ExecutorService executor;

    private ByteArrayOutputStream byteArrayOutputStream;
    private PrintStream printStream;
    private PrintStream errStream;

    public DummyCallable() {
        byteArrayOutputStream = new ByteArrayOutputStream();
        printStream = new PrintStream(byteArrayOutputStream);
        errStream = new PrintStream(byteArrayOutputStream);

        executor = Executors.newCachedThreadPool();
        session = sessionFactory.create(System.in, printStream, errStream);
    }

    public String executeCommand(final String command) throws IOException {
        byteArrayOutputStream.flush();
        byteArrayOutputStream.reset();

        String response;
        FutureTask<String> commandFuture = new FutureTask<String> (new Callable<String>() {
            public String call() {
                try {
                    System.err.println(command);
                    session.execute(command);
                }
                catch (Exception e) {
                    e.printStackTrace(System.err);
                }

                printStream.flush();
                errStream.flush();
                return byteArrayOutputStream.toString();
            }
        });

        try {
            executor.submit(commandFuture);
            response = commandFuture.get(10000L, TimeUnit.MILLISECONDS);
        }
        catch (Exception e) {
            e.printStackTrace(System.err);
            response = "SHELL COMMAND TIMED OUT: ";
        }

        System.err.println(response);

        return response;
    }
}

我在 "java.lang.NullPointerException" 行

"session = sessionFactory.create(System.in, printStream, errStream);"

详细信息:

java.lang.NullPointerException
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

有人可以帮我吗?

@Inject 在 karaf 中不起作用。如果您使用 karaf 4,您可以使用包 org.apache.karaf.shell.api.action.lifecycle.

中的 @Reference