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:com.netflix.dynomitemanager.defaultimpl.StorageProcessManager.java

public void stop() throws IOException {
    logger.info("Stopping Storage process ....");
    List<String> command = Lists.newArrayList();
    if (!"root".equals(System.getProperty("user.name"))) {
        command.add(SUDO_STRING);//w w  w  .  j ava  2 s.  co  m
        command.add("-n");
        command.add("-E");
    }
    for (String param : config.getStorageStopScript().split(" ")) {
        if (StringUtils.isNotBlank(param))
            command.add(param);
    }
    ProcessBuilder stopCass = new ProcessBuilder(command);
    stopCass.directory(new File("/"));
    stopCass.redirectErrorStream(true);
    Process stopper = stopCass.start();

    sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS);
    try {
        int code = stopper.exitValue();
        if (code == 0) {
            logger.info("Storage process has been stopped");
            instanceState.setStorageProxyAlive(false);
        } else {
            logger.error("Unable to stop storage process. Error code: {}", code);
            logProcessOutput(stopper);
        }
    } catch (Exception e) {
        logger.warn("couldn't shut down Storage process correctly", e);
    }
}

From source file:com.github.ffremont.microservices.springboot.node.tasks.StartTask.java

/**
 * Syntaxe : java [-options] class [args...] (pour l'excution d'une classe)
 * ou java [-options] -jar jarfile [args...] (pour l'excution d'un fichier
 * JAR/*from www  . j  ava2  s.com*/
 *
 * @param task
 * @throws
 * com.github.ffremont.microservices.springboot.node.exceptions.FailStartedException
 * @throws
 * com.github.ffremont.microservices.springboot.node.exceptions.FileMsNotFoundException
 */
@Override
public void run(MicroServiceTask task) throws FailStartedException, FileMsNotFoundException {
    LOG.info("Dmarrage du micro service {}", task.getMs().getName());

    Path jar = helper.targetJarOf(task.getMs());
    Path workingDir = helper.targetDirOf(task.getMs());

    if (!Files.exists(jar)
            || !Files.exists(Paths.get(workingDir.toString(), InstallTask.CHECKSUM_FILE_NAME + ".txt"))) {
        throw new FileMsNotFoundException("Jar inexistant ou invalide");
    }

    String javaEx = this.javaExec.isEmpty() ? System.getProperty("java.home") + "/bin/java" : this.javaExec;

    ProcessBuilder ps = new ProcessBuilder(javaEx, "-jar", helper.targetJarOf(task.getMs()).toString(), "&");
    ps.directory(workingDir.toFile());

    try {
        Path consoleLog = Paths.get(workingDir.toString(), "console.log");
        ps.redirectOutput(consoleLog.toFile());
        ps.redirectError(consoleLog.toFile());

        LOG.info("Run de {}", ps.command().toString());
        ps.start();
    } catch (IOException ex) {
        throw new FailStartedException("Impossible de dmarrer le programme java : " + task.getMs().getId(),
                ex);
    }

    LOG.info("Micro service {} dmarr", task.getMs().getName());
}

From source file:com.temetra.vroomapi.RouteController.java

@RequestMapping(value = "/route", produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public JsonNode route(@RequestParam(value = "loc") String[] locs,
        @RequestParam(value = "startAtFirst", defaultValue = "true") boolean startAtFirst,
        @RequestParam(value = "endAtLast", defaultValue = "false") boolean endAtLast,
        @RequestParam(value = "includeGeometry", defaultValue = "false") boolean includeGeometry)
        throws Exception {
    long millis = System.currentTimeMillis();

    File vroomBinFile = new File(vroomBinary);
    if (!vroomBinFile.exists()) {
        log.error("Vroom binary file doesn't exist");
        throw new Exception("Vroom binary file doesn't exist");
    }// ww w.ja  v  a 2  s.c  o  m

    if (!vroomBinFile.canExecute()) {
        log.error("Cannot execute Vroom binary file");
        throw new Exception("Cannot execute Vroom binary file");
    }

    if (locs.length < 2) {
        log.error("Zero or one location sent");
        throw new Exception("Must send more than one location");
    }

    List<String> progArgs = new ArrayList<>();
    progArgs.add("./" + vroomBinFile.getName());
    if (startAtFirst) {
        progArgs.add("-s");
    }
    if (endAtLast) {
        progArgs.add("-e");
    }
    if (includeGeometry) {
        progArgs.add("-g");
    }

    progArgs.add("loc=" + Joiner.on("&loc=").join(locs) + "");
    log.info("Run (" + millis + "): " + Joiner.on(' ').join(progArgs));

    StringBuilder output = new StringBuilder();
    ProcessBuilder builder = new ProcessBuilder(progArgs);
    builder.directory(vroomBinFile.getParentFile());
    builder.redirectErrorStream(true);
    Process process = builder.start();

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
        String line;
        while ((line = reader.readLine()) != null) {
            output.append(line);
        }
        process.waitFor();
    }

    log.info("Output (" + millis + "): " + output.toString());
    return jsonMapper.readTree(output.toString());
}

From source file:de.phoenix.submission.SubmissionCompilerAndTest.java

@Override
public PhoenixSubmissionResult controlSubmission(TaskSubmission submission) {

    SubmissionTask task = new SubmissionTask();

    File dir = PhoenixApplication.submissionPipelineDir;
    List<String> commands = getCommands();

    // Check, if all necessary classes are submitted
    Set<String> classes = new HashSet<String>();
    for (Text text : submission.getTask().getTexts()) {
        classes.add(text.getTitle());/*from w w w  . j  av a  2 s. c o m*/
    }

    for (Text clazz : submission.getTexts()) {
        task.addClass(clazz.convert());
        classes.remove(clazz.getTitle());
    }

    // Some to implement classes are missing -> error
    if (!classes.isEmpty()) {
        return new PhoenixSubmissionResult(SubmissionStatus.MISSING_FILES,
                "Missing classes to implement/submit. Maybe you wrote the name of the class wrong? Missing Classes:\r\n"
                        + classes.toString());
    }

    if (submission.getTask().isAutomaticTest()) {
        for (TaskTest test : submission.getTask().getTaskTests()) {
            addTest(task, test);
        }
    }

    // TODO: Add libraries
    ProcessBuilder builder = new ProcessBuilder(commands);
    builder.directory(dir);

    File errorLog = new File(dir, "error.log");
    errorLog.delete();
    builder.redirectError(errorLog);

    try {
        Process process = builder.start();
        JSON_MAPPER.writeValue(process.getOutputStream(), task);
        process.getOutputStream().close();

        PhoenixSubmissionResult result = JSON_MAPPER.readValue(process.getInputStream(),
                PhoenixSubmissionResult.class);

        return result;
    } catch (Exception e) {
        DebugLog.log(e);
    }

    return new PhoenixSubmissionResult(SubmissionStatus.OK, "Fine");
}

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

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

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

    ProcessBuilder startStorage = new ProcessBuilder(command);

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

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

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

From source file:org.eclipse.acute.tests.AbstractAcuteTest.java

/**
 *
 * @param projectName the name that will be used as prefix for the project, and that will be used to find
 * the content of the project from the plugin "projects" folder
 * @throws IOException/*from   w  w w  .java 2 s  .co  m*/
 * @throws CoreException
 * @throws InterruptedException
 */
protected IProject provisionProject(String projectName)
        throws IOException, CoreException, InterruptedException {
    URL url = FileLocator.find(Platform.getBundle("org.eclipse.acute.tests"),
            Path.fromPortableString("projects/" + projectName), Collections.emptyMap());
    url = FileLocator.toFileURL(url);
    File folder = new File(url.getFile());
    if (folder != null && folder.exists()) {
        IProject project = ResourcesPlugin.getWorkspace().getRoot()
                .getProject(projectName + "_" + getClass().getName() + "_" + System.currentTimeMillis());
        project.create(new NullProgressMonitor());
        this.provisionedProjects.put(projectName, project);
        FileUtils.copyDirectory(folder, project.getLocation().toFile());
        // workaround for https://github.com/OmniSharp/omnisharp-node-client/issues/265
        ProcessBuilder dotnetRestoreBuilder = new ProcessBuilder(AcutePlugin.getDotnetCommand(), "restore");
        dotnetRestoreBuilder.directory(project.getLocation().toFile());
        assertEquals(0, dotnetRestoreBuilder.start().waitFor());
        project.open(new NullProgressMonitor());
        project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
        return project;
    } else {
        return null;
    }
}

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);/*from   w  ww.j av a 2  s. c  o  m*/
    pb.directory(execDir);
    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.sonar.it.android.AndroidTest.java

@Test
@Ignore("Deactivated awaiting resolution of http://jira.sonarsource.com/browse/JC-145")
public void should_run_lint_after_export_and_import_results() throws Exception {
    assumeTrue(AndroidTestSuite.isAtLeastPlugin1_1());
    String response = exportProfile("it-profile");
    File baseDir = new File("projects/SonarAndroidSample/app");
    FileUtils.write(new File(baseDir, "lint.xml"), response, Charsets.UTF_8);
    ProcessBuilder pb = new ProcessBuilder("CMD", "/C", "gradle lint");
    pb.directory(baseDir);
    pb.inheritIO();/*w  w w.ja v a2  s.com*/
    Process gradleProcess = pb.start();
    int exitStatus = gradleProcess.waitFor();
    if (exitStatus != 0) {
        fail("Failed to execute gradle lint.");
    }
    SonarRunner analysis = SonarRunner.create().setProfile("it-profile").setProjectName("SonarAndroidSample2")
            .setProjectKey("SonarAndroidSample2").setProjectVersion("1.0").setSourceDirs("src/main")
            .setProjectDir(baseDir).setProperty("sonar.android.lint.report", "lint-report-build.xml")
            .setProperty("sonar.import_unknown_files", "true");
    orchestrator.executeBuild(analysis);
    Resource project = sonar.find(ResourceQuery.createForMetrics("SonarAndroidSample2", "violations"));

    assertThat(project.getMeasureIntValue("violations")).isEqualTo(2);

}

From source file:org.xwiki.formula.internal.NativeFormulaRenderer.java

/**
 * Execute a system command.//from  w ww  .j  av  a 2  s. c  o  m
 * 
 * @param commandLine the command and its arguments
 * @param cwd the directory to use as the current working directory for the executed process
 * @return {@code true} if the command succeeded (return code 0), {@code false} otherwise
 * @throws IOException if the process failed to start
 */
private boolean executeCommand(String[] commandLine, File cwd) throws IOException {
    List<String> commandList = new Vector<String>(commandLine.length);
    Collections.addAll(commandList, commandLine);

    ProcessBuilder processBuilder = new ProcessBuilder(commandList);
    processBuilder.directory(cwd);
    Process process = processBuilder.start();
    IOUtils.copy(process.getInputStream(), new NullOutputStream());

    try {
        process.waitFor();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    if (process.exitValue() != 0) {
        LOGGER.debug("Error generating image: " + IOUtils.toString(process.getErrorStream()));
    }

    return process.exitValue() == 0;
}

From source file:com.blackducksoftware.integration.hub.docker.executor.Executor.java

public String[] executeCommand(final String commandString)
        throws IOException, InterruptedException, HubIntegrationException {
    final List<String> commandStringList = Arrays.asList(commandString.split(" "));
    final ProcessBuilder builder = new ProcessBuilder();
    builder.command(commandStringList.toArray(new String[commandStringList.size()]));
    builder.directory(new File("."));
    final Process process = builder.start();
    final boolean finished = process.waitFor(this.commandTimeout, TimeUnit.MILLISECONDS);
    if (!finished) {
        throw new HubIntegrationException(String.format(
                "Execution of command %s timed out (timeout: %d milliseconds)", commandString, commandTimeout));
    }/*from  w ww. j  a  va2  s.  c o  m*/
    final int errCode = process.exitValue();
    if (errCode == 0) {
        logger.debug(String.format("Execution of command: %s: Succeeded", commandString));
    } else {
        throw new HubIntegrationException(
                String.format("Execution of command: %s: Error code: %d", commandString, errCode));
    }
    final InputStream inputStream = process.getInputStream();
    final String outputString = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
    logger.debug(String.format("Command output:/n%s", outputString));
    return outputString.split(System.lineSeparator());
}