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.c4om.autoconf.ulysses.configanalyzer.guilauncher.ChromeAppEditorGUILauncher.java

/**
 * @see com.c4om.autoconf.ulysses.interfaces.configanalyzer.core.GUILauncher#launchGUI(com.c4om.autoconf.ulysses.interfaces.configanalyzer.core.datastructures.ConfigurationAnalysisContext, com.c4om.autoconf.ulysses.interfaces.Target)
 *///from   ww  w. ja  v  a  2 s. com
@SuppressWarnings("resource")
@Override
public void launchGUI(ConfigurationAnalysisContext context, Target target) throws GUILaunchException {
    try {
        List<File> temporaryFolders = this.getTemporaryStoredChangesetsAndConfigs(context, target);

        for (File temporaryFolder : temporaryFolders) {

            //The temporary folder where one subfolder per analyzer execution will be stored (and removed).
            File temporaryFolderRoot = temporaryFolder.getParentFile().getParentFile();

            System.out.println("Writing launch properties.");

            //Now, we build the properties file
            Properties launchProperties = new Properties();
            String relativeTemporaryFolder = temporaryFolder.getAbsolutePath()
                    .replaceAll("^" + Pattern.quote(temporaryFolderRoot.getAbsolutePath()), "")
                    .replaceAll("^" + Pattern.quote(File.separator), "")
                    .replaceAll(Pattern.quote(File.separator) + "$", "")
                    .replaceAll(Pattern.quote(File.separator) + "+", "/");
            //            launchProperties.put(KEY_LOAD_RECOMMENDATIONS_FILE, relativeTemporaryFolder+CHANGESET_TO_APPLY);
            launchProperties.put(KEY_CATALOG, relativeTemporaryFolder + CATALOG_FILE_PATH);
            Writer writer = new OutputStreamWriter(
                    new FileOutputStream(new File(temporaryFolderRoot, LAUNCH_PROPERTIES_FILE_NAME)),
                    Charsets.UTF_8);
            launchProperties.store(writer, "");
            writer.close();
            System.out.println("Launch properties written!!!!");

            System.out.println("Launching XML editor Chrome app");

            Properties configurationAnalyzerProperties = context.getConfigurationAnalyzerSettings();
            String chromeLocation = configurationAnalyzerProperties.getProperty(PROPERTIES_KEY_CHROME_LOCATION);
            String editorChromeAppLocation = configurationAnalyzerProperties
                    .getProperty(PROPERTIES_KEY_EDITOR_CHROME_APP_LOCATION);

            ProcessBuilder chromeEditorPB = new ProcessBuilder(
                    ImmutableList.of(chromeLocation, "--load-and-launch-app=" + editorChromeAppLocation));
            chromeEditorPB.directory(new File(editorChromeAppLocation));
            chromeEditorPB.start();
            System.out.println("Editor started!!!");
            System.out.println("Now, make all your changes and press ENTER when finished...");
            new Scanner(System.in).nextLine();
            FileUtils.forceDeleteOnExit(temporaryFolder.getParentFile());

        }
    } catch (IOException e) {
        throw new GUILaunchException(e);
    }
}

From source file:net.sf.jasperreports.phantomjs.PhantomJSProcess.java

public void startPhantomJS() {
    String mainScriptTempName = director.getScriptManager().getScriptFilename(PhantomJS.MAIN_SCRIPT_RESOURCE);
    String listenAddress = listenURI.getHost() + ":" + listenURI.getPort();
    int idleTimeout = director.getProcessIdleTimeout();

    List<String> command = new ArrayList<String>();
    command.add(director.getPhantomjsExecutablePath());
    String options = "";
    if (director.getOptions() != null) {
        for (PropertySuffix suffix : director.getOptions()) {
            String option = suffix.getValue();
            if (option != null && !option.trim().isEmpty()) {
                command.add(option.trim());
                options += option.trim() + " ";
            }//from  www  . ja va2  s. c om
        }
    }

    command.add(mainScriptTempName);
    command.add("-listenAddress");
    command.add(listenAddress);
    command.add("-confirmMessage");
    command.add(PHANTOMJS_CONFIRMATION_MESSAGE);
    command.add("-idleTimeout");
    command.add(Integer.toString(idleTimeout));

    log.info("PhantomJS process " + id + " starting on port " + listenURI.getPort());
    if (log.isDebugEnabled()) {
        log.debug(id + " starting phantomjs process with command: " + director.getPhantomjsExecutablePath()
                + options + " \"" + mainScriptTempName + "\"" + " -listenAddress \"" + listenAddress + "\""
                + " -confirmMessage \"" + PHANTOMJS_CONFIRMATION_MESSAGE + "\"" + " -idleTimeout " + idleTimeout
                + "");
    }

    ProcessBuilder pb = new ProcessBuilder(command);
    pb.redirectErrorStream(false);
    pb.directory(director.getScriptManager().getTempFolder());

    try {
        process = pb.start();

        ProcessOutputReader outputReader = new ProcessOutputReader(this);
        outputReader.start();
        boolean started = outputReader.waitConfirmation(director.getProcessStartTimeout());
        if (!started) {
            log.error("PhantomJS process " + id + " failed to start");//TODO lucianc write error output
            process.destroy();

            throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_FAILED_START, (Object[]) null);
        }

        processConnection = new ProcessConnection(director, this);
    } catch (IOException e) {
        throw new JRRuntimeException(e);
    }
}

From source file:de.sandroboehme.lesscss.mojo.NodeJsLessCompiler.java

private String compile(String input) throws LessException, IOException, InterruptedException {
    long start = System.currentTimeMillis();

    File inputFile = File.createTempFile("lessc-input-", ".less");
    FileOutputStream out = new FileOutputStream(inputFile);
    IOUtils.write(input, out);//from w  ww  .j  av  a  2 s  .c  o m
    out.close();
    File outputFile = File.createTempFile("lessc-output-", ".css");
    File lesscJsFile = new File(tempDir, "lessc.js");

    ProcessBuilder pb = new ProcessBuilder(nodeExecutablePath, lesscJsFile.getAbsolutePath(),
            inputFile.getAbsolutePath(), outputFile.getAbsolutePath(), String.valueOf(compress));
    pb.redirectErrorStream(true);
    Process process = pb.start();
    IOUtils.copy(process.getInputStream(), System.out);

    int exitStatus = process.waitFor();

    FileInputStream in = new FileInputStream(outputFile);
    String result = IOUtils.toString(in);
    in.close();
    if (!inputFile.delete()) {
        log.warn("Could not delete temp file: " + inputFile.getAbsolutePath());
    }
    if (!outputFile.delete()) {
        log.warn("Could not delete temp file: " + outputFile.getAbsolutePath());
    }
    if (exitStatus != 0) {
        throw new LessException(result, null);
    }

    log.debug("Finished compilation of LESS source in " + (System.currentTimeMillis() - start) + " ms.");

    return result;
}

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);/*w  w w .j  av a 2 s .co  m*/
    builder.directory(detectBaseDirectory());
    Process p = builder.start();
    p.waitFor();
    IOUtils.copy(p.getInputStream(), System.out);
    return p;
}

From source file:com.example.bot.spring.KitchenSinkController.java

private void system(String... args) {
    ProcessBuilder processBuilder = new ProcessBuilder(args);
    try {//from w w w.  j  ava  2 s.c  o  m
        Process start = processBuilder.start();
        int i = start.waitFor();
        log.info("result: {} =>  {}", Arrays.toString(args), i);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } catch (InterruptedException e) {
        log.info("Interrupted", e);
        Thread.currentThread().interrupt();
    }
}

From source file:com.bekwam.resignator.commands.KeytoolCommand.java

public List<KeystoreEntry> findKeystoreEntries(String keytoolExec, String keystore, String storepass)
        throws CommandExecutionException {

    List<KeystoreEntry> entries = new ArrayList<>();

    Preconditions.checkNotNull(keytoolExec);
    Preconditions.checkNotNull(keystore);
    Preconditions.checkNotNull(storepass);

    File outputFile = null;/*from w ww  .ja v a2  s .  c om*/

    try {

        String[] cmdAndArgs = { keytoolExec, "-keystore", keystore, "-storepass", storepass, "-list" };

        File resignatorDir = new File(System.getProperty("user.home"), ".resignator");

        String outputFileName = OUTPUTFILE_PREFIX
                + StringUtils.lowerCase(RandomStringUtils.randomAlphabetic(12)) + OUTPUTFILE_SUFFIX;

        outputFile = new File(resignatorDir, outputFileName);

        ProcessBuilder pb = new ProcessBuilder(cmdAndArgs);
        pb.redirectErrorStream(false);
        pb.redirectOutput(outputFile);

        Process p = pb.start();

        boolean exitted = p.waitFor(TIMEOUT_SECS, TimeUnit.SECONDS);

        if (exitted) {

            if (p.exitValue() == 0) {

                BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(outputFile)));
                entries.addAll(parseKeystoreEntries(br));
                br.close();

            } else {

                String firstLine = "";
                if (outputFile != null && outputFile.exists()) {
                    BufferedReader br = new BufferedReader(new FileReader(outputFile));
                    firstLine = br.readLine();
                    br.close();
                }

                if (logger.isErrorEnabled()) {
                    logger.error("error running exec={}; firstLine={}", keytoolExec, firstLine);
                }

                throw new CommandExecutionException(
                        "Command '" + keytoolExec + "' failed to run" + newLine + firstLine);
            }

        } else {

            if (logger.isErrorEnabled()) {
                logger.error("command '" + keytoolExec + "' timed out");
            }

            throw new CommandExecutionException("Command '" + keytoolExec + "' timed out");
        }

    } catch (Exception exc) { // includes interrupted exception

        if (logger.isErrorEnabled()) {
            logger.error("error running keytool", exc);
        }

        throw new CommandExecutionException("Error running keytool command" + newLine + exc.getMessage());

    } finally {
        if (outputFile != null) {
            outputFile.delete();
        }
    }

    return entries;
}

From source file:com.netflix.raigad.defaultimpl.ElasticSearchProcessManager.java

public void start(boolean join_ring) throws IOException {
    logger.info("Starting elasticsearch server");

    List<String> command = Lists.newArrayList();
    if (!"root".equals(System.getProperty("user.name"))) {
        command.add(SUDO_STRING);/*w  ww . ja  va  2  s .  co m*/
        command.add("-n");
        command.add("-E");
    }
    command.addAll(getStartCommand());

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

    env.put("DATA_DIR", config.getDataFileLocation());

    startEs.directory(new File("/"));
    startEs.redirectErrorStream(true);
    Process starter = startEs.start();
    logger.info("Starting Elasticsearch server ....");
    try {
        sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS);
        int code = starter.exitValue();
        if (code == 0)
            logger.info("Elasticsearch server has been started");
        else
            logger.error("Unable to start Elasticsearch server. Error code: {}", code);

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

From source file:functionalTests.annotations.AptTest.java

private Result runApt() throws CompilationExecutionException {
    try {/*from w  w  w  .j a v a 2s .c om*/
        ProcessBuilder processBuilder = new ProcessBuilder(Arrays.asList(_aptCommand));
        Map<String, String> env = processBuilder.environment();
        env.put("CLASSPATH", _classpath);

        Process aptProcess = processBuilder.start();

        BufferedReader stderr = new BufferedReader(new InputStreamReader(aptProcess.getErrorStream()));
        //flushOutput(stderr);

        return getResults(stderr);
    } catch (IOException ioExcp) {
        String msg = "Cannot execute the command " + compressCommand(_aptCommand) + ".reason:"
                + ioExcp.getMessage();
        logger.error(msg, ioExcp);
        throw new CompilationExecutionException(msg, ioExcp);
    } catch (SecurityException secExcp) {
        String msg = "Cannot execute the command " + compressCommand(_aptCommand)
                + "; security access violation.";
        logger.error(msg, secExcp);
        throw new CompilationExecutionException(msg, secExcp);
    }
}

From source file:org.mashupmedia.encode.ProcessManager.java

public String callProcess(List<String> commands) throws IOException {

    logger.info("Starting process...");

    ProcessBuilder processBuilder = new ProcessBuilder(commands);
    processBuilder.redirectErrorStream(true);
    Process process = processBuilder.start();

    InputStream inputStream = process.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    String line;/*from   www.ja  va  2s  .  c o  m*/

    StringBuilder outputBuilder = new StringBuilder();

    while ((line = bufferedReader.readLine()) != null) {
        logger.info(line);
        outputBuilder.append(line);
    }
    IOUtils.closeQuietly(inputStream);

    try {
        int waitForValue = process.waitFor();
        logger.info("Process waitFor value = " + waitForValue);
    } catch (InterruptedException e) {
        logger.error("Error waiting for waitFor.", e);
    }

    int exitValue = process.exitValue();
    logger.info("Process exit value = " + exitValue);

    return outputBuilder.toString();

}

From source file:dk.netarkivet.wayback.aggregator.IndexAggregator.java

/**
 * Calls the Unix sort command with the options <code>$filesNames -o
 * $outputfile -T WaybackSettings#WAYBACK_AGGREGATOR_TEMP_DIR.
 * <p>// www  .  ja v  a  2  s .c o  m
 * Sets the LC_ALL environment variable before making the call.
 *
 * @param files The files to merge and sort
 * @param outputFile The resulting sorted file
 * @param additionalArgs A list af extra arguments, which (if different from null) are added to the sort call.<p>
 * Note: If any of the args contain a whitespace the call will fail.
 */
private void processFiles(File[] files, File outputFile, List<String> additionalArgs) {
    if (files.length == 0) {
        // Empty file list will cause sort to wait for further input,
        // and the call will therefore never return
        return;
    }

    Process p = null;

    try {
        List<String> inputFileList = new LinkedList<String>();
        for (int i = 0; i < files.length; i++) {
            if (files[i].exists() && files[i].isFile()) {
                inputFileList.add(files[i].getCanonicalPath());
            } else {
                log.warn("File " + files[i] + " doesn't exist or isn't a regular file, "
                        + "dropping from list of files to " + "sort and merge");
            }
        }
        List<String> cmd = new LinkedList<String>();
        // Prepare to run the unix sort command, see sort manual page for
        // details
        cmd.add("sort");
        cmd.addAll(inputFileList);
        cmd.add("-o");
        cmd.add(outputFile.getCanonicalPath());
        cmd.add("-T");
        cmd.add(Settings.get(WaybackSettings.WAYBACK_AGGREGATOR_TEMP_DIR));
        if (additionalArgs != null && !additionalArgs.isEmpty()) {
            for (String argument : additionalArgs) {
                ArgumentNotValid.checkTrue(argument.indexOf(' ') == -1,
                        "The argument '" + argument + "' contains spaces, this isn't allowed ");
            }
            cmd.addAll(additionalArgs);
        }
        ProcessBuilder pb = new ProcessBuilder(cmd);
        // Reset all locale definitions
        pb.environment().put("LC_ALL", "C");
        // Run the command in the user.dir directory
        pb.directory(new File(System.getProperty("user.dir")));
        p = pb.start();
        p.waitFor();
        if (p.exitValue() != 0) {
            log.error("Failed to sort index files, sort exited with " + "return code " + p.exitValue());
        }
    } catch (Exception e) {
        log.error("Failed to aggregate indexes ", e);
    }
}