Example usage for java.lang ProcessBuilder directory

List of usage examples for java.lang ProcessBuilder directory

Introduction

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

Prototype

File directory

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

Click Source Link

Usage

From source file:edu.northwestern.bioinformatics.studycalendar.utility.osgimosis.BidirectionalObjectStoreTest.java

private Process performMemoryTest(String refType) throws IOException, InterruptedException {
    ProcessBuilder builder = new ProcessBuilder("java", "-Xmx16M", "-cp", "target/classes:target/test/classes",
            MemTest.class.getName(), refType);
    builder.redirectErrorStream(true);/*from   w  ww  . ja v  a  2  s  . c o  m*/
    builder.directory(detectBaseDirectory());
    Process p = builder.start();
    p.waitFor();
    IOUtils.copy(p.getInputStream(), System.out);
    return p;
}

From source file:com.github.mojos.distribute.PackageMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {

    if (version != null) {
        packageVersion = version;//from  ww w . j  a va 2  s  .  c o  m
    }

    //Copy sourceDirectory
    final File sourceDirectoryFile = new File(sourceDirectory);
    final File buildDirectory = Paths.get(project.getBuild().getDirectory(), "py").toFile();

    try {
        FileUtils.copyDirectory(sourceDirectoryFile, buildDirectory);
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to copy source", e);
    }

    final File setup = Paths.get(buildDirectory.getPath(), "setup.py").toFile();
    final boolean setupProvided = setup.exists();

    final File setupTemplate = setupProvided ? setup
            : Paths.get(buildDirectory.getPath(), "setup-template.py").toFile();

    try {
        if (!setupProvided) {
            //update VERSION to latest version
            List<String> lines = new ArrayList<String>();
            final InputStream inputStream = new BufferedInputStream(new FileInputStream(setupTemplate));
            try {
                lines.addAll(IOUtils.readLines(inputStream));
            } finally {
                inputStream.close();
            }

            int index = 0;
            for (String line : lines) {
                line = line.replace(VERSION, packageVersion);
                line = line.replace(PROJECT_NAME, packageName);
                lines.set(index, line);
                index++;
            }

            final OutputStream outputStream = new FileOutputStream(setup);
            try {
                IOUtils.writeLines(lines, "\n", outputStream);
            } finally {
                outputStream.flush();
                outputStream.close();
            }
        }

        //execute setup script
        ProcessBuilder processBuilder = new ProcessBuilder(pythonExecutable, setup.getCanonicalPath(),
                "bdist_egg");
        processBuilder.directory(buildDirectory);
        processBuilder.redirectErrorStream(true);

        Process pr = processBuilder.start();
        int exitCode = pr.waitFor();
        BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        String line = "";
        while ((line = buf.readLine()) != null) {
            getLog().info(line);
        }

        if (exitCode != 0) {
            throw new MojoExecutionException("python setup.py returned error code " + exitCode);
        }

    } catch (FileNotFoundException e) {
        throw new MojoExecutionException("Unable to find " + setup.getPath(), e);
    } catch (IOException e) {
        throw new MojoExecutionException("Unable to read " + setup.getPath(), e);
    } catch (InterruptedException e) {
        throw new MojoExecutionException("Unable to execute python " + setup.getPath(), e);
    }

}

From source file:org.sonar.api.utils.command.CommandExecutor.java

/**
 * @throws org.sonar.api.utils.command.TimeoutException on timeout, since 4.4
 * @throws CommandException on any other error
 * @param timeoutMilliseconds any negative value means no timeout.
 * @since 3.0/*  ww w.  j ava  2s .co m*/
 */
public int execute(Command command, StreamConsumer stdOut, StreamConsumer stdErr, long timeoutMilliseconds) {
    ExecutorService executorService = null;
    Process process = null;
    StreamGobbler outputGobbler = null;
    StreamGobbler errorGobbler = null;
    try {
        ProcessBuilder builder = new ProcessBuilder(command.toStrings(false));
        if (command.getDirectory() != null) {
            builder.directory(command.getDirectory());
        }
        builder.environment().putAll(command.getEnvironmentVariables());
        process = builder.start();

        outputGobbler = new StreamGobbler(process.getInputStream(), stdOut);
        errorGobbler = new StreamGobbler(process.getErrorStream(), stdErr);
        outputGobbler.start();
        errorGobbler.start();

        executorService = Executors.newSingleThreadExecutor();
        Future<Integer> ft = executorService.submit((Callable<Integer>) process::waitFor);
        int exitCode;
        if (timeoutMilliseconds < 0) {
            exitCode = ft.get();
        } else {
            exitCode = ft.get(timeoutMilliseconds, TimeUnit.MILLISECONDS);
        }
        waitUntilFinish(outputGobbler);
        waitUntilFinish(errorGobbler);
        verifyGobbler(command, outputGobbler, "stdOut");
        verifyGobbler(command, errorGobbler, "stdErr");
        return exitCode;

    } catch (java.util.concurrent.TimeoutException te) {
        throw new TimeoutException(command, "Timeout exceeded: " + timeoutMilliseconds + " ms", te);

    } catch (CommandException e) {
        throw e;

    } catch (Exception e) {
        throw new CommandException(command, e);

    } finally {
        if (process != null) {
            process.destroy();
        }
        waitUntilFinish(outputGobbler);
        waitUntilFinish(errorGobbler);
        closeStreams(process);

        if (executorService != null) {
            executorService.shutdown();
        }
    }
}

From source file:drm.taskworker.workers.OptimusWorker.java

private TaskResult start(File workdir, Task task) throws IOException, ParameterFoundException {
    String obj = (String) task.getParam(PRM_START_FILE);
    // FIXME only works with the adapted taskworker-client script (not committed)
    byte[] file = Base64.decodeBase64(obj);

    String method = (String) task.getParam(PRM_START_METHOD);

    File f = new File(workdir, "input.zip");
    OutputStream out = new FileOutputStream(f);
    out.write(file);/*  w  ww  .ja  v a2 s .  c  o m*/
    out.close();

    ProcessBuilder pb = new ProcessBuilder("python", task.getJobOption("optimus.exe"), "input.zip", method);
    pb.directory(workdir);

    Process handle = pb.start();

    (new VoidStreamPump(handle.getInputStream())).start();
    (new VoidStreamPump(handle.getErrorStream())).start();

    handles.put(task.getJobId(), handle);

    // start looking for flag file
    File goFile = new File(workdir, task.getJobOption("optimus.flagfile.go"));
    while (!goFile.exists()) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new Error("should not occur", e);
        }
    }
    goFile.delete();
    return split(workdir, task);
}

From source file:org.craftercms.cstudio.publishing.processor.ShellProcessor.java

@Override
public void doProcess(PublishedChangeSet changeSet, Map<String, String> parameters, PublishingTarget target)
        throws PublishingException {
    checkConfiguration(parameters, target);
    LOGGER.debug("Starting Shell Processor");
    ProcessBuilder builder = new ProcessBuilder();
    builder.directory(getWorkingDir(workingDir, parameters.get(FileUploadServlet.PARAM_SITE)));
    LOGGER.debug("Working directory is " + workingDir);
    HashMap<String, String> argumentsMap = buildArgumentsMap(getFileList(parameters, changeSet));
    if (asSingleCommand) {
        StrSubstitutor substitutor = new StrSubstitutor(argumentsMap, "%{", "}");
        String execComand = substitutor.replace(command);
        LOGGER.debug("Command to be Executed is " + execComand);
        builder.command("/bin/bash", "-c", execComand);

    } else {//from   w w w.ja v  a  2  s.com
        Set<String> keys = argumentsMap.keySet();
        ArrayList<String> commandAsList = new ArrayList<String>();
        commandAsList.add(command.trim());
        for (String key : keys) {
            if (!key.equalsIgnoreCase(INCLUDE_FILTER_PARAM)) {
                commandAsList.add(argumentsMap.get(key));
            }
        }
        LOGGER.debug("Command to be Executed is " + StringUtils.join(commandAsList, " "));
        builder.command(commandAsList);
    }

    builder.environment().putAll(enviroment);
    builder.redirectErrorStream(true);
    try {
        Process process = builder.start();
        process.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String str;
        while ((str = reader.readLine()) != null) {
            LOGGER.info("PROCESS OUTPUT :" + str);
        }
        reader.close();
        LOGGER.info("Process Finish with Exit Code " + process.exitValue());
        LOGGER.debug("Process Output ");
    } catch (IOException ex) {
        LOGGER.error("Error ", ex);
    } catch (InterruptedException e) {
        LOGGER.error("Error ", e);
    } finally {
        LOGGER.debug("End of Shell Processor");
    }
}

From source file:com.photon.phresco.framework.impl.ProjectRuntimeManagerImpl.java

private BufferedReader executeJenkinsProcess(List<String> commands) throws PhrescoException {
    ProcessBuilder processBuilder = new ProcessBuilder(commands);
    processBuilder.directory(new File("C:\\download\\workspace\\tools\\jenkins"));
    try {/*from  w ww .j  a  v a2  s.  c  om*/
        Process process = processBuilder.start();
        return new BufferedReader(new InputStreamReader(process.getInputStream()));
    } catch (IOException e) {
        throw new PhrescoException(e);
    }
}

From source file:plugins.GerritTriggerTest.java

private Process logProcessBuilderIssues(ProcessBuilder pb, String commandName)
        throws InterruptedException, IOException {
    String dir = "";
    if (pb.directory() != null) {
        dir = pb.directory().getAbsolutePath();
    }/*w  ww .  j a  v  a  2 s .com*/
    LOGGER.info("Running : " + pb.command() + " => directory: " + dir);
    Process processToRun = pb.start();
    int result = processToRun.waitFor();
    if (result != 0) {
        StringWriter writer = new StringWriter();
        IOUtils.copy(processToRun.getErrorStream(), writer);
        LOGGER.severe("Issue occurred during command \"" + commandName + "\":\n" + writer.toString());
        writer.close();
    }
    return processToRun;
}

From source file:com.netflix.dynomitemanager.defaultimpl.FloridaProcessManager.java

public void start() throws IOException {
    logger.info(String.format("Starting dynomite server"));

    List<String> command = Lists.newArrayList();
    if (!"root".equals(System.getProperty("user.name"))) {
        command.add(SUDO_STRING);/* w w  w.j  ava2s .com*/
        command.add("-n");
        command.add("-E");
    }
    command.addAll(getStartCommand());

    ProcessBuilder startDynomite = new ProcessBuilder(command);
    Map<String, String> env = startDynomite.environment();
    setEnv(env);

    startDynomite.directory(new File("/"));
    startDynomite.redirectErrorStream(true);
    Process starter = startDynomite.start();

    try {
        sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS);
        int code = starter.exitValue();
        if (code == 0) {
            logger.info("Dynomite server has been started");
            instanceState.setStorageProxyAlive(true);
        } else {
            logger.error("Unable to start Dynomite server. Error code: {}", code);
        }

        logProcessOutput(starter);
    } catch (Exception e) {
        logger.warn("Starting Dynomite has an error", e);
    }
}

From source file:functionaltests.scilab.AbstractScilabTest.java

protected ProcessBuilder initCommand(String testName, int nb_iter) throws Exception {
    ProcessBuilder pb = new ProcessBuilder();
    pb.directory(sci_tb_home);
    pb.redirectErrorStream(true);/*from w  ww.  jav a 2 s .  com*/
    int runAsMe = 0;

    if (System.getProperty("proactive.test.runAsMe") != null) {
        runAsMe = 1;
    }
    if (System.getProperty("scilab.test.leaks") != null) {
        testLeak = 1;
        leakFile = new File(test_home + fs + "JIMS.log");
        if (leakFile.exists()) {
            leakFile.delete();
        }
    }
    if (System.getProperty("scilab.bin.path") != null) {
        pb.command(System.getProperty("scilab.bin.path"), "-nw", "-f",
                (new File(test_home + fs + "RunUnitTest.sci")).getCanonicalPath(), "-args", schedURI.toString(),
                credFile.toString(), "" + nb_iter, testName, "" + runAsMe, "" + testLeak, "" + leakFile);
    } else {
        pb.command("scilab", "-nw", "-f", (new File(test_home + fs + "RunUnitTest.sci")).getCanonicalPath(),
                "-args", schedURI.toString(), credFile.toString(), "" + nb_iter, testName, "" + runAsMe,
                "" + testLeak, "" + leakFile);
    }
    return pb;
}

From source file:output.TikzTex.java

/**
 * Use PDF-Latex to parse the .tex file/*from  w ww  .j ava 2s . c  om*/
 * @param file the source File containing the Data
 * @throws IOException
 */
public void genPdf(File file) throws IOException {
    ProcessBuilder pb = new ProcessBuilder("pdflatex", "-shell-escape", file.getAbsolutePath());
    File directory = new File(outputDir);
    pb.directory(directory);

    Process p;
    try {
        p = pb.start();
        // We need to parse the Error and the Output generated by pdflatex
        StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), "ERROR");
        StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream(), "OUTPUT");
        errorGobbler.start();
        outputGobbler.start();
        // Wait until its done
        int exitVal = p.waitFor();

        // Spawn a Frame with the Image
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        String imgPath = file.getAbsolutePath().substring(0, file.getAbsolutePath().length() - 4) + ".png";
        ImageIcon icon = new ImageIcon(imgPath);
        // resize
        Image img = icon.getImage();
        double ratio = (double) icon.getIconWidth() / icon.getIconHeight();
        Image newimg = img.getScaledInstance((int) (Math.round(600 * ratio)), 600, java.awt.Image.SCALE_SMOOTH);
        icon = new ImageIcon(newimg);
        JLabel imgLabel = new JLabel(icon);
        JScrollPane scrollPanel = new JScrollPane(imgLabel);

        frame.getContentPane().add(scrollPanel);
        frame.setSize(1280, 720);
        frame.setVisible(true);
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
}