Example usage for java.lang Process getOutputStream

List of usage examples for java.lang Process getOutputStream

Introduction

In this page you can find the example usage for java.lang Process getOutputStream.

Prototype

public abstract OutputStream getOutputStream();

Source Link

Document

Returns the output stream connected to the normal input of the process.

Usage

From source file:org.pentaho.di.trans.steps.orabulkloader.OraBulkDataOutput.java

public void open(VariableSpace space, Process sqlldrProcess) throws KettleException {
    String loadMethod = meta.getLoadMethod();
    try {//from w w  w  .j a v a2  s . c  om
        OutputStream os;

        if (OraBulkLoaderMeta.METHOD_AUTO_CONCURRENT.equals(loadMethod)) {
            os = sqlldrProcess.getOutputStream();
        } else {
            // Else open the data file filled in.
            String dataFilePath = getFilename(
                    getFileObject(space.environmentSubstitute(meta.getDataFile()), space));
            File dataFile = new File(dataFilePath);
            // Make sure the parent directory exists
            dataFile.getParentFile().mkdirs();
            os = new FileOutputStream(dataFile, false);
        }

        String encoding = meta.getEncoding();
        if (Utils.isEmpty(encoding)) {
            // Use the default encoding.
            output = new BufferedWriter(new OutputStreamWriter(os));
        } else {
            // Use the specified encoding
            output = new BufferedWriter(new OutputStreamWriter(os, encoding));
        }
    } catch (IOException e) {
        throw new KettleException("IO exception occured: " + e.getMessage(), e);
    }
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.spec.DuplicateGerritListenersPreloadedProjectHudsonTestCase.java

/**
 * Tests that configuring an existing project via jenkins cli doesn't produce duplicated triggers
 * and that the trigger is configured for the new project pattern.
 *
 * @throws Exception if so//from   w w  w . java2s  . c om
 */
@Test
@LocalData
public void testReconfigureUsingCli() throws Exception {
    assertNrOfEventListeners(0);
    TopLevelItem testProj = j.jenkins.getItem("testProj");
    String gerritProjectPattern = "someotherproject";
    Document document = loadConfigXmlViaCli(testProj);
    String xml = changeConfigXml(gerritProjectPattern, document);

    List<String> cmd = javaCliJarCmd("update-job", testProj.getFullName());
    Process process = Runtime.getRuntime().exec(cmd.toArray(new String[cmd.size()]));
    OutputStream output = process.getOutputStream();
    IOUtils.write(xml, output);
    IOUtils.closeQuietly(output);
    String response = IOUtils.toString(process.getInputStream());
    System.out.println(response);
    assertEquals(0, process.waitFor());
    assertNrOfEventListeners(0);
    assertEventListenerWithSomeOtherProjectSet(gerritProjectPattern);
}

From source file:org.globus.workspace.WorkspaceUtil.java

/**
 * @param command command array/*  www  . j  a  va2 s . c o m*/
 * @param event passing in false disables the event log
 * @param stdin stdin for process
 * @param eventLog log events to info?
 * @param traceLog alternatively, log events to trace?
 * @param trackingID optional for event logging, an id > 0?
 * @return stdout
 * @throws WorkspaceException exc
 * @throws ReturnException if exit code != 0, will contain return code
 *         as well as stdout and stderr if they exist.
 */
public static String runCommand(String[] command, boolean event, String stdin, boolean eventLog,
        boolean traceLog, int trackingID) throws WorkspaceException, ReturnException {

    if (command == null) {
        logger.error("Command cannot be null");
        throw new WorkspaceException("Command cannot be null");
    }

    if (eventLog && event) {
        logger.info(Lager.ev(trackingID) + printCmd(command));
    } else if (traceLog && event) {
        logger.trace(printCmd(command));
    }

    final Runtime runtime = Runtime.getRuntime();
    String stdout = null;
    String stderr = null;
    InputStream processStdoutStream = null;
    InputStream processStderrStream = null;

    try {
        final Process process = runtime.exec(command);

        // Unfortunately there can be buffer overflow problems if there are
        // not threads consuming stdout/stderr, seen that with workspace-
        // control create commands on certain platforms.

        processStderrStream = process.getErrorStream();
        final FutureTask stderrConsumer = new FutureTask(new StreamConsumer(processStderrStream));

        processStdoutStream = process.getInputStream();
        final FutureTask stdoutConsumer = new FutureTask(new StreamConsumer(processStdoutStream));

        executor.submit(stdoutConsumer);
        executor.submit(stderrConsumer);

        if (stdin != null) {
            if (traceLog) {
                logger.trace("stdin provided");
            }
            BufferedWriter in = null;
            OutputStreamWriter osw = null;
            OutputStream os = null;
            try {
                os = process.getOutputStream();
                osw = new OutputStreamWriter(os);
                in = new BufferedWriter(osw);
                in.write(stdin);
                in.newLine();
                in.flush();
            } finally {
                if (in != null) {
                    in.close();
                }
                if (osw != null) {
                    osw.close();
                }
                if (os != null) {
                    os.close();
                }
            }
            if (traceLog) {
                logger.trace("stdin sent");
            }
        } else {
            OutputStream os = null;
            try {
                os = process.getOutputStream();
            } finally {
                if (os != null) {
                    os.close();
                }
            }
        }

        final int returnCode;
        try {
            returnCode = process.waitFor();
        } catch (InterruptedException exp) {
            logger.error("Interupped exp thrown ", exp);
            throw new WorkspaceException("Interrupted: ", exp);
        }

        if (eventLog && event) {
            logger.info(Lager.ev(trackingID) + "Return code is " + returnCode);
        } else if (traceLog && event) {
            logger.trace("Return code is " + returnCode);
        }

        try {
            stdout = (String) stdoutConsumer.get(60L, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        try {
            stderr = (String) stderrConsumer.get(60L, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        if (returnCode != 0) {
            if (stderr != null && stdout != null) {

                logger.error(Lager.ev(trackingID) + "system command FAILURE" + "\nSTDOUT:\n" + stdout
                        + "\n\nSTDERR:\n" + stderr);

                throw new ReturnException(returnCode, stderr, stdout);

            } else if (stderr != null) {

                logger.error(Lager.ev(trackingID) + "system command FAILURE" + "\nSTDERR:\n" + stderr);
                throw new ReturnException(returnCode, stderr);

            } else {

                logger.error(Lager.ev(trackingID) + "system command FAILURE, no stdout or stderr");
                throw new ReturnException(returnCode);
            }

        } else {
            if (stdout != null) {
                if (eventLog && event) {
                    logger.info(Lager.ev(trackingID) + "\n" + "STDOUT:\n" + stdout);
                } else if (traceLog && event) {
                    logger.trace("\nSTDOUT:\n" + stdout);
                }
            }
        }
    } catch (IOException ioe) {
        logger.error(ioe);
        throw new WorkspaceException("", ioe);
    } finally {
        try {

            if (processStdoutStream != null) {
                processStdoutStream.close();
            }
            if (processStderrStream != null) {
                processStderrStream.close();
            }
        } catch (IOException exp) {
            logger.error("Could not close stream", exp);
        }
    }

    // may be null
    return stdout;
}

From source file:org.uoa.eolus.template.Nest.java

public void copyUserToUserTemplate(String fromuser, String touser, String template, String target, boolean move)
        throws DirectoryException {
    String cmd = "mv";
    if (move)/* w w  w .  j  ava2s  .  c om*/
        cmd = "mv " + repo + "/" + fromuser + "/" + template + " " + repo + "/" + touser + "/" + target
                + "; exit; \n";
    else
        cmd = "cp -r " + repo + "/" + fromuser + "/" + template + " " + repo + "/" + touser + "/." + target
                + "; mv " + repo + "/" + touser + "/." + target + " " + repo + "/" + touser + "/" + target
                + "; exit; \n";

    System.out.println("CMD: " + cmd);
    Runtime run = Runtime.getRuntime();
    try {
        Process child = run.exec("/bin/bash");
        BufferedWriter outCommand = new BufferedWriter(new OutputStreamWriter(child.getOutputStream()));
        outCommand.write(cmd);
        outCommand.flush();
        // child.waitFor();
        // if (child.exitValue() != 0)
        // return false;
        // else
    } catch (Exception e) {
        throw new DirectoryException("Cannot execute cp/mv command.", e);
    }
}

From source file:com.sastix.cms.common.services.htmltopdf.PdfImpl.java

public byte[] getPDF() throws IOException, InterruptedException {
    ProcessBuilder processBuilder = new ProcessBuilder(getCommandAsArray());
    Process process = processBuilder.start();
    //Runtime runtime = Runtime.getRuntime();
    //Process process = runtime.exec(getCommandAsArray());

    for (Page page : pages) {
        if (page.getType().equals(PageType.htmlAsString)) {
            OutputStream stdInStream = process.getOutputStream();
            stdInStream.write(page.getSource().getBytes("UTF-8"));
            stdInStream.close();/* www  . java2 s.  c om*/
        }
    }

    StreamEater outputStreamEater = new StreamEater(process.getInputStream());
    outputStreamEater.start();

    StreamEater errorStreamEater = new StreamEater(process.getErrorStream());
    errorStreamEater.start();

    outputStreamEater.join();
    errorStreamEater.join();
    process.waitFor();

    if (process.exitValue() != 0) {
        throw new RuntimeException("Process (" + getCommand() + ") exited with status code "
                + process.exitValue() + ":\n" + new String(errorStreamEater.getBytes()));
    }

    if (outputStreamEater.getError() != null) {
        throw outputStreamEater.getError();
    }

    if (errorStreamEater.getError() != null) {
        throw errorStreamEater.getError();
    }

    return outputStreamEater.getBytes();
}

From source file:azkaban.utils.FileIOUtils.java

/**
 * Run a unix command that will symlink files, and recurse into directories.
 *///from w  w w . j a  va 2s.  c  om
public static void createDeepSymlink(File sourceDir, File destDir) throws IOException {
    if (!sourceDir.exists()) {
        throw new IOException("Source directory " + sourceDir.getPath() + " doesn't exist");
    } else if (!destDir.exists()) {
        throw new IOException("Destination directory " + destDir.getPath() + " doesn't exist");
    } else if (sourceDir.isFile() && destDir.isFile()) {
        throw new IOException("Source or Destination is not a directory.");
    }

    Set<String> paths = new HashSet<String>();
    createDirsFindFiles(sourceDir, sourceDir, destDir, paths);

    StringBuffer buffer = new StringBuffer();
    for (String path : paths) {
        File sourceLink = new File(sourceDir, path);
        path = "." + path;

        buffer.append("ln -s ").append(sourceLink.getAbsolutePath()).append("/*").append(" ").append(path)
                .append(";");
    }

    String command = buffer.toString();
    ProcessBuilder builder = new ProcessBuilder().command("sh", "-c", command);
    builder.directory(destDir);

    // XXX what about stopping threads ??
    Process process = builder.start();
    try {
        NullLogger errorLogger = new NullLogger(process.getErrorStream());
        NullLogger inputLogger = new NullLogger(process.getInputStream());
        errorLogger.start();
        inputLogger.start();

        try {
            if (process.waitFor() < 0) {
                // Assume that the error will be in standard out. Otherwise it'll be
                // in standard in.
                String errorMessage = errorLogger.getLastMessages();
                if (errorMessage.isEmpty()) {
                    errorMessage = inputLogger.getLastMessages();
                }

                throw new IOException(errorMessage);
            }

            // System.out.println(errorLogger.getLastMessages());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } finally {
        IOUtils.closeQuietly(process.getInputStream());
        IOUtils.closeQuietly(process.getOutputStream());
        IOUtils.closeQuietly(process.getErrorStream());
    }
}

From source file:com.appcel.core.encoder.executor.FfmpegEncoderExecutor.java

public void execute(MediaRecord record, File directory) throws EncoderException {

    LOGGER.info(" ffmpeg ?  video ...  Ffmpeg  ===>>> " + args);

    final ProcessBuilder pb = new ProcessBuilder().directory(directory);
    pb.redirectErrorStream(true);/*  ww w . j  a v  a2 s.co  m*/
    if (null != directory) {
        LOGGER.info("ffmpeg ??==========>>>" + directory.toString());
    }

    pb.command(args);

    try {
        final Process process = pb.start();
        inputStream = process.getInputStream();

        MediaInputStreamParser.parseMediaRecord(inputStream, record);

        outputStream = process.getOutputStream();
        errorStream = process.getErrorStream();
        // ???????.
        //         BufferedInputStream in = new BufferedInputStream(inputStream);
        //         BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
        //         String lineStr;
        //         while ((lineStr = inBr.readLine()) != null)
        //            LOGGER.info("process.getInputStream() ===>>> " + lineStr);

        int waitfor = process.waitFor();
        if (waitfor != 0) {
            //p.exitValue()==0?1??
            if (process.exitValue() == 1) {
                LOGGER.info("===>>> ffmpeg ? Failed!");
                throw new EncoderException("ffmpeg ? Failed!");
            } else {
                LOGGER.info("==========>>> ffmpeg ??.");
            }
        } else {
            LOGGER.info("==========>>> ffmpeg ??.");
        }

    } catch (IOException e) {
        LOGGER.error("==========>>> ffmpeg ? Message: " + e.getMessage());
        LOGGER.error("==========>>> ffmpeg ? Cause: " + e.getCause());
        e.printStackTrace();
    } catch (InterruptedException e) {
        LOGGER.error("==========>>> ffmpeg ? Message: " + e.getMessage());
        LOGGER.error("==========>>> ffmpeg ? Cause: " + e.getCause());
        e.printStackTrace();
        Thread.currentThread().interrupt();
    } finally {
        destroy();
    }
}

From source file:com.kolich.common.util.runtime.RuntimeClosure.java

private final Either<Exception, T> doit(final Process process) {
    Either<Exception, T> result = null;
    try {/*from   w w w.  jav a  2 s  .c o m*/
        result = Right.right(run(process));
        success(process);
    } catch (Exception e) {
        result = Left.left(e);
    } finally {
        if (process != null) {
            closeQuietly(process.getInputStream());
            closeQuietly(process.getOutputStream());
            closeQuietly(process.getErrorStream());
        }
    }
    return result;
}

From source file:org.squale.welcom.outils.rsh.Impl.CmdRshClient.java

/**
 * Retourne le resultat d'un commande Unix en rsh Attention : le buffer est limit a 1024.
 * //from  ww w.ja v a  2 s  .com
 * @param cmd : Commande unix
 * @param buff : Ecrit dans l'entree standard le contenu
 * @throws IOException : Retourne le buffer rcp ou bien une erreur d'execution
 * @return resultat unix
 */
public int executecmd(final String cmd, final byte buff[]) throws IOException {
    lastReturnStream = null;
    lastErrorStream = null;

    Process rsh = null;
    int exitVal = DEFAULT_EXIT_VAL;

    // Stocke ce que l'on a envoyer
    final String cmdsend = rshCmd + cmd;
    addMessage(cmdsend + "\n");

    try {
        rsh = Runtime.getRuntime().exec(cmdsend);

        // Si on a quelquechose dans le buffer
        if (buff != null) {
            CopyUtils.copy(buff, rsh.getOutputStream());
            addMessage(buff);
            rsh.getOutputStream().close();
        }

        exitVal = rsh.waitFor();

        if (rsh.getInputStream() != null) {
            lastReturnStream = IOUtils.toString(rsh.getInputStream());
            addMessage(lastReturnStream);
        }

        if (rsh.getErrorStream() != null) {
            lastErrorStream = IOUtils.toString(rsh.getErrorStream());

            if (lastErrorStream.length() > 0) {
                addMessage(lastErrorStream);

                return 1;
            }
        }
    } catch (final IOException ioe) {
        addMessage(ioe.getMessage());
        throw ioe;
    } catch (final InterruptedException e) {
        addMessage(e.getMessage());
        throw new IOException(e.getMessage());
    }

    if (exitVal == 0) {
        addMessage(">OK\n");
    }

    return exitVal;
}

From source file:org.uoa.eolus.template.Nest.java

public void copyUserTemplate(String user, String template, String target, boolean move)
        throws DirectoryException {
    String cmd = "mv";
    if (move)//from w w w.  j a va  2  s  .c  o m
        cmd = "mv " + repo + "/" + user + "/" + template + " " + repo + "/" + user + "/" + target
                + "; exit; \n";
    else
        cmd = "cp -r " + repo + "/" + user + "/" + template + " " + repo + "/" + user + "/." + target + "; mv "
                + repo + "/" + user + "/." + target + " " + repo + "/" + user + "/" + target + "; exit; \n";

    System.out.println("CMD: " + cmd);

    Runtime run = Runtime.getRuntime();
    try {
        Process child = run.exec("/bin/bash");
        BufferedWriter outCommand = new BufferedWriter(new OutputStreamWriter(child.getOutputStream()));
        outCommand.write(cmd);
        outCommand.flush();
        //         InputStream out = child.getInputStream();
        //         InputStreamReader isr = new InputStreamReader(out);
        //         BufferedReader output = new BufferedReader(isr);
        //         InputStream err = child.getErrorStream();
        //         InputStreamReader eisr = new InputStreamReader(err);
        //         BufferedReader error = new BufferedReader(eisr);
        //         System.out.println("Waiting for");         
        child.waitFor();
        //         String o = "";
        //         String s;
        //         while ((s = output.readLine()) != null) {
        //            o += s + "\n";
        //         }
        //         System.out.println("stdout: " + o);
        //         String e = "";
        //         s = error.readLine(); // First line is a warning: Warning:
        //         // Permanently added 'XX.XX.XX.XX' (RSA) to
        //         // the list of known hosts.
        //         while ((s = error.readLine()) != null) {
        //            e += s + "\n";
        //         }
        //         System.out.println("stderr: " + e);

        if (child.exitValue() != 0)
            throw new InternalErrorException("Copy process failed.");
        else {
            System.out.println("Returning.");
        }
    } catch (Exception e) {
        throw new DirectoryException("Cannot execute rm command.", e);
    }
}