Example usage for java.lang ProcessBuilder ProcessBuilder

List of usage examples for java.lang ProcessBuilder ProcessBuilder

Introduction

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

Prototype

public ProcessBuilder(String... command) 

Source Link

Document

Constructs a process builder with the specified operating system program and arguments.

Usage

From source file:fr.amap.lidar.PtgScanConversion.java

public void toLaz(SimpleScan scan, File outputDirectory, boolean laz, boolean exportIntensity)
        throws IOException, InterruptedException, UnsupportedOperationException, Exception {

    /***Convert rxp to txt***/

    Mat4D transfMatrix = Mat4D.multiply(scan.sopMatrix, scan.popMatrix);

    Mat3D rotation = new Mat3D();
    rotation.mat = new double[] { transfMatrix.mat[0], transfMatrix.mat[1], transfMatrix.mat[2],
            transfMatrix.mat[4], transfMatrix.mat[5], transfMatrix.mat[6], transfMatrix.mat[8],
            transfMatrix.mat[9], transfMatrix.mat[10] };

    File outputTxtFile = new File(
            outputDirectory.getAbsolutePath() + File.separator + scan.file.getName() + ".txt");

    try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputTxtFile))) {
        PTGScan ptgScan = new PTGScan();
        ptgScan.openScanFile(scan.file);

        LPointShotExtractor shots = new LPointShotExtractor(ptgScan);
        Iterator<LShot> iterator = shots.iterator();

        while (iterator.hasNext()) {

            LShot shot = iterator.next();
            shot.direction.normalize();/*from   w w w.  ja v  a  2s.c  o m*/

            Vec4D origin = Mat4D.multiply(transfMatrix,
                    new Vec4D(shot.origin.x, shot.origin.y, shot.origin.z, 1.0d));
            Vec3D direction = Mat3D.multiply(rotation,
                    new Vec3D(shot.direction.x, shot.direction.y, shot.direction.z));

            for (int i = 0; i < shot.ranges.length; i++) {

                double x = origin.x + direction.x * shot.ranges[i];
                double y = origin.y + direction.y * shot.ranges[i];
                double z = origin.z + direction.z * shot.ranges[i];

                if (exportIntensity) {
                    writer.write(x + " " + y + " " + z + " " + (i + 1) + " " + shot.ranges.length + " "
                            + shot.point.intensity + "\n");
                } else {
                    writer.write(x + " " + y + " " + z + " " + (i + 1) + " " + shot.ranges.length + "\n");
                }

            }

        }
    }

    /***Convert txt to laz***/
    String propertyValue = System.getProperty("user.dir");
    System.out.println("Current jar directory : " + propertyValue);

    String txtToLasPath;

    String osName = getOSName();

    switch (osName) {
    case "windows":
    case "linux":
        txtToLasPath = propertyValue + File.separator + "LASTools" + File.separator + osName + File.separator
                + "txt2las";
        break;
    default:
        throw new UnsupportedOperationException("Os architecture not supported");
    }

    if (osName.equals("windows")) {
        txtToLasPath = txtToLasPath + ".exe";
    }

    File outputLazFile;
    if (laz) {
        outputLazFile = new File(
                outputDirectory.getAbsolutePath() + File.separator + scan.file.getName() + ".laz");
    } else {
        outputLazFile = new File(
                outputDirectory.getAbsolutePath() + File.separator + scan.file.getName() + ".las");
    }

    String[] commandLine;

    if (exportIntensity) {
        commandLine = new String[] { txtToLasPath, "-i", outputTxtFile.getAbsolutePath(), "-o",
                outputLazFile.getAbsolutePath(), "-parse", "xyzrni" };
    } else {
        commandLine = new String[] { txtToLasPath, "-i", outputTxtFile.getAbsolutePath(), "-o",
                outputLazFile.getAbsolutePath(), "-parse", "xyzrn" };
    }

    System.out.println("Command line : "
            + ArrayUtils.toString(commandLine).replaceAll(",", " ").replaceAll("}", "").replace("{", ""));

    ProcessBuilder pb = new ProcessBuilder(commandLine);
    pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
    pb.redirectError(ProcessBuilder.Redirect.INHERIT);

    Process p = pb.start();

    p.waitFor();

}

From source file:edu.pitt.dbmi.ccd.queue.task.ScheduledAlgorithJob.java

private void killJob(Long queueId) {
    JobQueueInfo jobQueueInfo = jobQueueInfoService.findOne(queueId);
    if (jobQueueInfo.getStatus() == 0) {
        LOGGER.info("Delete Job ID by user from queue: " + queueId);
        jobQueueInfoService.deleteJobById(queueId);
    } else {//  w  w  w.j a v a 2s. co  m
        Long pid = jobQueueInfo.getPid();
        if (pid == null) {
            LOGGER.info("Delete Job ID by user from queue: " + queueId);
            jobQueueInfoService.deleteJobById(queueId);
        } else {
            Platform platform = Platform.detect();
            System.out.println(
                    "Processes.isProcessRunning(platform, pid):" + Processes.isProcessRunning(platform, pid));
            if (Processes.isProcessRunning(platform, pid)) {
                /*
                 * ISupportConfig support = null; IStreamProcessor output =
                 * null;
                 */
                List<String> commands = new LinkedList<>();
                if (platform == Platform.Windows) {
                    // return Processes.tryKillProcess(support, platform,
                    // output, pid.intValue());
                    commands.add("taskkill");
                    commands.add("/pid");
                    commands.add(String.valueOf(pid));
                    commands.add("/f");
                    commands.add("/t");
                } else {
                    // return Processes.killProcess(support, platform,
                    // output, pid.intValue());
                    commands.add("kill");
                    commands.add("-9");
                    commands.add(String.valueOf(pid));
                }
                LOGGER.info("Kill Job Queue Id: " + jobQueueInfo.getId());
                jobQueueInfo.setStatus(2);
                jobQueueInfoService.saveJobIntoQueue(jobQueueInfo);
                ProcessBuilder pb = new ProcessBuilder(commands);
                try {
                    pb.start();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    LOGGER.error("Request to kill an algorithm job did not run successfully.", e);
                }
            } else {
                LOGGER.info("Job does not exist, delete Job ID from queue: " + queueId);
                jobQueueInfoService.deleteJobById(queueId);
            }
        }
    }
}

From source file:com.ebiznext.flume.source.TestMultiLineExecSource.java

private static List<String> exec(String command) throws Exception {
    String[] commandArgs = command.split("\\s+");
    Process process = new ProcessBuilder(commandArgs).start();
    BufferedReader reader = null;
    try {/*from  ww  w.  ja  v  a 2  s .c  om*/
        reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        List<String> result = Lists.newArrayList();
        String line;
        while ((line = reader.readLine()) != null) {
            result.add(line);
        }
        return result;
    } finally {
        process.destroy();
        if (reader != null) {
            reader.close();
        }
        int exit = process.waitFor();
        if (exit != 0) {
            throw new IllegalStateException("Command [" + command + "] exited with " + exit);
        }
    }
}

From source file:com.netflix.genie.core.jobs.workflow.impl.JobKickoffTask.java

/**
 * {@inheritDoc}//from w w w. j  a  v a  2  s . com
 */
@Override
public void executeTask(@NotNull final Map<String, Object> context) throws GenieException, IOException {
    final long start = System.nanoTime();
    try {
        final JobExecutionEnvironment jobExecEnv = (JobExecutionEnvironment) context
                .get(JobConstants.JOB_EXECUTION_ENV_KEY);
        final String jobWorkingDirectory = jobExecEnv.getJobWorkingDir().getCanonicalPath();
        final JobRequest jobRequest = jobExecEnv.getJobRequest();
        final String user = jobRequest.getUser();
        final Writer writer = (Writer) context.get(JobConstants.WRITER_KEY);
        final String jobId = jobRequest.getId()
                .orElseThrow(() -> new GeniePreconditionException("No job id found. Unable to continue."));
        log.info("Starting Job Kickoff Task for job {}", jobId);

        // At this point all contents are written to the run script and we call an explicit flush and close to write
        // the contents to the file before we execute it.
        try {
            writer.flush();
            writer.close();
        } catch (IOException e) {
            throw new GenieServerException("Failed to execute job with exception." + e);
        }
        // Create user, if enabled
        if (isUserCreationEnabled) {
            createUser(user, jobRequest.getGroup().orElse(null));
        }
        // Set the ownership to the user and run as the user, if enabled
        final List<String> command = new ArrayList<>();
        if (isRunAsUserEnabled) {
            changeOwnershipOfDirectory(jobWorkingDirectory, user);

            // This is needed because the genie.log file is still generated as the user running Genie system.
            makeDirGroupWritable(jobWorkingDirectory + "/genie/logs");
            command.add("sudo");
            command.add("-u");
            command.add(user);
        }

        // If the OS is linux use setsid to launch the process so that the entire process tree
        // is launched in process group id which is the same as the pid of the parent process
        if (SystemUtils.IS_OS_LINUX) {
            command.add("setsid");
        }

        final String runScript = jobWorkingDirectory + JobConstants.FILE_PATH_DELIMITER
                + JobConstants.GENIE_JOB_LAUNCHER_SCRIPT;
        command.add(runScript);

        // Cannot convert to executor because it does not provide an api to get process id.
        final ProcessBuilder pb = new ProcessBuilder(command).directory(jobExecEnv.getJobWorkingDir())
                .redirectOutput(new File(jobExecEnv.getJobWorkingDir() + JobConstants.GENIE_LOG_PATH))
                .redirectError(new File(jobExecEnv.getJobWorkingDir() + JobConstants.GENIE_LOG_PATH));

        //
        // Check if file can be executed. This is to fix issue where execution of the run script fails because
        // the file may be used by some other program
        //
        canExecute(runScript);
        try {
            final Process process = pb.start();
            final int processId = this.getProcessId(process);
            final Calendar calendar = Calendar.getInstance(UTC);
            calendar.add(Calendar.SECOND, jobRequest.getTimeout().orElse(JobRequest.DEFAULT_TIMEOUT_DURATION));
            final JobExecution jobExecution = new JobExecution.Builder(this.hostname).withId(jobId)
                    .withProcessId(processId).withCheckDelay(jobExecEnv.getCommand().getCheckDelay())
                    .withTimeout(calendar.getTime()).withMemory(jobExecEnv.getMemory()).build();
            context.put(JobConstants.JOB_EXECUTION_DTO_KEY, jobExecution);
        } catch (final IOException ie) {
            throw new GenieServerException("Unable to start command " + String.valueOf(command), ie);
        }
        log.info("Finished Job Kickoff Task for job {}", jobId);
    } finally {
        final long finish = System.nanoTime();
        this.timer.record(finish - start, TimeUnit.NANOSECONDS);
    }
}

From source file:com.frostwire.gui.updates.InstallerUpdater.java

private void showUpdateMessage() {
    GUIMediator.safeInvokeLater(new Runnable() {
        public void run() {
            if (_executableFile == null) {
                return;
            }/*from  w w w  . ja va  2  s.  com*/

            int result = JOptionPane.showConfirmDialog(null, _updateMessage.getMessageInstallerReady(),
                    I18n.tr("Update"), JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE);

            if (result == JOptionPane.YES_OPTION) {
                try {
                    if (OSUtils.isWindows()) {
                        String[] commands = new String[] { "CMD.EXE", "/C", _executableFile.getAbsolutePath() };

                        ProcessBuilder pbuilder = new ProcessBuilder(commands);
                        pbuilder.start();
                    } else if (OSUtils.isLinux() && OSUtils.isUbuntu()) {
                        String[] commands = new String[] { "gdebi-gtk", _executableFile.getAbsolutePath() };

                        ProcessBuilder pbuilder = new ProcessBuilder(commands);
                        pbuilder.start();
                    } else if (OSUtils.isMacOSX()) {
                        String[] mountCommand = new String[] { "hdiutil", "attach",
                                _executableFile.getAbsolutePath() };

                        String[] finderShowCommand = new String[] { "open",
                                "/Volumes/" + FilenameUtils.getBaseName(_executableFile.getName()) };

                        ProcessBuilder pbuilder = new ProcessBuilder(mountCommand);
                        Process mountingProcess = pbuilder.start();

                        mountingProcess.waitFor();

                        pbuilder = new ProcessBuilder(finderShowCommand);
                        pbuilder.start();
                    }

                    GUIMediator.shutdown();
                } catch (Throwable e) {
                    LOG.error("Unable to launch new installer", e);
                }
            }
        }
    });
}

From source file:hydrograph.ui.perspective.ApplicationWorkbenchWindowAdvisor.java

private void serviceInitiator(Properties properties) throws IOException {
    if (OSValidator.isWindows()) {
        //Updated the java classpath to include the dependent jars
        String path = "";
        try {//from ww  w .j a  va  2 s .  c o  m
            path = Paths.get(Platform.getInstallLocation().getURL().toURI()).toString() + "\\";
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            logger.error(e.getMessage());
        }

        logger.debug(Platform.getInstallLocation().getURL().getPath());
        String command = "java -cp \"" + getInstallationConfigPath().trim() + ";" + path
                + properties.getProperty(SERVICE_DEPENDENCIES) + ";" + path
                + properties.getProperty(SERVICE_JAR) + "\" " + properties.getProperty(DRIVER_CLASS);
        logger.debug("Starting server with command - " + command);
        ProcessBuilder builder = new ProcessBuilder(new String[] { "cmd", "/c", command });
        builder.start();
    } else if (OSValidator.isMac()) {
        logger.debug("On Mac Operating System....");
        //Updated the java classpath to include the dependent jars
        String command = "java -cp " + getInstallationConfigPath().trim() + ":"
                + Platform.getInstallLocation().getURL().getPath() + properties.getProperty(SERVICE_JAR) + ":"
                + Platform.getInstallLocation().getURL().getPath()
                + properties.getProperty(SERVICE_DEPENDENCIES) + " " + properties.getProperty(DRIVER_CLASS);
        logger.debug("command{}", command);
        ProcessBuilder builder = new ProcessBuilder(new String[] { "bash", "-c", command });
        builder.start();

    } else if (OSValidator.isUnix()) {
        new ProcessBuilder(new String[] { "java", "-jar", properties.getProperty(SERVICE_JAR) }).start();
    } else if (OSValidator.isSolaris()) {
    }
}

From source file:com.netflix.genie.server.jobmanager.impl.JobManagerImpl.java

/**
 * {@inheritDoc}//from   www  .jav  a2 s .co m
 */
@Override
public void launch() throws GenieException {
    LOG.info("called");
    if (!this.initCalled) {
        throw new GeniePreconditionException("Init wasn't called. Unable to continue.");
    }

    // create the ProcessBuilder for this process
    final List<String> processArgs = this.createBaseProcessArguments();
    processArgs.addAll(Arrays.asList(StringUtil.splitCmdLine(this.job.getCommandArgs())));
    final ProcessBuilder processBuilder = new ProcessBuilder(processArgs);

    // construct the environment variables
    this.setupCommonProcess(processBuilder);

    // Launch the actual process
    this.launchProcess(processBuilder, 5000);
}

From source file:com.cloud.utils.script.Script.java

public String execute(OutputInterpreter interpreter) {
    String[] command = _command.toArray(new String[_command.size()]);

    if (_logger.isDebugEnabled()) {
        _logger.debug("Executing: " + buildCommandLine(command));
    }// ww  w  .j a  v  a2 s  .c o  m

    try {
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.redirectErrorStream(true);
        if (_workDir != null)
            pb.directory(new File(_workDir));

        _process = pb.start();
        if (_process == null) {
            _logger.warn("Unable to execute: " + buildCommandLine(command));
            return "Unable to execute the command: " + command[0];
        }

        BufferedReader ir = new BufferedReader(new InputStreamReader(_process.getInputStream()));

        _thread = Thread.currentThread();
        ScheduledFuture<String> future = null;
        if (_timeout > 0) {
            future = s_executors.schedule(this, _timeout, TimeUnit.MILLISECONDS);
        }

        Task task = null;
        if (interpreter != null && interpreter.drain()) {
            task = new Task(interpreter, ir);
            s_executors.execute(task);
        }

        while (true) {
            try {
                if (_process.waitFor() == 0) {
                    _logger.debug("Execution is successful.");
                    if (interpreter != null) {
                        return interpreter.drain() ? task.getResult() : interpreter.interpret(ir);
                    } else {
                        // null return exitValue apparently
                        return String.valueOf(_process.exitValue());
                    }
                } else {
                    break;
                }
            } catch (InterruptedException e) {
                if (!_isTimeOut) {
                    /*
                     * This is not timeout, we are interrupted by others,
                     * continue
                     */
                    _logger.debug("We are interrupted but it's not a timeout, just continue");
                    continue;
                }

                TimedOutLogger log = new TimedOutLogger(_process);
                Task timedoutTask = new Task(log, ir);

                timedoutTask.run();
                if (!_passwordCommand) {
                    _logger.warn("Timed out: " + buildCommandLine(command) + ".  Output is: "
                            + timedoutTask.getResult());
                } else {
                    _logger.warn("Timed out: " + buildCommandLine(command));
                }

                return ERR_TIMEOUT;
            } finally {
                if (future != null) {
                    future.cancel(false);
                }
                Thread.interrupted();
            }
        }

        _logger.debug("Exit value is " + _process.exitValue());

        BufferedReader reader = new BufferedReader(new InputStreamReader(_process.getInputStream()), 128);

        String error;
        if (interpreter != null) {
            error = interpreter.processError(reader);
        } else {
            error = String.valueOf(_process.exitValue());
        }

        if (_logger.isDebugEnabled()) {
            _logger.debug(error);
        }
        return error;
    } catch (SecurityException ex) {
        _logger.warn("Security Exception....not running as root?", ex);
        return stackTraceAsString(ex);
    } catch (Exception ex) {
        _logger.warn("Exception: " + buildCommandLine(command), ex);
        return stackTraceAsString(ex);
    } finally {
        if (_process != null) {
            IOUtils.closeQuietly(_process.getErrorStream());
            IOUtils.closeQuietly(_process.getOutputStream());
            IOUtils.closeQuietly(_process.getInputStream());
            _process.destroy();
        }
    }
}

From source file:net.solarnetwork.node.control.ping.HttpRequesterJob.java

private void handleOSCommand(String command) {
    if (command == null) {
        return;/*from ww w .  j  a  v a 2  s.  c  o  m*/
    }
    ProcessBuilder pb = new ProcessBuilder(command.split("\\s+"));
    try {
        Process pr = pb.start();
        logInputStream(pr.getInputStream(), false);
        logInputStream(pr.getErrorStream(), true);
        pr.waitFor();
        if (pr.exitValue() == 0) {
            log.debug("Command [{}] executed", command);
            handleCommandSleep();
        } else {
            log.error("Error executing [{}], exit status: {}", command, pr.exitValue());
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.netflix.genie.web.jobs.workflow.impl.JobKickoffTask.java

/**
 * {@inheritDoc}// w ww . j a  v a 2 s  .  co m
 */
@Override
public void executeTask(@NotNull final Map<String, Object> context) throws GenieException, IOException {
    final long start = System.nanoTime();
    final Set<Tag> tags = Sets.newHashSet();
    try {
        final JobExecutionEnvironment jobExecEnv = (JobExecutionEnvironment) context
                .get(JobConstants.JOB_EXECUTION_ENV_KEY);
        final String jobWorkingDirectory = jobExecEnv.getJobWorkingDir().getCanonicalPath();
        final JobRequest jobRequest = jobExecEnv.getJobRequest();
        final String user = jobRequest.getUser();
        final Writer writer = (Writer) context.get(JobConstants.WRITER_KEY);
        final String jobId = jobRequest.getId()
                .orElseThrow(() -> new GeniePreconditionException("No job id found. Unable to continue."));
        log.info("Starting Job Kickoff Task for job {}", jobId);

        // At this point all contents are written to the run script and we call an explicit flush and close to write
        // the contents to the file before we execute it.
        try {
            writer.flush();
            writer.close();
        } catch (IOException e) {
            throw new GenieServerException("Failed to execute job", e);
        }
        // Create user, if enabled
        if (isUserCreationEnabled) {
            createUser(user, jobRequest.getGroup().orElse(null));
        }
        final List<String> command = new ArrayList<>();

        // If the OS is linux use setsid to launch the process so that the entire process tree
        // is launched in process group id which is the same as the pid of the parent process
        if (SystemUtils.IS_OS_LINUX) {
            command.add("setsid");
        }

        // Set the ownership to the user and run as the user, if enabled
        if (isRunAsUserEnabled) {
            changeOwnershipOfDirectory(jobWorkingDirectory, user);

            // This is needed because the genie.log file is still generated as the user running Genie system.
            makeDirGroupWritable(jobWorkingDirectory + "/genie/logs");
            command.add("sudo");
            command.add("-u");
            command.add(user);
        }

        final String runScript = jobWorkingDirectory + JobConstants.FILE_PATH_DELIMITER
                + JobConstants.GENIE_JOB_LAUNCHER_SCRIPT;
        command.add(runScript);

        // Cannot convert to executor because it does not provide an api to get process id.
        final ProcessBuilder pb = new ProcessBuilder(command).directory(jobExecEnv.getJobWorkingDir())
                .redirectOutput(new File(jobExecEnv.getJobWorkingDir() + JobConstants.GENIE_LOG_PATH))
                .redirectError(new File(jobExecEnv.getJobWorkingDir() + JobConstants.GENIE_LOG_PATH));

        //
        // Check if file can be executed. This is to fix issue where execution of the run script fails because
        // the file may be used by some other program
        //
        canExecute(runScript);
        try {
            final Process process = pb.start();
            final int processId = this.getProcessId(process);
            final Instant timeout = Instant.now().plus(
                    jobRequest.getTimeout().orElse(JobRequest.DEFAULT_TIMEOUT_DURATION), ChronoUnit.SECONDS);
            final JobExecution jobExecution = new JobExecution.Builder(this.hostname).withId(jobId)
                    .withProcessId(processId).withCheckDelay(jobExecEnv.getCommand().getCheckDelay())
                    .withTimeout(timeout).withMemory(jobExecEnv.getMemory()).build();
            context.put(JobConstants.JOB_EXECUTION_DTO_KEY, jobExecution);
        } catch (final IOException ie) {
            throw new GenieServerException("Unable to start command " + String.valueOf(command), ie);
        }
        log.info("Finished Job Kickoff Task for job {}", jobId);
        MetricsUtils.addSuccessTags(tags);
    } catch (final Throwable t) {
        MetricsUtils.addFailureTagsWithException(tags, t);
        throw t;
    } finally {
        this.getRegistry().timer(JOB_KICKOFF_TASK_TIMER_NAME, tags).record(System.nanoTime() - start,
                TimeUnit.NANOSECONDS);
    }
}