org.xlcloud.xsa.ext.hpc.service.process.ProcessExecutor.java Source code

Java tutorial

Introduction

Here is the source code for org.xlcloud.xsa.ext.hpc.service.process.ProcessExecutor.java

Source

/*
 * Copyright 2012 AMG.lab, a Bull Group Company
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.xlcloud.xsa.ext.hpc.service.process;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.xlcloud.rest.exception.InternalErrorException;

/**
 * Class simplifying running processes, writing to their input and reading from their output.
 *
 * @author Krzysztof Szafraski, AMG.net
 */
public class ProcessExecutor {

    private static final Logger LOG = Logger.getLogger(ProcessExecutor.class);

    /**
     * Runs the specified command. Returns whole process output and its exit code.
     * 
     * @param command
     * @return
     * @throws InternalErrorException when there was an IOException or InterruptedException
     */
    public ProcessExecutionResult run(List<String> command) throws InternalErrorException {
        return run(command, Collections.<String>emptyList());
    }

    /**
     * Runs the specified command, and then writes lines from inputLines one by
     * one to the process input stream. Returns whole process output and its exit code.
     * 
     * @param command
     * @param inputLines
     * @return
     * @throws InternalErrorException when there was an IOException or InterruptedException
     */
    public ProcessExecutionResult run(List<String> command, List<String> inputLines) throws InternalErrorException {
        try {
            // run the command
            ProcessBuilder processBuilder = new ProcessBuilder(command).redirectErrorStream(true);
            Process process = processBuilder.start();

            // input all given lines
            if (!inputLines.isEmpty()) {
                BufferedWriter writer = new BufferedWriter(new PrintWriter(process.getOutputStream()));
                for (String inputLine : inputLines) {
                    writer.write(inputLine);
                    writer.newLine();
                }
                writer.close();
            }

            // read the whole output
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder output = new StringBuilder();
            // We avoid using readLine(), because we want to have a raw output (readLine() skips end-of-line chars).
            char[] buffer = new char[1024];
            int numRead;
            while ((numRead = reader.read(buffer)) != -1) {
                output.append(buffer, 0, numRead);
            }
            reader.close();

            ProcessExecutionResult result = new ProcessExecutionResult();
            result.setExitCode(process.waitFor());
            result.setOutput(output.toString());
            return result;
        } catch (IOException | InterruptedException e) {
            LOG.error(e.getMessage(), e);
            throw new InternalErrorException(
                    "An error occurred when executing command: " + StringUtils.join(command, " "), e.getMessage());
        }
    }
}