Executing external Processes using ProcessService

ProcessService is a bean which can be injected into a TaskType to execute external processes.

ProcessService uses the ExternalProcessBuilder to collect information such as the command, environment variables and working directory to be used to launch a new process. When the process is executed its output is automatically appended to the build log as it becomes available.

Example

The following Task uses ProcessService to execute the ls Unix/Linux/Mac utility to list the files and directories available in the working directory. The TaskResultBuilder is then used to check that the return code of the process is zero (e.g. that the task is successful).

Example:

import com.atlassian.bamboo.task.TaskContext;
import com.atlassian.bamboo.task.TaskException;
import com.atlassian.bamboo.task.TaskResult;
import com.atlassian.bamboo.task.TaskResultBuilder;
import com.atlassian.bamboo.task.TaskType;
import com.atlassian.utils.process.ExternalProcess;

import java.util.Arrays;

public class ListDirectoryTaskType implements TaskType
{
    private final ProcessService processService;

    public ListDirectoryTaskType(final ProcessService processService)
    {
        this.processService = processService;
    }
    
    public TaskResult execute(final TaskContext taskContext) throws TaskException
    {
        TaskResultBuilder builder = TaskResultBuilder.create(taskContext);
        
        ExternalProcess process = processService.createProcess(taskContext, 
                new ExternalProcessBuilder()
                .command(Arrays.asList("/bin/ls"))
                .workingDirectory(taskContext.getWorkingDirectory()));

        process.execute();
        
        return builder.checkReturnCode(process, 0).build();
    }
}
Was this page helpful?

Have a question about this article?

See questions about this article

Powered by Confluence and Scroll Viewport