Search code examples
javaosgiapache-karafkarafblueprint-osgi

Executing Karaf commands in java


The below code executes karaf commands in the console,

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;
    }
}

I am getting "java.lang.NullPointerException" at the line

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

It's the detail info:

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)

Can anybody help me ?


Solution

  • @Inject does not work in karaf. If you use karaf 4 you can use @Reference from the package org.apache.karaf.shell.api.action.lifecycle.