Sunday, May 8, 2011

Executing external files from a Netbeans plugin

As developers we are familiar with lot of IDEs among them Netbeans is one of the most popular IDE in the world. it is an open source platform and have a pluggable architecture where developers can extend the features of the IDE by adding plugins. the purpose of this article is not to tell how to write Netbeans plugin this will tell you how to call an external batch file exe or if you use Linux how to call a linux command from a plugin.

first create a Netbeans Modules project
 then right click on the project and select new and Action. that will create an Action for you. then right click on the project and select properties and select Libraries

then choose the Add option. tick the Show Non-API Modules option





























press ok..
add the folliwing import statements.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.netbeans.api.extexecution.ExecutionDescriptor;
import org.netbeans.api.extexecution.ExecutionService;

and add this method into the source code :

    public Integer execute() throws InterruptedException, ExecutionException {
        Callable processCallable = new Callable() {

            public Process call() throws IOException {
                return new ProcessBuilder("/bin/ls").start();
            }
        };

        ExecutionDescriptor descriptor = new ExecutionDescriptor().frontWindow(true).controllable(true);

        ExecutionService service = ExecutionService.newService(processCallable,
                descriptor, "ls command");

        Future task = service.run();
        return task.get();
    }
and then call this execute() method from the actionPerformed() method in the Action class.
here i am running ls command in linux but you can use any other external program by giving its path.