Example usage for java.lang ProcessBuilder start

List of usage examples for java.lang ProcessBuilder start

Introduction

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

Prototype

public Process start() throws IOException 

Source Link

Document

Starts a new process using the attributes of this process builder.

Usage

From source file:com.hortonworks.registries.storage.tool.shell.ShellMigrationExecutor.java

@Override
public void execute(Connection connection) throws SQLException {
    String scriptLocation = this.shellScriptResource.getLocationOnDisk();
    try {/*from  ww w. j  a va2  s.  c  om*/
        List<String> args = new ArrayList<String>();
        args.add(scriptLocation);
        ProcessBuilder builder = new ProcessBuilder(args);
        builder.redirectErrorStream(true);
        Process process = builder.start();
        Scanner in = new Scanner(process.getInputStream());
        System.out.println(StringUtils.repeat("+", 200));
        while (in.hasNextLine()) {
            System.out.println(in.nextLine());
        }
        int returnCode = process.waitFor();
        System.out.println(StringUtils.repeat("+", 200));
        if (returnCode != 0) {
            throw new FlywayException("script exited with value : " + returnCode);
        }
    } catch (Exception e) {
        LOG.error(e.toString());
        // Only if SQLException or FlywaySqlScriptException is thrown flyway will mark the migration as failed in the metadata table
        throw new SQLException(String.format("Failed to run script \"%s\", %s", scriptLocation, e.getMessage()),
                e);
    }
}

From source file:edu.illinois.cs.cogcomp.CompileMojo.java

public void execute() throws MojoExecutionException {
    dFlag = FileUtils.getPlatformIndependentFilePath(dFlag);
    gspFlag = FileUtils.getPlatformIndependentFilePath(gspFlag);
    sourcepathFlag = FileUtils.getPlatformIndependentFilePath(sourcepathFlag);

    classpath.add(dFlag);//  w  ww . jav a2 s  .  co m
    classpath.add(gspFlag);

    String newpath = StringUtils.join(classpath, File.pathSeparator);

    // If these directories don't exist, make them.
    new File(dFlag).mkdirs();
    new File(gspFlag).mkdirs();

    for (String lbjInputFile : lbjavaInputFileList) {
        if (StringUtils.isEmpty(lbjInputFile)) {
            // making the optional-compile-parameter happy.
            continue;
        }

        getLog().info("Calling Java edu.illinois.cs.cogcomp.lbjava.Main...");

        lbjInputFile = FileUtils.getPlatformIndependentFilePath(lbjInputFile);

        try {
            String[] args = new String[] { "java", "-cp", newpath, "edu.illinois.cs.cogcomp.lbjava.Main", "-d",
                    dFlag, "-gsp", gspFlag, "-sourcepath", sourcepathFlag, lbjInputFile };

            ProcessBuilder pr = new ProcessBuilder(args);
            pr.inheritIO();
            Process p = pr.start();
            p.waitFor();

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Yeah, an error.");
        }
    }

}

From source file:edu.illinois.cs.cogcomp.GenerateMojo.java

public void execute() throws MojoExecutionException {
    dFlag = FileUtils.getPlatformIndependentFilePath(dFlag);
    gspFlag = FileUtils.getPlatformIndependentFilePath(gspFlag);
    sourcepathFlag = FileUtils.getPlatformIndependentFilePath(sourcepathFlag);

    classpath.add(dFlag);//  ww w  . j a va 2s  .c  o  m
    classpath.add(gspFlag);

    String newpath = StringUtils.join(classpath, File.pathSeparator);

    // If these directories don't exist, make them.
    new File(dFlag).mkdirs();
    new File(gspFlag).mkdirs();

    for (String lbjInputFile : lbjavaInputFileList) {
        if (StringUtils.isEmpty(lbjInputFile)) {
            // making the optional-compile-step parameter happy.
            continue;
        }

        getLog().info("Calling Java edu.illinois.cs.cogcomp.lbjava.Main...");

        lbjInputFile = FileUtils.getPlatformIndependentFilePath(lbjInputFile);

        try {
            String[] args = new String[] { "java", "-cp", newpath, "edu.illinois.cs.cogcomp.lbjava.Main", "-c",
                    "-d", dFlag, "-gsp", gspFlag, "-sourcepath", sourcepathFlag, lbjInputFile };

            ProcessBuilder pr = new ProcessBuilder(args);
            pr.inheritIO();
            Process p = pr.start();
            p.waitFor();

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Yeah, an error.");
        }
    }

}

From source file:net.landora.video.playerbackends.GenericPlayerBackend.java

@Override
public void playFile(File file) {
    try {//w w w.  ja  v a  2  s . c o  m
        List<String> args = new ArrayList<String>();
        args.add(ProgramsAddon.getInstance().getConfiguredPath(program));
        args.addAll(Arrays.asList(extraArgs));
        args.add(file.getAbsolutePath());

        ProcessBuilder process = new ProcessBuilder(args);
        process.redirectErrorStream(true);
        Process p = process.start();

        StringWriter buffer = new StringWriter();
        IOUtils.copy(p.getInputStream(), buffer);
        p.waitFor();

    } catch (Exception e) {
        log.error("Error playing file with " + program.getName() + ": " + file, e);
    }
}

From source file:jeplus.RadianceWinTools.java

/**
 * Call DaySim gen_dc to run the simulation
 * @param config Radiance Configuration/*from  ww w. j  ava2  s  .com*/
 * @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:es.ua.dlsi.patch.translation.LocalApertiumTranslator.java

public Set<String> getTranslation(final String input) {

    Set<String> output = new HashSet<>();
    String finalline = "";
    // pull from the map if already there

    try {/*from   w w w . ja v  a  2  s . c  o  m*/
        String[] command = { "apertium", "-u", langCmd };
        ProcessBuilder probuilder = new ProcessBuilder(command);

        Process process = probuilder.start();
        OutputStream stdin = process.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
        writer.write(input);
        writer.newLine();
        writer.flush();
        writer.close();

        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) {
            finalline += line;
        }
        br.close();

    } catch (Exception e) {
        e.printStackTrace(System.err);
        System.exit(-1);
    }
    output.add(finalline);
    return output;
}

From source file:com.github.born2snipe.project.setup.scm.GitRepoInitializer.java

private void executeCommandIn(File projectDir, String... commands) {
    try {/*from www.j ava  2s. c o  m*/
        ProcessBuilder processBuilder = new ProcessBuilder(commands);
        processBuilder.directory(projectDir);
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();
        System.out.println(IOUtils.toString(process.getInputStream()));
        process.waitFor();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:ee.ria.xroad.monitor.executablelister.AbstractExecLister.java

/**
 * Method for testability/*from w  w  w  . j a  v  a  2 s  .  c om*/
 * @return
 * @throws IOException
 * @throws InterruptedException
 */
ProcessOutputs executeProcess() throws IOException, InterruptedException {

    ProcessBuilder b = new ProcessBuilder("/bin/sh", "-c", getCommand());

    Process p = b.start();
    p.waitFor();
    ProcessOutputs outputs = new ProcessOutputs();
    // need to read all of output everytime, reading it partially causes bad problems
    outputs.setOut(CharStreams.toString(new InputStreamReader(p.getInputStream())).replace("'", ""));
    outputs.setErr(CharStreams.toString(new InputStreamReader(p.getErrorStream())));
    return outputs;
}

From source file:mmllabvsdextractfeature.MMllabVSDExtractFeature.java

/**
 * //from   w w w. ja  va2  s .  c  o  m
 * @param tarScriptShFile
 * @param folderForTar
 * @param dirtoSave
 * @return
 * @throws IOException 
 */
Boolean zipFolder(String tarScriptShFile, String folderForZip, String dirtoSave) throws IOException {
    //ProcessBuilder pb = new ProcessBuilder("/home/tiendv/NetBeansProjects/trunk/MMllabVSDExtractFeature/src/mmllabvsdextractfeature/unzip.sh","/home/tiendv/Downloads/tiendv.tar","/home/tiendv");
    Boolean result = false;
    ProcessBuilder pb = new ProcessBuilder(tarScriptShFile, folderForZip, dirtoSave);
    Process process = pb.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line = null;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
    return result;

}

From source file:com.kylinolap.common.util.OSCommandExecutor.java

private void runNativeCommand() throws IOException {
    String[] cmd = new String[3];
    String osName = System.getProperty("os.name");
    if (osName.startsWith("Windows")) {
        cmd[0] = "cmd.exe";
        cmd[1] = "/C";
    } else {/*from www  . j  a  v a  2 s  .  c  o m*/
        cmd[0] = "/bin/bash";
        cmd[1] = "-c";
    }
    cmd[2] = command;

    ProcessBuilder builder = new ProcessBuilder(cmd);
    builder.redirectErrorStream(true);
    Process proc = builder.start();

    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    IOUtils.copy(proc.getInputStream(), buf);
    output = buf.toString("UTF-8");

    try {
        exitCode = proc.waitFor();
    } catch (InterruptedException e) {
        throw new IOException(e);
    }
}