Example usage for java.lang ProcessBuilder redirectInput

List of usage examples for java.lang ProcessBuilder redirectInput

Introduction

In this page you can find the example usage for java.lang ProcessBuilder redirectInput.

Prototype

public ProcessBuilder redirectInput(File file) 

Source Link

Document

Sets this process builder's standard input source to a file.

Usage

From source file:com.smash.revolance.ui.materials.CmdlineHelper.java

public CmdlineHelper exec() throws InterruptedException, IOException {
    ProcessBuilder pb = new ProcessBuilder();

    if (dir != null) {
        pb.directory(dir);//from www.j a v a2 s  . c  o m
    }

    pb.command(cmd);

    pb.redirectError(ProcessBuilder.Redirect.to(err));
    pb.redirectOutput(ProcessBuilder.Redirect.to(out));
    pb.redirectInput(ProcessBuilder.Redirect.from(in));

    System.out.println("Executing cmd: " + cmd[0] + " from dir: " + dir);
    System.out.println("Redirecting out to: " + out.getAbsolutePath());
    System.out.println("Redirecting err to: " + err.getAbsolutePath());

    Process process = pb.start();
    if (sync) {
        process.waitFor();
    }

    this.process = process;

    return this;
}

From source file:org.apache.nifi.processors.standard.ExecuteStreamCommand.java

@Override
public void onTrigger(ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile inputFlowFile = session.get();
    if (null == inputFlowFile) {
        return;/*from   w ww. j  a  v a  2s  .  c om*/
    }

    final ArrayList<String> args = new ArrayList<>();
    final boolean putToAttribute = context.getProperty(PUT_OUTPUT_IN_ATTRIBUTE).isSet();
    final Integer attributeSize = context.getProperty(PUT_ATTRIBUTE_MAX_LENGTH).asInteger();
    final String attributeName = context.getProperty(PUT_OUTPUT_IN_ATTRIBUTE).getValue();

    final String executeCommand = context.getProperty(EXECUTION_COMMAND)
            .evaluateAttributeExpressions(inputFlowFile).getValue();
    args.add(executeCommand);
    final String commandArguments = context.getProperty(EXECUTION_ARGUMENTS)
            .evaluateAttributeExpressions(inputFlowFile).getValue();
    final boolean ignoreStdin = Boolean.parseBoolean(context.getProperty(IGNORE_STDIN).getValue());
    if (!StringUtils.isBlank(commandArguments)) {
        for (String arg : ArgumentUtils.splitArgs(commandArguments,
                context.getProperty(ARG_DELIMITER).getValue().charAt(0))) {
            args.add(arg);
        }
    }
    final String workingDir = context.getProperty(WORKING_DIR).evaluateAttributeExpressions(inputFlowFile)
            .getValue();

    final ProcessBuilder builder = new ProcessBuilder();

    logger.debug("Executing and waiting for command {} with arguments {}",
            new Object[] { executeCommand, commandArguments });
    File dir = null;
    if (!StringUtils.isBlank(workingDir)) {
        dir = new File(workingDir);
        if (!dir.exists() && !dir.mkdirs()) {
            logger.warn("Failed to create working directory {}, using current working directory {}",
                    new Object[] { workingDir, System.getProperty("user.dir") });
        }
    }
    final Map<String, String> environment = new HashMap<>();
    for (final Map.Entry<PropertyDescriptor, String> entry : context.getProperties().entrySet()) {
        if (entry.getKey().isDynamic()) {
            environment.put(entry.getKey().getName(), entry.getValue());
        }
    }
    builder.environment().putAll(environment);
    builder.command(args);
    builder.directory(dir);
    builder.redirectInput(Redirect.PIPE);
    builder.redirectOutput(Redirect.PIPE);
    final Process process;
    try {
        process = builder.start();
    } catch (IOException e) {
        logger.error("Could not create external process to run command", e);
        throw new ProcessException(e);
    }
    try (final OutputStream pos = process.getOutputStream();
            final InputStream pis = process.getInputStream();
            final InputStream pes = process.getErrorStream();
            final BufferedInputStream bis = new BufferedInputStream(pis);
            final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(pes))) {
        int exitCode = -1;
        final BufferedOutputStream bos = new BufferedOutputStream(pos);
        FlowFile outputFlowFile = putToAttribute ? inputFlowFile : session.create(inputFlowFile);

        ProcessStreamWriterCallback callback = new ProcessStreamWriterCallback(ignoreStdin, bos, bis, logger,
                attributeName, session, outputFlowFile, process, putToAttribute, attributeSize);
        session.read(inputFlowFile, callback);

        outputFlowFile = callback.outputFlowFile;
        if (putToAttribute) {
            outputFlowFile = session.putAttribute(outputFlowFile, attributeName,
                    new String(callback.outputBuffer, 0, callback.size));
        }

        exitCode = callback.exitCode;
        logger.debug("Execution complete for command: {}.  Exited with code: {}",
                new Object[] { executeCommand, exitCode });

        Map<String, String> attributes = new HashMap<>();

        final StringBuilder strBldr = new StringBuilder();
        try {
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                strBldr.append(line).append("\n");
            }
        } catch (IOException e) {
            strBldr.append("Unknown...could not read Process's Std Error");
        }
        int length = strBldr.length() > 4000 ? 4000 : strBldr.length();
        attributes.put("execution.error", strBldr.substring(0, length));

        final Relationship outputFlowFileRelationship = putToAttribute ? ORIGINAL_RELATIONSHIP
                : OUTPUT_STREAM_RELATIONSHIP;
        if (exitCode == 0) {
            logger.info("Transferring flow file {} to {}",
                    new Object[] { outputFlowFile, outputFlowFileRelationship.getName() });
        } else {
            logger.error("Transferring flow file {} to {}. Executable command {} ended in an error: {}",
                    new Object[] { outputFlowFile, outputFlowFileRelationship.getName(), executeCommand,
                            strBldr.toString() });
        }

        attributes.put("execution.status", Integer.toString(exitCode));
        attributes.put("execution.command", executeCommand);
        attributes.put("execution.command.args", commandArguments);
        outputFlowFile = session.putAllAttributes(outputFlowFile, attributes);

        // This transfer will transfer the FlowFile that received the stream out put to it's destined relationship.
        // In the event the stream is put to the an attribute of the original, it will be transferred here.
        session.transfer(outputFlowFile, outputFlowFileRelationship);

        if (!putToAttribute) {
            logger.info("Transferring flow file {} to original", new Object[] { inputFlowFile });
            inputFlowFile = session.putAllAttributes(inputFlowFile, attributes);
            session.transfer(inputFlowFile, ORIGINAL_RELATIONSHIP);
        }

    } catch (final IOException ex) {
        // could not close Process related streams
        logger.warn("Problem terminating Process {}", new Object[] { process }, ex);
    } finally {
        process.destroy(); // last ditch effort to clean up that process.
    }
}

From source file:org.p_vcd.process.ProcessBase.java

private void runCommandInternal(String command, ProcessArguments commandArgs, File workingDir,
        StringBuffer sbSaveStdout, StringBuffer sbSaveStderr) throws Exception {
    commandArgs.insertFirst(command);//from  w  ww  .j  ava 2s .com
    FileUtils.forceMkdir(workingDir);
    StringBuffer sbLog = new StringBuffer();
    sbLog.append("\n").append(MyUtil.getFormateDate());
    commandArgs.addToLog(sbLog);
    System.out.println(sbLog.toString());
    this.status.appendOutputLine(sbLog.toString());
    ProcessBuilder pb = new ProcessBuilder(commandArgs.getCommands());
    pb.directory(workingDir);
    pb.redirectInput(Redirect.INHERIT);
    pb.redirectOutput(Redirect.PIPE);
    pb.redirectError(Redirect.PIPE);
    long init = System.currentTimeMillis();
    this.currentSystemProcess = pb.start();
    PrintThreadWithStatus thStdout = new PrintThreadWithStatus(this.currentSystemProcess.getInputStream(),
            command, this.status, sbSaveStdout);
    PrintThreadWithStatus thStderr = new PrintThreadWithStatus(this.currentSystemProcess.getErrorStream(),
            command, this.status, sbSaveStderr);
    this.currentSystemProcess.getOutputStream().close();
    thStdout.start();
    thStderr.start();
    int ret = -1;
    try {
        this.processRunning = true;
        ret = this.currentSystemProcess.waitFor();
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    } finally {
        this.processRunning = false;
    }
    try {
        thStderr.join();
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
    try {
        thStdout.join();
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    }
    long milis = System.currentTimeMillis() - init;
    if (ret != 0) {
        throw new Exception("command error code=" + ret + " (" + milis + " ms)");
    }
    sbLog = new StringBuffer();
    sbLog.append(MyUtil.getFormateDate()).append("command ").append(command).append(" ok (").append(milis)
            .append(" ms)");
    System.out.println(sbLog.toString());
    this.status.appendOutputLine(sbLog.toString());
}