Example usage for java.lang ProcessBuilder command

List of usage examples for java.lang ProcessBuilder command

Introduction

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

Prototype

List command

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

Click Source Link

Usage

From source file:org.apache.asterix.test.aql.TestExecutor.java

private static String executeVagrantScript(ProcessBuilder pb, String node, String scriptName) throws Exception {
    pb.command("vagrant", "ssh", node, "--", pb.environment().get("SCRIPT_HOME") + scriptName);
    Process p = pb.start();//from   w  ww  .j a va  2s .com
    p.waitFor();
    InputStream input = p.getInputStream();
    return IOUtils.toString(input, StandardCharsets.UTF_8.name());
}

From source file:com.web.searchlocal.flashpaper.thread.Covnert2SwfTask.java

/** 
 * //from  w w  w.  j  a  v a  2  s  .c om
 */
public void excute() {
    String tmpOutFile = outFile.getPath().concat(File.separator)
            .concat(inFile.getName().replaceAll("[.]{1}.*$", ".swf"));
    List<String> commandArray = new ArrayList<String>();
    commandArray.add(defaultCommand);
    commandArray.add(inFile.getPath());
    commandArray.add("-o");
    commandArray.add(tmpOutFile);
    ProcessBuilder pbObj = new ProcessBuilder();
    pbObj.command(commandArray);
    pbObj.directory(outFile);
    pbObj.redirectErrorStream(true);
    try {
        Process proObj = pbObj.start();
        final InputStream ins = proObj.getInputStream();
        final ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        Thread th = new Thread() {
            public void run() {
                ReadableByteChannel rbcObj = Channels.newChannel(ins);
                try {
                    while (rbcObj.read(byteBuffer) != -1) {
                        byteBuffer.flip();
                        logger.info(java.nio.charset.Charset.defaultCharset().decode(byteBuffer));
                        byteBuffer.clear();
                    }
                } catch (IOException e) {
                    logger.error(e);
                }
            }
        };
        th.setDaemon(true);
        th.start();
        try {
            proObj.waitFor();
            logger.error("??." + tmpOutFile);
        } catch (InterruptedException e) {
            logger.error(e);
        }
    } catch (IOException e) {
        logger.error(e);
    }
}

From source file:org.sonar.process.monitor.JavaProcessLauncher.java

private ProcessBuilder create(JavaCommand javaCommand) {
    List<String> commands = new ArrayList<>();
    commands.add(buildJavaPath());//from  w  ww. j a va2  s.c o  m
    commands.addAll(javaCommand.getJavaOptions());
    // TODO warning - does it work if temp dir contains a whitespace ?
    commands.add(String.format("-Djava.io.tmpdir=%s", tempDir.getAbsolutePath()));
    commands.add(getJmxAgentCommand());
    commands.addAll(buildClasspath(javaCommand));
    commands.add(javaCommand.getClassName());
    commands.add(buildPropertiesFile(javaCommand).getAbsolutePath());

    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.command(commands);
    processBuilder.directory(javaCommand.getWorkDir());
    processBuilder.environment().putAll(javaCommand.getEnvVariables());
    processBuilder.redirectErrorStream(true);
    return processBuilder;
}

From source file:aiai.ai.core.ExecProcessService.java

public Result execCommand(List<String> cmd, File execDir, File consoleLogFile)
        throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder();
    pb.command(cmd);
    pb.directory(execDir);//from  w ww .  j  av a2s . co m
    pb.redirectErrorStream(true);
    final Process process = pb.start();

    final StreamHolder streamHolder = new StreamHolder();
    int exitCode;
    try (final FileOutputStream fos = new FileOutputStream(consoleLogFile);
            BufferedOutputStream bos = new BufferedOutputStream(fos)) {
        final Thread reader = new Thread(() -> {
            try {
                streamHolder.is = process.getInputStream();
                int c;
                while ((c = streamHolder.is.read()) != -1) {
                    bos.write(c);
                }
            } catch (IOException e) {
                log.error("Error collect data from output stream", e);
            }
        });
        reader.start();

        exitCode = process.waitFor();
        reader.join();
    } finally {
        try {
            if (streamHolder.is != null) {
                streamHolder.is.close();
            }
        } catch (Throwable th) {
            log.warn("Error with closing InputStream", th);
        }
    }

    log.info("Any errors of execution? {}", (exitCode == 0 ? "No" : "Yes"));
    log.debug("'\tcmd: {}", cmd);
    log.debug("'\texecDir: {}", execDir.getPath());
    String console = readLastLines(500, consoleLogFile);
    log.debug("'\tconsole output:\n{}", console);

    return new Result(exitCode == 0, exitCode, console);
}

From source file:com.yfiton.oauth.receiver.GraphicalReceiver.java

@Override
public AuthorizationData requestAuthorizationData(String authorizationUrl,
        String authorizationCodeParameterName, String... requestParameterNames) throws NotificationException {
    try {// www .  j  a v  a2  s .  c om
        File tmpFile = File.createTempFile("yfiton", ".auth");

        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.inheritIO();
        processBuilder.command("java",
                //"-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005",
                "-classpath", getClasspath(), WebBrowser.class.getName(),
                "--authorization-code-parameter-name=" + authorizationCodeParameterName,
                "--authorization-file=" + tmpFile.getAbsolutePath(), "--authorization-url=" + authorizationUrl,
                "--debug=" + (debug ? "true" : "false"),
                "--webengine-listener-class=" + webEngineListenerClazz.getName());

        Process process = processBuilder.start();

        int returnCode = process.waitFor();

        switch (returnCode) {
        case 0:
            return OAuthUtils.readAuthorizationInfo(tmpFile.toPath());
        case 255:
            throw new NotificationException("Authorization process aborted");
        default:
            throw new NotificationException(
                    "Error occurred while waiting for process: return code " + returnCode);
        }
    } catch (ClassNotFoundException | ConfigurationException | IOException | InterruptedException e) {
        throw new NotificationException(e.getMessage());
    }
}

From source file:de.zib.gndms.logic.model.gorfx.c3grid.ExternalProviderStageInORQCalculator.java

private ProcessBuilderAction createEstAction(final File estCommandFileParam,
        final TransientContract contParam) {
    final @NotNull ProcessBuilder pb = new ProcessBuilder();
    try {//from www  .  j  a  v  a2  s  . c o m
        pb.command(estCommandFileParam.getCanonicalPath());
        pb.directory(new File(getSysInfo().getSystemTempDirName()));
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }

    ProcessBuilderAction action;
    // todo add permissions here when delegation is implemented
    action = parmAux.createPBAction(getORQArguments(), contParam, null);
    action.setProcessBuilder(pb);
    action.setOutputReceiver(new StringBuilder(INITIAL_STRING_BUILDER_CAPACITY));
    action.setErrorReceiver(new StringBuilder(INITIAL_STRING_BUILDER_CAPACITY));
    return action;
}

From source file:com.googlecode.goclipse.tooling.oracle.GoOracleFindDefinitionOperation_Test.java

public void testCreateProcessBuilder$() throws Exception {
    GoOracleFindDefinitionOperation op = new GoOracleFindDefinitionOperation("gopath");

    ProcessBuilder pb;
    pb = op.createProcessBuilder(SAMPLE_GOEnv_1, SAMPLE_GOPATH_Entry.resolve("src/foobar/file.go"), 0);
    assertEquals(pb.command().get(4), "foobar");

    try {/*  w w w . j a  v  a  2  s.  com*/
        op.createProcessBuilder(SAMPLE_GOEnv_1, SAMPLE_GOPATH_Entry.resolve("not_on_src/foobar/file.go"), 0);
        assertFail();
    } catch (CommonException se) {
        assertTrue(se.getMessage().contains("file not in the Go environment"));
    }
}

From source file:org.gradle.vcs.fixtures.GitHttpRepository.java

private Action<HttpExchange> getRefsAction() {
    return new ErroringAction<HttpExchange>() {
        @Override//from www .  jav a2 s  . c  o m
        protected void doExecute(HttpExchange httpExchange) throws Exception {
            ProcessBuilder builder = new ProcessBuilder();
            Process process = builder.command("git", "upload-pack", "--advertise-refs",
                    backingRepo.getWorkTree().getAbsolutePath()).redirectErrorStream(true).start();
            ByteArrayOutputStream content = new ByteArrayOutputStream();
            content.write("001e# service=git-upload-pack\n".getBytes());
            content.write("0000".getBytes());
            IOUtils.copy(process.getInputStream(), content);
            process.waitFor();
            int result = process.waitFor();
            if (result != 0) {
                throw new RuntimeException("Failed to run git upload-pack");
            }

            byte[] bytes = content.toByteArray();
            httpExchange.getResponseHeaders().add("content-type",
                    "application/x-git-upload-pack-advertisement");
            httpExchange.sendResponseHeaders(200, bytes.length);
            httpExchange.getResponseBody().write(bytes);
        }
    };
}

From source file:org.gradle.vcs.fixtures.GitHttpRepository.java

public void expectCloneSomething() {
    server.expect(server.get(backingRepo.getName() + "/info/refs", getRefsAction()));
    server.expect(server.post(backingRepo.getName() + "/git-upload-pack", new ErroringAction<HttpExchange>() {
        @Override//from www .  j a va2  s .  c o m
        protected void doExecute(HttpExchange httpExchange) throws Exception {
            httpExchange.getResponseHeaders().add("content-type", "application/x-git-upload-pack-result");
            httpExchange.sendResponseHeaders(200, 0);
            ProcessBuilder builder = new ProcessBuilder();
            final Process process = builder.command("git", "upload-pack", "--stateless-rpc",
                    backingRepo.getWorkTree().getAbsolutePath()).redirectErrorStream(true).start();

            InputStream instream = new GZIPInputStream(httpExchange.getRequestBody());
            ByteArrayOutputStream requestContent = new ByteArrayOutputStream();
            IOUtils.copy(instream, requestContent);
            byte[] bytes = requestContent.toByteArray();
            process.getOutputStream().write(bytes);
            process.getOutputStream().flush();

            IOUtils.copy(process.getInputStream(), httpExchange.getResponseBody());
            int result = process.waitFor();
            if (result != 0) {
                throw new RuntimeException("Failed to run git upload-pack");
            }
        }
    }));
}

From source file:org.sonatype.gshell.commands.vfs.EditCommand.java

private Object edit(final CommandContext context, final File localFile) throws Exception {
    assert context != null;
    assert localFile != null;

    log.debug("Editing file: {}", localFile);

    List<String> editorCmd = selectEditor();

    log.debug("Executing: {} {}", editorCmd, localFile);

    ProcessBuilder builder = new ProcessBuilder();
    for (String s : editorCmd) {
        builder.command().add(s);
    }// w  w w. j a v  a 2s  .com
    builder.command().add(localFile.getAbsolutePath());

    Process p = builder.start();

    log.debug("Waiting for process to exit...");
    int status = p.waitFor();
    log.info("Process exited w/status: {}", status);

    return status;
}