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:eu.abc4trust.cryptoEngine.uprove.util.UProveLauncher.java

public void start(int port, String name) {
    this.startCalled = true;
    // System.out.println("UProveLauncher.start - instance : " + this +
    // " - port : " + launchName + " :" + launchPort + " - is stopped == " +
    // stopped + " - uproveProcess " + this.uproveProcess );
    ProcessBuilder processBuilder;
    if (this.isWindows()) {
        processBuilder = new ProcessBuilder(this.WINDOWS_COMMAND);
    } else {/*from   w  w w .j  a  va 2  s  .c  o m*/
        processBuilder = new ProcessBuilder(this.NON_WINDOWS_COMMAND);
    }
    processBuilder.command().add("" + port);
    //Map<String, String> env = processBuilder.environment();
    //env.clear();

    processBuilder.directory(this.workingDirectory);
    try {
        this.uproveProcess = processBuilder.start();
        // System.out.println(this.uproveProcess.exitValue());
        InputStream is = this.uproveProcess.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        String terminationString = "Press Enter to exit";
        boolean done = false;
        while (!done) {
            line = br.readLine();
            if (line != null) {
                System.out.println(line);
                done = line.endsWith(terminationString);
            } else {
                System.out.println("UProveLauncher - we get null on stdout from process - process has died..");
                break;
            }
        }
        this.debugOutputCollector = new DebugOutputCollector(this.uproveProcess, name);
        this.debugOutput = new Thread(this.debugOutputCollector, "DebugCollector");
        if (done)
            this.debugOutput.start();
        // System.out.println("process started");
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.symbian.driver.plugins.romflash.Activator.java

public boolean FlashRom(String romLocation) {

    try {/*from w  w w.  j a v  a  2s .  co  m*/
        File rom = new File(romLocation);
        if (method.compareToIgnoreCase("serial") == 0) {
            if (!(switchOff() && switchOn())) {
                LOGGER.log(Level.SEVERE, "Could not reboot device, so No rom flashing.");
                return false;
            }
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish.");
            }
            File trgtTestFile = JarUtils.extractResource(Activator.class, "/resource/trgtest.exe");
            if (trgtTestFile.isFile()) {
                ProcessBuilder ld = new ProcessBuilder(trgtTestFile.getAbsolutePath(), portNumber,
                        rom.getCanonicalPath());
                ld.directory(trgtTestFile.getParentFile());
                Process pp = ld.start();
                LOGGER.log(Level.INFO, "started trgtest process");
                BufferedReader br = new BufferedReader(new InputStreamReader(pp.getInputStream()));
                StringBuffer sb = new StringBuffer();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line).append("\n");
                    LOGGER.log(Level.INFO, line);
                }
                //String answer = sb.toString();

                try {
                    LOGGER.log(Level.INFO, "going to wait now for trgtest to finish");
                    pp.waitFor();
                } catch (InterruptedException e) {
                    LOGGER.log(Level.SEVERE, "Failed to wait for trgtest.exe to finish.");
                }
                LOGGER.log(Level.INFO, "trgtest returned: " + pp.exitValue());
                pp.destroy();

            } else {
                LOGGER.log(Level.SEVERE, "Could not find trgtest.exe file.");
            }
        } else // usb rom loading
        {
            // switch the device off...
            switchOff();
            List<File> lis1 = Arrays.asList(File.listRoots());
            // get reboot plugin, and reboot the device
            switchOn(); // or just switch on as things may be
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish.");
            }
            File[] listRoots2 = File.listRoots();
            // find the drive that made the difference!!
            File diff = null;
            for (File root : listRoots2) {
                if (!lis1.contains(root)) // found new drive
                {
                    diff = root;
                    break;
                }
            }
            File romfl = new File(diff, rom.getName());
            romfl.delete();
            File aCopyFrom = new File(rom.getCanonicalPath());
            FileChannel lSrcChannel = new FileInputStream(aCopyFrom).getChannel();
            FileChannel lDstChannel = new FileOutputStream(romfl).getChannel();
            lDstChannel.transferFrom(lSrcChannel, 0, lSrcChannel.size());
            lSrcChannel.close();
            lDstChannel.close();

            File syncFile = JarUtils.extractResource(Activator.class, "/resource/sync.exe");
            if (syncFile.isFile()) {

                ProcessBuilder ld = new ProcessBuilder(syncFile.getAbsolutePath(), "-r", "-e", diff.toString());

                ld.directory(syncFile.getParentFile());
                ld.start();
                // wait 10 seconds for the rom to load ...
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish.");
                }
            } else {
                LOGGER.log(Level.SEVERE, "Could not find sync.exe file.");
            }
        }
    } catch (IOException lIOException) {
        LOGGER.log(Level.SEVERE, "Could not flash ROM " + lIOException.getMessage());
        return false;
    }
    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
        LOGGER.log(Level.SEVERE, "Failed to wait for sync.exe to finish.");
    }
    return true;
}

From source file:org.lilyproject.clientmetrics.postproc.MetricsReportTool.java

private void executePlot(GroupName groupName, File outputDir) throws IOException, InterruptedException {
    System.out.println("Calling gnuplot for " + groupName);
    ProcessBuilder pb = new ProcessBuilder("gnuplot", groupName.fileName + ".plot.txt");
    pb.directory(outputDir);
    Process p = pb.start();//from  w w  w  . j  a  va  2s.co m
    int exitValue = p.waitFor();
    if (exitValue != 0) {
        System.err.println("Warning: gnuplot returned exit code: " + exitValue);
    }
}

From source file:de.teamgrit.grit.checking.compile.HaskellCompileChecker.java

/**
 * checkProgram invokes the Haskell compiler on a given file and reports
 * the output./*from   w w  w . j  a  va2  s. c  om*/
 * 
 * @param pathToProgramFile
 *            Specifies the file or folder containing that should be
 *            compiled. (accepts .lhs and .hs files)
 * @param compilerName
 *            The compiler to be used (usually ghc).
 * @param compilerFlags
 *            Additional flags to be passed to the compiler.
 * @throws FileNotFoundException
 *             Is thrown when the file in pathToProgramFile cannot be
 *             opened
 * @throws BadCompilerSpecifiedException
 *             Is thrown when the given compiler cannot be called
 * @return A {@link CompilerOutput} that contains all compiler messages and
 *         flags on how the compile run went.
 * @throws BadFlagException
 *             When ghc doesn't recognize a flag, this exception is thrown.
 */
@Override
public CompilerOutput checkProgram(Path pathToProgramFile, String compilerName, List<String> compilerFlags)
        throws FileNotFoundException, BadCompilerSpecifiedException, BadFlagException {

    Process compilerProcess = null;

    try {
        // create compiler invocation.
        List<String> compilerInvocation = createCompilerInvocation(pathToProgramFile, compilerName,
                compilerFlags);

        ProcessBuilder compilerProcessBuilder = new ProcessBuilder(compilerInvocation);

        // make sure the compiler stays in its directory.
        compilerProcessBuilder.directory(pathToProgramFile.getParent().toFile());

        compilerProcess = compilerProcessBuilder.start();
        // this will never happen because createCompilerInvocation never
        // throws this Exception. Throw declaration needs to be in method
        // declaration because of the implemented Interface although we
        // never use it in the HaskellCompileChecker
    } catch (CompilerOutputFolderExistsException e) {
        LOGGER.severe("A problem while compiling, which never should happen, occured" + e.getMessage());
    } catch (BadCompilerSpecifiedException e) {
        throw new BadCompilerSpecifiedException(e.getMessage());
    } catch (IOException e) {

        // If we cannot call the compiler we return a CompilerOutput
        // initialized with false, false, indicating
        // that the compiler wasn't invoked properly and that there was no
        // clean Compile.
        CompilerOutput compilerInvokeError = new CompilerOutput();
        compilerInvokeError.setClean(false);
        compilerInvokeError.setCompilerInvoked(false);
        return compilerInvokeError;
    }

    // Now we read compiler output. If everything is ok ghc reports
    // nothing in the errorStream.
    InputStream compilerOutputStream = compilerProcess.getErrorStream();
    InputStreamReader compilerStreamReader = new InputStreamReader(compilerOutputStream);
    BufferedReader compilerOutputBuffer = new BufferedReader(compilerStreamReader);
    String line;

    CompilerOutput compilerOutput = new CompilerOutput();
    compilerOutput.setCompilerInvoked(true);

    List<String> compilerOutputLines = new LinkedList<>();

    try {
        while ((line = compilerOutputBuffer.readLine()) != null) {
            compilerOutputLines.add(line);
        }
        // Errors are separated via an empty line (""). But after the
        // the last error the OutputBuffer has nothing more to write.
        // In order to recognize the last error we insert an empty String
        // at the end of the list.
        // Only needs to be done when there are errors.
        if (compilerOutputLines.size() != 0) {
            line = "";
            compilerOutputLines.add(line);
        }

        compilerOutputStream.close();
        compilerStreamReader.close();
        compilerOutputBuffer.close();
        compilerProcess.destroy();

    } catch (IOException e) {

        // Reading might go wrong here if ghc should unexpectedly die
        LOGGER.severe("Error while reading from compiler stream.");
        compilerOutput.setClean(false);
        compilerOutput.setCompileStreamBroken(true);
        return compilerOutput;
    }

    // ghc -c generates a .o(object) and a .hi(haskell interface) file.
    // But we don't need those files so they can be deleted.
    // The generated files have the same name like our input file so we
    // can just exchange the file endings in order to get the
    // correct file paths for deletion
    if (Files.isDirectory(pathToProgramFile, LinkOption.NOFOLLOW_LINKS)) {

        // we use a file walker in order to find all files in the folder
        // and its subfolders
        RegexDirectoryWalker dirWalker = new RegexDirectoryWalker(".+\\.([Ll])?[Hh][Ss]");
        try {
            Files.walkFileTree(pathToProgramFile, dirWalker);
        } catch (IOException e) {
            LOGGER.severe("Could not walk submission " + pathToProgramFile.toString()
                    + " while building copiler invocation: " + e.getMessage());
        }

        for (Path candidatePath : dirWalker.getFoundFiles()) {
            File candidateFile = candidatePath.toFile();
            if (!candidateFile.isDirectory()) {
                String extension = FilenameUtils.getExtension(candidateFile.toString());
                if (extension.matches("[Ll]?[Hh][Ss]")) {
                    File ghcGeneratedObject = new File(
                            FilenameUtils.removeExtension(candidateFile.toString()) + ".o");
                    File ghcGeneratedInterface = new File(
                            FilenameUtils.removeExtension(candidateFile.toString()) + ".hi");
                    ghcGeneratedObject.delete();
                    ghcGeneratedInterface.delete();
                }
            }
        }
    } else {
        String extension = FilenameUtils.getExtension(pathToProgramFile.toString());
        if (extension.matches("[Ll]?[Hh][Ss]")) {
            File ghcGeneratedObject = new File(
                    FilenameUtils.removeExtension(pathToProgramFile.toString()) + ".o");
            File ghcGeneratedInterface = new File(
                    FilenameUtils.removeExtension(pathToProgramFile.toString()) + ".hi");
            ghcGeneratedObject.delete();
            ghcGeneratedInterface.delete();
        }

    }

    // if there are no errors there is no Output to handle
    if (compilerOutputLines.size() != 0) {
        compilerOutput = splitCompilerOutput(compilerOutputLines, compilerOutput);
    } else {
        compilerOutput.setClean(true);
    }
    return compilerOutput;
}

From source file:org.apache.taverna.commandline.TavernaCommandLineTest.java

private synchronized void runWorkflow(String command, String workflow, File outputsDirectory,
        boolean inputValues, boolean secure, boolean database) throws Exception {
    ProcessBuilder processBuilder = new ProcessBuilder("sh", command);
    processBuilder.redirectErrorStream(true);
    processBuilder.directory(buildDirectory);
    List<String> args = processBuilder.command();
    for (File input : inputs) {
        if (inputValues) {
            args.add("-inputvalue");
            args.add(input.getName());/*from w w w  .j  a va  2  s  .  c  om*/
            args.add(IOUtils.toString(new FileReader(input)));
        } else {
            args.add("-inputfile");
            args.add(input.getName());
            args.add(input.getAbsolutePath());
        }
    }
    args.add("-outputdir");
    args.add(outputsDirectory.getPath());
    if (secure) {
        args.add("-cmdir");
        args.add(getClass().getResource("/security").getFile());
        args.add("-cmpassword");
    }
    if (database) {
        args.add("-embedded");
    }
    args.add(workflow);
    Process process = processBuilder.start();
    if (secure) {
        PrintStream outputStream = new PrintStream(process.getOutputStream());
        outputStream.println("test");
        outputStream.flush();
    }
    waitFor(process);
}

From source file:org.cloudata.core.common.ShellCommand.java

/** Run a command */
private void runCommand() throws IOException {
    if (onlyUnix() && WINDOWS) {
        return;//from   w  w  w .  j  av  a  2 s. c o  m
    }
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    boolean completed = false;

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }
    if (dir != null) {
        builder.directory(this.dir);
    }

    process = builder.start();
    final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        try {
            // make sure that the error thread exits
            errThread.join();
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while reading the error stream", ie);
        }
        completed = true;
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        // close the input stream
        try {
            inReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed) {
            errThread.interrupt();
        }
        try {
            errReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = System.currentTimeMillis();
    }
}

From source file:com.azurenight.maven.TroposphereMojo.java

public void runJythonScriptOnInstall(File outputDirectory, List<String> args, File outputFile)
        throws MojoExecutionException {
    getLog().info("running " + args + " in " + outputDirectory);
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.directory(outputDirectory);
    pb.environment().put("BASEDIR", project.getBasedir().getAbsolutePath());
    final Process p;
    ByteArrayOutputStream stdoutBaos = null;
    ByteArrayOutputStream stderrBaos = null;
    try {/*from   www .ja  v a2s  .  c om*/
        p = pb.start();
    } catch (IOException e) {
        throw new MojoExecutionException("Executing jython failed. tried to run: " + pb.command(), e);
    }
    if (outputFile == null) {
        stdoutBaos = new ByteArrayOutputStream();
        copyIO(p.getInputStream(), stdoutBaos);
    } else {
        try {
            copyIO(p.getInputStream(), new FileOutputStream(outputFile));
        } catch (FileNotFoundException e) {
            throw new MojoExecutionException("Failed to copy output to : " + outputFile.getAbsolutePath(), e);
        }
    }
    stderrBaos = new ByteArrayOutputStream();
    copyIO(p.getErrorStream(), stderrBaos);
    copyIO(System.in, p.getOutputStream());
    try {
        boolean error = false;
        if (p.waitFor() != 0) {
            error = true;
        }
        if (getLog().isDebugEnabled() && stdoutBaos != null) {
            getLog().debug(stdoutBaos.toString());
        }
        if (getLog().isErrorEnabled() && stderrBaos != null) {
            getLog().error(stderrBaos.toString());
        }
        if (error) {
            throw new MojoExecutionException("Jython failed with return code: " + p.exitValue());
        }
    } catch (InterruptedException e) {
        throw new MojoExecutionException("Python tests were interrupted", e);
    }

}

From source file:tachyon.java.manager.JavaFxManager.java

@Override
public void run(ProcessItem pro) {
    build(pro);/*from  w w  w. j a  va 2s  . c  o  m*/
    if (!pro.isCancelled()) {
        ProcessBuilder pb = getRunString();
        pb.directory(getProject().getRootDirectory().toFile());
        try {
            Process start = pb.start();
            pro.setName("Launching Jar File for Project " + getProject().getProjectName());
            pro.setProcess(start);
            ProcessPool.getPool().addItem(pro);
            (new Thread(new Project.OutputReader(start.getInputStream(), pro.getConsole()))).start();
            (new Thread(new Project.ErrorReader(start.getErrorStream(), pro.getConsole()))).start();
            int waitFor = start.waitFor();
            System.out.println(waitFor);
        } catch (IOException | InterruptedException e) {
        }
    }
}

From source file:tachyon.java.manager.JavaFxManager.java

@Override
public void compile(ProcessItem pro) {
    if (!pro.isCancelled()) {
        ProcessBuilder pb = getCompileString();
        pb.directory(getProject().getRootDirectory().toFile());
        try {/*from  www.j a  v  a2 s .  com*/
            Process start = pb.start();
            pro.setName("Compile Files for Project " + getProject().getProjectName());
            pro.setProcess(start);
            ProcessPool.getPool().addItem(pro);
            (new Thread(new Project.OutputReader(start.getInputStream(), pro.getConsole()))).start();
            (new Thread(new Project.ErrorReader(start.getErrorStream(), pro.getConsole()))).start();
            int waitFor = start.waitFor();
            System.out.println(waitFor);
        } catch (IOException | InterruptedException e) {
        }
    }
}

From source file:de.teamgrit.grit.checking.compile.GccCompileChecker.java

@Override
public CompilerOutput checkProgram(Path pathToProgramFile, Path outputFolder, String compilerName,
        List<String> compilerFlags)
        throws FileNotFoundException, BadCompilerSpecifiedException, BadFlagException {

    // First we build the command to invoke the compiler. This consists of
    // the compiler executable, the path of the
    // file to compile and compiler flags. So for example we call:
    List<String> compilerInvocation = createCompilerInvocation(pathToProgramFile, compilerName, compilerFlags);
    // Now we build a launchable process from the given parameters and set
    // the working directory.
    Process compilerProcess = null;

    try {/*from  ww  w .  j a  v  a  2s  . co  m*/
        ProcessBuilder compilerProcessBuilder = new ProcessBuilder(compilerInvocation);
        // make sure the compiler stays in its directory.
        if (Files.isDirectory(pathToProgramFile)) {
            compilerProcessBuilder.directory(pathToProgramFile.toFile());
        } else {
            compilerProcessBuilder.directory(pathToProgramFile.getParent().toFile());
        }
        compilerProcess = compilerProcessBuilder.start();
    } catch (IOException e) {
        // If we cannot call the compiler we return a CompilerOutput
        // initialized with false, false, indicating
        // that the compiler wasn't invoked properly and that there was no
        // clean Compile.
        CompilerOutput compilerInvokeError = new CompilerOutput();
        compilerInvokeError.setClean(false);
        compilerInvokeError.setCompilerInvoked(false);
        LOGGER.severe("Couldn't launch GCC. Check whether it's in the system's PATH");
        return compilerInvokeError;
    }

    // Now we read compiler output. If everything is ok gcc reports
    // nothing at all.
    InputStream compilerOutputStream = compilerProcess.getErrorStream();
    InputStreamReader compilerStreamReader = new InputStreamReader(compilerOutputStream);
    BufferedReader compilerOutputBuffer = new BufferedReader(compilerStreamReader);
    String line;

    CompilerOutput compilerOutput = new CompilerOutput();
    compilerOutput.setCompilerInvoked(true);

    List<String> compilerOutputLines = new LinkedList<>();

    try {
        while ((line = compilerOutputBuffer.readLine()) != null) {
            compilerOutputLines.add(line);
        }

        compilerOutputStream.close();
        compilerStreamReader.close();
        compilerOutputBuffer.close();
        compilerProcess.destroy();
    } catch (IOException e) {
        // Reading might go wrong here if gcc should unexpectedly terminate
        LOGGER.severe("Error while reading from compiler stream.");
        compilerOutput.setClean(false);
        compilerOutput.setCompileStreamBroken(true);
        return compilerOutput;
    }

    if (compilerOutputLines.size() == 0) {
        compilerOutput.setClean(true);
    }

    compilerOutput = splitCompilerOutput(compilerOutputLines, compilerOutput);

    // delete all .o and .exe files
    // these are output files generated by gcc which we won't need
    // anymore
    File[] candidateToplevelFiles = pathToProgramFile.toFile().listFiles();
    for (File candidateFile : candidateToplevelFiles) {
        if (!candidateFile.isDirectory()) {
            String extension = FilenameUtils.getExtension(candidateFile.toString());
            if (extension.matches("([Oo]|([Ee][Xx][Ee]))")) {
                // We only pass the filename, since gcc will be
                // confined to the dir the file is located in.
                candidateFile.delete();
            }
        }

    }

    return compilerOutput;
}