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:eu.udig.omsbox.core.OmsScriptExecutor.java

/**
 * Execute an OMS script.//from  w  w w .  j a va 2 s .c  o m
 * 
 * @param script the script file or the script string.
 * @param internalStream
 * @param errorStream
 * @param loggerLevelGui the log level as presented in the GUI, can be OFF|ON. This is not the OMS logger level, which 
 *                              in stead has to be picked from the {@link OmsBoxConstants#LOGLEVELS_MAP}.
 * @param ramLevel the heap size to use in megabytes.
 * @return the process.
 * @throws Exception
 */
public Process exec(String script, final PrintStream internalStream, final PrintStream errorStream,
        String loggerLevelGui, String ramLevel) throws Exception {
    if (loggerLevelGui == null)
        loggerLevelGui = OmsBoxConstants.LOGLEVEL_GUI_OFF;

    File scriptFile = new File(script);
    if (!scriptFile.exists()) {
        // if the file doesn't exist, it is a script, let's put it into a file
        scriptFile = File.createTempFile("omsbox_script_", ".oms");
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter(scriptFile));
            bw.write(script);
        } finally {
            bw.close();
        }

    } else {
        // it is a script in a file, read it to log it
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        try {
            br = new BufferedReader(new FileReader(scriptFile));
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } finally {
            br.close();
        }
        script = sb.toString();
    }

    // tmp folder
    String tempdir = System.getProperty("java.io.tmpdir");
    File omsTmp = new File(tempdir + File.separator + "oms");
    if (!omsTmp.exists())
        omsTmp.mkdirs();

    List<String> arguments = new ArrayList<String>();
    arguments.add(javaFile);

    // ram usage
    String ramExpr = "-Xmx" + ramLevel + "m";
    arguments.add(ramExpr);

    // modules jars
    List<String> modulesJars = OmsModulesManager.getInstance().getModulesJars();
    StringBuilder sb = new StringBuilder();
    for (String moduleJar : modulesJars) {
        sb.append(File.pathSeparator).append(moduleJar);
    }
    String modulesJarsString = sb.toString().replaceFirst(File.pathSeparator, "");
    String resourcesFlag = "-Doms.sim.resources=\"" + modulesJarsString + "\"";
    arguments.add(resourcesFlag);

    // grass gisbase
    String grassGisbase = OmsBoxPlugin.getDefault().getGisbasePreference();
    if (grassGisbase != null && grassGisbase.length() > 0) {
        arguments.add("-D" + OmsBoxConstants.GRASS_ENVIRONMENT_GISBASE_KEY + "=" + grassGisbase);
    }
    String grassShell = OmsBoxPlugin.getDefault().getShellPreference();
    if (grassShell != null && grassShell.length() > 0) {
        arguments.add("-D" + OmsBoxConstants.GRASS_ENVIRONMENT_SHELL_KEY + "=" + grassShell);
    }

    // all the arguments
    arguments.add("-cp");
    arguments.add(classPath);
    arguments.add(CLI.class.getCanonicalName());
    arguments.add("-r ");
    arguments.add("\"" + scriptFile.getAbsolutePath() + "\"");

    String homeDir = System.getProperty("java.io.tmpdir");
    File homeFile = new File(homeDir);
    StringBuilder runSb = new StringBuilder();
    for (String arg : arguments) {
        runSb.append(arg).append(" ");
    }

    String[] args;
    if (Platform.getOS().equals(Platform.OS_WIN32)) {
        File tmpRunFile = new File(homeFile, "udig_spatialtoolbox.bat");
        FileUtils.writeStringToFile(tmpRunFile, "@echo off\n" + runSb.toString());
        args = new String[] { "cmd", "/c", tmpRunFile.getAbsolutePath() };
    } else {
        File tmpRunFile = new File(homeFile, "udig_spatialtoolbox.sh");
        FileUtils.writeStringToFile(tmpRunFile, runSb.toString());
        args = new String[] { "sh", tmpRunFile.getAbsolutePath() };
    }

    // {javaFile, ramExpr, resourcesFlag, "-cp", classPath,
    // CLI.class.getCanonicalName(), "-r",
    // scriptFile.getAbsolutePath()};

    ProcessBuilder processBuilder = new ProcessBuilder(args);
    // work in home
    // processBuilder.directory(homeFile);

    // environment
    Map<String, String> environment = processBuilder.environment();
    // environment.put("CLASSPATH", classPath);

    final Process process = processBuilder.start();
    internalStream.println(
            "Process started: " + new DateTime().toString(OmsBoxConstants.dateTimeFormatterYYYYMMDDHHMMSS));
    internalStream.println("");

    // command launched
    if (loggerLevelGui.equals(OmsBoxConstants.LOGLEVEL_GUI_ON)) {
        internalStream.println("------------------------------>8----------------------------");
        internalStream.println("Launching command: ");
        internalStream.println("------------------");
        List<String> command = processBuilder.command();
        for (String arg : command) {
            internalStream.print(arg);
            internalStream.print(" ");
        }
        internalStream.println("\n");
        internalStream.println("(you can run the above from command line, customizing the content)");
        internalStream.println("----------------------------------->8---------------------------------");
        internalStream.println("");
        // script run
        internalStream.println("Script run: ");
        internalStream.println("-----------");
        internalStream.println(script);
        internalStream.println("");
        internalStream.println("------------------------------>8----------------------------");
        internalStream.println("");
        // environment used
        internalStream.println("Environment used: ");
        internalStream.println("-----------------");

        Set<Entry<String, String>> entrySet = environment.entrySet();
        for (Entry<String, String> entry : entrySet) {
            internalStream.print(entry.getKey());
            internalStream.print(" =\t");
            internalStream.println(entry.getValue());
        }
        internalStream.println("------------------------------>8----------------------------");
        internalStream.println("");
    }
    internalStream.println("");
    isRunning = true;

    new Thread() {
        public void run() {
            BufferedReader br = null;
            try {
                InputStream is = process.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null) {
                    internalStream.println(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
                errorStream.println(e.getLocalizedMessage());
            } finally {
                if (br != null)
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                isRunning = false;
                updateListeners();
            }
            internalStream.println("");
            internalStream.println("");
            internalStream.println("Process finished: "
                    + new DateTime().toString(OmsBoxConstants.dateTimeFormatterYYYYMMDDHHMMSS));
        };
    }.start();

    new Thread() {
        public void run() {
            BufferedReader br = null;
            try {
                InputStream is = process.getErrorStream();
                InputStreamReader isr = new InputStreamReader(is);
                br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null) {
                    /*
                     * remove of ugly recurring geotools warnings. Not nice, but 
                     * at least users do not get confused. 
                     */
                    if (ConsoleMessageFilter.doRemove(line)) {
                        continue;
                    }
                    errorStream.println(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
                errorStream.println(e.getLocalizedMessage());
            } finally {
                if (br != null)
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
        };
    }.start();

    return process;
}

From source file:com.clustercontrol.util.CommandExecutor.java

public Process execute() throws HinemosUnknown {
    // workaround for JVM(Windows) Bug
    // Runtime#exec is not thread safe on Windows.

    try {/*  w  w w.ja  v a  2  s.com*/
        synchronized (_runtimeExecLock) {
            ProcessBuilder pb = new ProcessBuilder(_command);
            // ???"_JAVA_OPTIONS"????
            pb.environment().remove("_JAVA_OPTIONS");
            for (Map.Entry<String, String> entry : envMap.entrySet()) {
                pb.environment().put(entry.getKey(), entry.getValue());
            }
            process = pb.start();
        }
    } catch (Exception e) {
        log.warn("command executor failure. (command = " + _commandLine + ") " + e.getMessage(), e);
        throw new HinemosUnknown(e.getMessage());
    }
    return process;
}

From source file:com.redhat.jenkins.plugins.ci.integration.FedMsgMessagingPluginIntegrationTest.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 va2 s  .  c  om*/
    System.out.println("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);
        System.out.println("Issue occurred during command \"" + commandName + "\":\n" + writer.toString());
        writer.close();
    }
    return processToRun;
}

From source file:de.tudarmstadt.ukp.dkpro.core.RSTAnnotator.java

/**
 * Runs the parser on the given text//from  w  w w  .j  a  v a 2 s . co m
 *
 * @param originalText text
 * @return parse tree
 * @throws IOException exception
 */
public String parseWithRST(String originalText) throws IOException {
    // temporary file in
    File tmpFileIn = File.createTempFile("rst_tmp", ".txt");
    // output of RST parser is a .tree file
    File tmpFileOut = new File(tmpFileIn.getAbsolutePath() + ".tree");
    // tmp log
    File tmpFileLog = new File(tmpFileIn.getAbsolutePath() + ".log");

    try {
        // write the text into a temporary file
        FileUtils.writeStringToFile(tmpFileIn, originalText);

        String tmpDirName = System.getProperty("java.io.tmpdir");

        File rstParserSrcDir = new File(rstParserSrcDirPath);

        // create process
        ProcessBuilder processBuilder = new ProcessBuilder().inheritIO();

        // log to file
        processBuilder.redirectErrorStream(true);
        processBuilder.redirectOutput(ProcessBuilder.Redirect.to(tmpFileLog));

        // working dir must be set to the src dir of RST parser
        processBuilder.directory(rstParserSrcDir);

        // run the command
        processBuilder.command("python", new File(rstParserSrcDir, "parse.py").getAbsolutePath(), "-t",
                tmpDirName, tmpFileIn.getAbsolutePath(), "-g");
        Process process = processBuilder.start();

        // and wait
        int returnValue = process.waitFor();

        if (returnValue != 0) {
            throw new RuntimeException("Process exited with code " + returnValue);
        }

        // read the log
        if (this.debugRSTOutput) {
            getLogger().debug(FileUtils.readFileToString(tmpFileLog));
        }

        // read the output
        if (tmpFileOut.exists()) {
            return FileUtils.readFileToString(tmpFileOut);
        }
    } catch (InterruptedException e) {
        throw new IOException(e);
    } finally {
        // clean up
        if (!keepTmpFiles) {
            FileUtils.deleteQuietly(tmpFileIn);
            FileUtils.deleteQuietly(tmpFileOut);
            FileUtils.deleteQuietly(tmpFileLog);
        }
    }

    return null;
}

From source file:edu.stanford.epad.epadws.processing.pipeline.task.DicomHeadersTask.java

@Override
public void run() {
    Thread.currentThread().setPriority(Thread.MIN_PRIORITY); // Let interactive thread run sooner
    FileWriter tagFileWriter = null;
    InputStream is = null;/*from  www . j  a  v  a 2  s  .  c o  m*/
    InputStreamReader isr = null;
    BufferedReader br = null;
    Process process = null;

    try {
        String[] command = { "./dcm2txt", "-w", "250", "-l", "250", dicomInputFile.getAbsolutePath() };
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        String dicomBinDir = EPADConfig.getEPADWebServerDICOMScriptsDir() + "bin/";
        File script = new File(dicomBinDir, "dcm2txt");
        if (!script.exists())
            dicomBinDir = EPADConfig.getEPADWebServerDICOMBinDir();
        script = new File(dicomBinDir, "dcm2txt");
        // Java 6 - Runtime.getRuntime().exec("chmod u+x "+script.getAbsolutePath());
        script.setExecutable(true);

        processBuilder.directory(new File(dicomBinDir));
        process = processBuilder.start();
        process.getOutputStream();

        is = process.getInputStream();
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);

        String line;
        StringBuilder sb = new StringBuilder();
        StringBuilder log = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
            log.append("./dcm2txt: " + line).append("\n");
        }

        try {
            process.waitFor();
        } catch (InterruptedException e) {
            logger.info(log.toString());
            logger.warning("Couldn't get tags for series " + seriesUID + "; dicom="
                    + dicomInputFile.getAbsolutePath() + " tagFile:" + outputFile.getAbsolutePath(), e);
        }

        EPADFileUtils.createDirsAndFile(outputFile);
        File tagFile = outputFile;
        tagFileWriter = new FileWriter(tagFile);
        tagFileWriter.write(sb.toString());
    } catch (Exception e) {
        logger.warning("DicomHeadersTask failed to create DICOM tags for series " + seriesUID + " dicom FIle:"
                + dicomInputFile.getAbsolutePath() + " : " + outputFile.getAbsolutePath(), e);
    } catch (OutOfMemoryError oome) {
        logger.warning("DicomHeadersTask for series " + seriesUID + " out of memory: ", oome);
    } finally {
        IOUtils.closeQuietly(tagFileWriter);
        IOUtils.closeQuietly(br);

        if (process != null)
            process.destroy();
    }
}

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   w w  w .j a  va2s .  c om*/
        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;
}

From source file:cn.dockerfoundry.ide.eclipse.server.core.internal.ProcessLauncher.java

/**
 * Returns when the process has exited without errors. This will wait for
 * the process to exist, therefore will block the current thread in which it
 * is running. If any errors occur, throws CoreException CoreException
 * @throws CoreException if any errors occur while the process is being
 * launched//from  w  ww  .  j  a va2 s.  c  om
 */
public void run() throws CoreException {
    Exception error = null;
    Process p = null;
    try {

        List<String> processArguments = getProcessArguments();

        if (processArguments == null || processArguments.isEmpty()) {
            throw new CoreException(getErrorStatus("No process arguments were found")); //$NON-NLS-1$
        } else {

            ProcessBuilder processBuilder = new ProcessBuilder(processArguments);

            // Set any environment variables
            Map<String, String> envVars = getEnvironmentVariables();
            if (envVars != null) {
                Map<String, String> actualVars = processBuilder.environment();
                if (actualVars != null) {
                    for (Entry<String, String> entry : envVars.entrySet()) {
                        actualVars.put(entry.getKey(), entry.getValue());
                    }
                }
            }

            p = processBuilder.start();

            if (p == null) {
                throw new CoreException(getErrorStatus("No process was created.")); //$NON-NLS-1$
            } else {

                StringBuffer errorBuffer = new StringBuffer();
                // Clear the input and error streams to prevent the
                // process
                // from blocking
                handleProcessIOAsynch(p, null, errorBuffer);

                p.waitFor();

                if (errorBuffer.length() > 0) {
                    throw new CoreException(getErrorStatus(errorBuffer.toString()));
                } else if (p.exitValue() != 0) {
                    throw new CoreException(getErrorStatus("process exit value: " + p.exitValue())); //$NON-NLS-1$
                }
            }
        }
    } catch (InterruptedException ex) {
        error = ex;
    } catch (IOException ioe) {
        error = ioe;
    } catch (SecurityException se) {
        error = se;
    } finally {
        if (p != null) {
            p.destroy();
        }
    }

    if (error != null) {
        throw error instanceof CoreException ? (CoreException) error : CloudErrorUtil.toCoreException(error);
    }

}

From source file:alluxio.multi.process.MultiProcessCluster.java

/**
 * Copies the work directory to the artifacts folder.
 *//*from   www .ja va 2 s  .  c o m*/
public synchronized void saveWorkdir() throws IOException {
    Preconditions.checkState(mState == State.STARTED,
            "cluster must be started before you can save its work directory");
    ARTIFACTS_DIR.mkdirs();

    File tarball = new File(mWorkDir.getParentFile(), mWorkDir.getName() + ".tar.gz");
    // Tar up the work directory.
    ProcessBuilder pb = new ProcessBuilder("tar", "-czf", tarball.getName(), mWorkDir.getName());
    pb.directory(mWorkDir.getParentFile());
    pb.redirectOutput(Redirect.appendTo(TESTS_LOG));
    pb.redirectError(Redirect.appendTo(TESTS_LOG));
    Process p = pb.start();
    try {
        p.waitFor();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
    }
    // Move tarball to artifacts directory.
    File finalTarball = new File(ARTIFACTS_DIR, tarball.getName());
    FileUtils.moveFile(tarball, finalTarball);
    LOG.info("Saved cluster {} to {}", mClusterName, finalTarball.getAbsolutePath());
}

From source file:com.netscape.cms.profile.constraint.ExternalProcessConstraint.java

public void validate(IRequest request, X509CertInfo info) throws ERejectException {
    CMS.debug("About to execute command: " + this.executable);
    ProcessBuilder pb = new ProcessBuilder(this.executable);

    // set up process environment
    Map<String, String> env = pb.environment();
    for (String k : envVars.keySet()) {
        String v = request.getExtDataInString(envVars.get(k));
        if (v != null)
            env.put(k, v);/*from w  w w . j a v  a  2  s  . co  m*/
    }
    for (String k : extraEnvVars.keySet()) {
        String v = request.getExtDataInString(extraEnvVars.get(k));
        if (v != null)
            env.put(k, v);
    }

    Process p;
    String stdout = "";
    String stderr = "";
    boolean timedOut;
    try {
        p = pb.start();
        timedOut = !p.waitFor(timeout, TimeUnit.SECONDS);
        if (timedOut)
            p.destroyForcibly();
        else
            stdout = IOUtils.toString(p.getInputStream());
        stderr = IOUtils.toString(p.getErrorStream());
    } catch (Throwable e) {
        String msg = "Caught exception while executing command: " + this.executable;
        CMS.debug(msg);
        CMS.debug(e);
        throw new ERejectException(msg, e);
    }
    if (timedOut)
        throw new ERejectException("Request validation timed out");
    int exitValue = p.exitValue();
    CMS.debug("ExternalProcessConstraint: exit value: " + exitValue);
    CMS.debug("ExternalProcessConstraint: stdout: " + stdout);
    CMS.debug("ExternalProcessConstraint: stderr: " + stderr);
    if (exitValue != 0)
        throw new ERejectException(stdout);
}