在java中执行Karaf命令

时间:2016-03-15 10:39:56

标签: java osgi apache-karaf karaf blueprint-osgi

以下代码在控制台中执行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)

有人能帮助我吗?

1 个答案:

答案 0 :(得分:0)

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