Example usage for java.lang ProcessBuilder redirectErrorStream

List of usage examples for java.lang ProcessBuilder redirectErrorStream

Introduction

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

Prototype

boolean redirectErrorStream

To view the source code for java.lang ProcessBuilder redirectErrorStream.

Click Source Link

Usage

From source file:org.eclipse.php.composer.core.ComposerService.java

public static void downloadComposerPhar(File dest, String phpExec) throws CoreException {
    try {// w  w w.  j a  v a 2s . com
        if (dest.exists()) {
            boolean update = ComposerPreferences.getBoolean(ComposerPreferences.COMPOSER_PHAR_NODE, true);
            if (!update)
                return;

            long expDate = parseExpDate(dest) * 1000;
            if (System.currentTimeMillis() < expDate)
                return;
        }
        if (dest.exists()) {
            dest.delete();
        }

        File composerPhar = new File(dest, ComposerPreferences.COMPOSER_PHAR);
        String script = HttpHelper.executeGetRequest(GETCOMPOSER_ORG, null, null, 200);
        if (script != null) {
            File scriptFile = new File(getTemp(), "composertemp.php"); //$NON-NLS-1$
            if (!scriptFile.exists()) {
                scriptFile.createNewFile();
            }
            FileOutputStream outStream = new FileOutputStream(scriptFile);
            outStream.write(script.getBytes());
            outStream.close();

            String phpIni = PHPINIUtil.findPHPIni(phpExec).getAbsolutePath();
            List<String> command = new ArrayList<String>();
            command.add(phpExec);
            if (phpIni != null) {
                command.add("-c"); //$NON-NLS-1$
                command.add(phpIni);
            }
            command.add(scriptFile.getCanonicalPath());
            command.add("--"); //$NON-NLS-1$
            command.add(INSTALL_DIR + dest.getParentFile().getAbsolutePath());

            ProcessBuilder processBuilder = new ProcessBuilder(command);
            processBuilder.redirectErrorStream(true);
            PHPLaunchUtilities.appendLibrarySearchPathEnv(processBuilder.environment(),
                    new File(phpExec).getParentFile());

            Process p = processBuilder.start();
            String output = IOUtils.toString(p.getInputStream());

            try {
                int result = p.waitFor();
                if (result != 0) {
                    composerPhar.delete();
                    throw new CoreException(new org.eclipse.core.runtime.Status(IStatus.ERROR,
                            ComposerCorePlugin.PLUGIN_ID, NLS.bind(
                                    Messages.ComposerService_Error_Downloading_Composer_Phar, result, output)));
                }
            } catch (InterruptedException e) {
                ComposerCorePlugin.logError(e);
            } finally {
                scriptFile.delete();
            }
        }
    } catch (IOException e) {
        ComposerCorePlugin.logError(e);
    }
}

From source file:com.ibm.jaql.JaqlBaseTestCase.java

/**
 * Compares the tmp file and gold file using unix diff. whitespace is ignored
 * for the diff.//  w  w  w  .j a  v  a2 s .  c o m
 * 
 * 
 * @param tmpFileName tmp file name
 * @param goldFileName gold file name
 * @return <tt>true</tt> if the tmp file and gold file are the same;
 *         <tt>false</tt> otherwise.
 * @throws IOException
 */
public static boolean compareResults(String tmpFileName, String goldFileName) throws IOException {
    // use unix 'diff', ignoring whitespace
    ProcessBuilder pb = new ProcessBuilder("diff", "-w", tmpFileName, goldFileName);
    /*
     * Two input file for diff are the same only if nothing is printed to stdout
     * and stderr. Redirect stderr to stdout so that only stdout needs to
     * checked.
     */
    pb.redirectErrorStream(true);
    Process p = pb.start();
    InputStream str = p.getInputStream();

    byte[] b = new byte[1024];
    int numRead = 0;
    StringBuilder sb = new StringBuilder();
    while ((numRead = str.read(b)) > 0) {
        sb.append(new String(b, 0, numRead, "US-ASCII"));
    }
    if (sb.length() > 0)
        System.err.println("\ndiff -w " + tmpFileName + " " + goldFileName + "\n" + sb);

    return sb.length() == 0;
}

From source file:org.limewire.util.FileUtils.java

/**
 * Moves the given file or directory to Trash.
 * /* w w  w  .  j  av  a 2  s  .c  o m*/
 * @param file The file or directory to move to Trash
 * @throws IOException if the canonical path cannot be resolved
 *          or if the move process is interrupted
 * @return true on success
 */
private static boolean moveToTrashOSX(File file) {
    try {
        String[] command = moveToTrashCommand(file);
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectErrorStream();
        Process process = builder.start();
        ProcessUtils.consumeAllInput(process);
        process.waitFor();
    } catch (InterruptedException err) {
        LOG.error("InterruptedException", err);
    } catch (IOException err) {
        LOG.error("IOException", err);
    }
    return !file.exists();
}

From source file:com.kylinolap.metadata.tool.HiveSourceTableMgmt.java

/**
 * @param hiveCommd/*from  w w w.  java2  s.  c  o m*/
 */
private static String callGenerateCommand(String hiveCommd) throws IOException {
    // Get out put path
    String tempDir = System.getProperty("java.io.tmpdir");
    logger.info("OS current temporary directory is " + tempDir);
    if (StringUtils.isEmpty(tempDir)) {
        tempDir = "/tmp";
    }
    String[] cmd = new String[2];
    String osName = System.getProperty("os.name");
    if (osName.startsWith("Windows")) {
        cmd[0] = "cmd.exe";
        cmd[1] = "/C";
    } else {
        cmd[0] = "/bin/bash";
        cmd[1] = "-c";
    }

    // hive command output
    // String hiveOutputPath = tempDir + File.separator +
    // "tmp_kylin_output";
    String hiveOutputPath = File.createTempFile("HiveOutput", null).getAbsolutePath();
    // Metadata output
    File dir = File.createTempFile("meta", null);
    dir.delete();
    dir.mkdir();
    String tableMetaOutcomeDir = dir.getAbsolutePath();

    ProcessBuilder pb = null;

    if (osName.startsWith("Windows")) {
        pb = new ProcessBuilder(cmd[0], cmd[1],
                "ssh root@sandbox 'hive -e \"" + hiveCommd + "\"' > " + hiveOutputPath);
    } else {
        pb = new ProcessBuilder(cmd[0], cmd[1], "hive -e \"" + hiveCommd + "\" > " + hiveOutputPath);
    }

    // Run hive
    pb.directory(new File(tempDir));
    pb.redirectErrorStream(true);
    Process p = pb.start();
    InputStream is = p.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = null;

    try {
        br = new BufferedReader(isr);
        String line = null;
        logger.info("Execute : " + pb.command().get(0));
        while ((line = br.readLine()) != null) {
            logger.info(line);
        }
    } finally {
        if (null != br) {
            br.close();
        }
    }
    logger.info("Hive execution completed!");

    HiveSourceTableMgmt rssMgmt = new HiveSourceTableMgmt();
    rssMgmt.extractTableDescFromFile(hiveOutputPath, tableMetaOutcomeDir);
    return tableMetaOutcomeDir;
}

From source file:wordnice.utils.JavaUtils.java

protected static void executeBlock(CommandData out, String... args) throws IOException, InterruptedException {
    if (out.getTimeout() > 0) {
        executeSpecial(out, args);//from  w  w w . ja v  a 2s  . co m
        return;
    }
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.redirectErrorStream(out.isRedirectError());
    Process proc = pb.start();
    try (InputStream in = proc.getInputStream(); InputStream err = proc.getErrorStream()) {
        out.writeOutput(in);
        out.writeError(err);
        proc.waitFor();
        out.setExitStatus(proc.exitValue());
        if (out.getOnFinish() != null)
            out.getOnFinish().accept(out);
    }
}

From source file:jeplus.RadianceWinTools.java

/**
 * Call DaySim gen_dc to run the simulation
 * @param config Radiance Configuration//  w w  w. j  a  v  a2 s  .c  o  m
 * @param WorkDir The working directory where the input files are stored and the output files to be generated
 * @param model
 * @param in
 * @param out
 * @param err
 * @param process
 * @return the result code represents the state of execution steps. >=0 means successful
 */
public static int runGen_DC(RadianceConfig config, String WorkDir, String model, String in, String out,
        String err, ProcessWrapper process) {

    int ExitValue = -99;

    // Manipulate header file
    HashMap<String, String> props = new HashMap<>();
    // props.put("project_name", "");
    props.put("project_directory", "./");
    props.put("bin_directory", config.getResolvedDaySimBinDir());
    props.put("tmp_directory", "./");
    props.put("Template_File", config.getResolvedDaySimBinDir() + "../template/");
    props.put("sensor_file", in);
    try {
        FileUtils.moveFile(new File(WorkDir + File.separator + model),
                new File(WorkDir + File.separator + model + ".ori"));
    } catch (IOException ex) {
        logger.error("Error renaming header file to " + WorkDir + File.separator + model + ".ori", ex);
    }
    DaySimModel.updateHeaderFile(WorkDir + File.separator + model + ".ori", WorkDir + File.separator + model,
            props);

    // Run command
    try {
        StringBuilder buf = new StringBuilder(config.getResolvedDaySimBinDir());
        buf.append(File.separator).append("gen_dc");

        List<String> command = new ArrayList<>();
        command.add(buf.toString());
        command.add(model);
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(new File(WorkDir));
        builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedDaySimLibDir());
        builder.redirectOutput(new File(WorkDir + File.separator + out));
        if (err == null || out.equals(err)) {
            builder.redirectErrorStream(true);
        } else {
            builder.redirectError(new File(WorkDir + File.separator + err));
        }
        if (in != null) {
            builder.redirectInput(new File(WorkDir + File.separator + in));
        }
        Process proc = builder.start();
        if (process != null) {
            process.setWrappedProc(proc);
        }
        ExitValue = proc.waitFor();
    } catch (IOException | InterruptedException ex) {
        logger.error("Error occoured when executing DaySim gen_dc", ex);
    }

    // Return Radiance exit value
    return ExitValue;
}

From source file:org.apache.cassandra.utils.CLibrary.java

public static void createHardLinkWithExec(File sourceFile, File destinationFile) throws IOException {
    String osname = System.getProperty("os.name");
    ProcessBuilder pb;
    if (osname.startsWith("Windows")) {
        float osversion = Float.parseFloat(System.getProperty("os.version"));
        if (osversion >= 6.0f) {
            pb = new ProcessBuilder("cmd", "/c", "mklink", "/H", destinationFile.getAbsolutePath(),
                    sourceFile.getAbsolutePath());
        } else {//from   www.  ja v  a  2  s  .  co m
            pb = new ProcessBuilder("fsutil", "hardlink", "create", destinationFile.getAbsolutePath(),
                    sourceFile.getAbsolutePath());
        }
    } else {
        pb = new ProcessBuilder("ln", sourceFile.getAbsolutePath(), destinationFile.getAbsolutePath());
        pb.redirectErrorStream(true);
    }
    try {
        exec(pb);
    } catch (IOException ex) {
        logger.error("Unable to create hard link", ex);
        throw ex;
    }
}

From source file:org.exist.launcher.Launcher.java

protected static void run(List<String> args, BiConsumer<Integer, String> consumer) {
    final ProcessBuilder pb = new ProcessBuilder(args);
    final Optional<Path> home = ConfigurationHelper.getExistHome();
    if (home.isPresent()) {
        pb.directory(home.get().toFile());
    }/*from  www  . j  a  va 2  s.co m*/
    pb.redirectErrorStream(true);
    try {
        final Process process = pb.start();
        if (consumer != null) {
            final StringBuilder output = new StringBuilder();
            try (final BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), "UTF-8"))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    output.append('\n').append(line);
                }
            }
            final int exitValue = process.waitFor();
            consumer.accept(exitValue, output.toString());
        }
    } catch (IOException | InterruptedException e) {
        JOptionPane.showMessageDialog(null, e.getMessage(), "Error Running Process", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:edu.stanford.epad.epadws.dcm4chee.Dcm4CheeOperations.java

/**
 * TODO This does not work. The ./dcmdeleteSeries script invoked the dcm4chee twiddle command but it appears that the
 * moveSeriesToTrash operation it calls has no effect in this version of dcm4chee. See:
 * http://www.dcm4che.org/jira/browse/WEB-955
 *//*w  w  w  .  java2  s.com*/
public static boolean deleteSeries(String seriesUID, String seriesPk) {
    InputStream is = null;
    InputStreamReader isr = null;
    BufferedReader br = null;
    boolean success = false;

    try {
        log.info("Deleting series " + seriesUID + " seriesPK:" + seriesPk);

        String[] command = { "./dcmdeleteSeries", seriesPk, EPADConfig.xnatUploadProjectPassword };
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        String dicomScriptsDir = EPADConfig.getEPADWebServerDICOMScriptsDir() + "bin/";
        File script = new File(dicomScriptsDir, "dcmdeleteSeries");
        if (!script.exists())
            dicomScriptsDir = EPADConfig.getEPADWebServerMyScriptsDir();
        script = new File(dicomScriptsDir, "dcmdeleteSeries");
        // Java 6 - Runtime.getRuntime().exec("chmod u+x "+script.getAbsolutePath());
        script.setExecutable(true);
        processBuilder.directory(new File(dicomScriptsDir));
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();
        process.getOutputStream();
        is = process.getInputStream();
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);

        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
            log.info("./dcmdeleteSeries: " + line);
        }
        try {
            int exitValue = process.waitFor();
            if (exitValue == 0) {
                log.info("Deleted DICOM series " + seriesUID + " pk:" + seriesPk);
                success = true;
            } else {
                log.warning("Failed to delete DICOM series " + seriesUID + " pk=" + seriesPk + "; exitValue="
                        + exitValue + "\n" + sb.toString());
            }
        } catch (Exception e) {
            log.warning("Failed to delete DICOM series " + seriesUID, e);
        }

        String cmdLineOutput = sb.toString();

        if (cmdLineOutput.toLowerCase().contains("error")) {
            throw new IllegalStateException("Failed for: " + parseError(cmdLineOutput));
        }
    } catch (IOException e) {
        log.warning("Failed to delete DICOM series " + seriesUID, e);
    } finally {
        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(is);
    }
    return success;
}

From source file:org.gradle.process.internal.worker.DefaultJavaExecutableVersionProber.java

private List<String> execJavaVersion(JavaExecSpec execSpec) {
    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.redirectErrorStream(true);
    processBuilder.command(execSpec.getExecutable(), "-version");
    try {//from   ww w.j  a  v  a 2s  .  c o m
        Process process = processBuilder.start();
        return IOUtils.readLines(process.getInputStream());
    } catch (IOException e) {
        // ignore
    }
    return Collections.emptyList();
}