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:ai.grakn.graql.GraqlShell.java

/**
 * load the user's preferred editor to edit a query
 * @return the string written to the editor
 *//*www.j  ava  2s.  co m*/
private String runEditor() throws IOException {
    // Get preferred editor
    Map<String, String> env = System.getenv();
    String editor = Optional.ofNullable(env.get("EDITOR")).orElse(DEFAULT_EDITOR);

    // Run the editor, pipe input into and out of tty so we can provide the input/output to the editor via Graql
    ProcessBuilder builder = new ProcessBuilder("/bin/bash", "-c",
            editor + " </dev/tty >/dev/tty " + tempFile.getAbsolutePath());

    // Wait for user to finish editing
    try {
        builder.start().waitFor();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

    return String.join("\n", Files.readAllLines(tempFile.toPath()));
}

From source file:io.stallion.utils.ProcessHelper.java

public CommandResult run() {

    String cmdString = String.join(" ", args);
    System.out.printf("----- Execute command: %s ----\n", cmdString);
    ProcessBuilder pb = new ProcessBuilder(args);
    if (!empty(directory)) {
        pb.directory(new File(directory));
    }//from w  w w.j a  va2s  . c o  m
    Map<String, String> env = pb.environment();
    CommandResult commandResult = new CommandResult();
    Process p = null;
    try {
        if (showDotsWhileWaiting == null) {
            showDotsWhileWaiting = !inheritIO;
        }

        if (inheritIO) {
            p = pb.inheritIO().start();
        } else {
            p = pb.start();
        }

        BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        BufferedReader out = new BufferedReader(new InputStreamReader(p.getInputStream()));

        if (!empty(input)) {
            Log.info("Writing input to pipe {0}", input);
            IOUtils.write(input, p.getOutputStream(), UTF8);
            p.getOutputStream().flush();
        }

        while (p.isAlive()) {
            p.waitFor(1000, TimeUnit.MILLISECONDS);
            if (showDotsWhileWaiting == true) {
                System.out.printf(".");
            }
        }

        commandResult.setErr(IOUtils.toString(err));
        commandResult.setOut(IOUtils.toString(out));
        commandResult.setCode(p.exitValue());

        if (commandResult.succeeded()) {
            info("\n---- Command execution completed ----\n");
        } else {
            Log.warn("Command failed with error code: " + commandResult.getCode());
        }

    } catch (IOException e) {
        Log.exception(e, "Error running command: " + cmdString);
        commandResult.setCode(999);
        commandResult.setEx(e);
    } catch (InterruptedException e) {
        Log.exception(e, "Error running command: " + cmdString);
        commandResult.setCode(998);
        commandResult.setEx(e);
    }
    Log.fine(
            "\n\n----Start shell command result----:\nCommand:  {0}\nexitCode: {1}\n----------STDOUT---------\n{2}\n\n----------STDERR--------\n{3}\n\n----end shell command result----\n",
            cmdString, commandResult.getCode(), commandResult.getOut(), commandResult.getErr());
    return commandResult;
}

From source file:jp.co.tis.gsp.tools.dba.dialect.OracleDialect.java

@Override
public void importSchema(ImportParams params) throws MojoExecutionException {
    BufferedReader reader = null;

    try {/*from w  w w .ja va2  s . c  o  m*/
        File dumpFile = params.getDumpFile();

        if (!dumpFile.exists())
            throw new MojoExecutionException(dumpFile.getName() + " is not found?");

        String user = params.getAdminUser();
        String password = params.getAdminPassword();
        String schema = params.getSchema();

        createDirectory(user, password, dumpFile.getParentFile());

        // Oracle?????
        dropAllObjects(user, password, schema);

        ProcessBuilder pb = new ProcessBuilder("impdp", user + "/" + password, "directory=exp_dir",
                "dumpfile=" + dumpFile.getName(), "schemas=" + schema, "nologfile=y", "exclude=user");
        pb.redirectErrorStream(true);
        Process process = pb.start();
        Charset terminalCharset = System.getProperty("os.name").toLowerCase().contains("windows")
                ? Charset.forName("Shift_JIS")
                : Charset.forName("UTF-8");

        reader = new BufferedReader(new InputStreamReader(process.getInputStream(), terminalCharset));
        //???????????????
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }

        process.waitFor();
        if (process.exitValue() != 0) {
            throw new MojoExecutionException("oracle import error");
        }
        process.destroy();
    } catch (Exception e) {
        throw new MojoExecutionException("oracle import", e);
    } finally {
        IOUtils.closeQuietly(reader);
    }

}

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

/**
 * Actually launch a process based on the process builder.
 *
 * @param processBuilder The process builder to use.
 * @param sleepTime      The time to sleep between checks of the job process status
 * @throws GenieException If any issue happens launching the process.
 */// ww w . j av  a2s. co m
protected void launchProcess(final ProcessBuilder processBuilder, final int sleepTime) throws GenieException {
    try {
        // launch job, and get process handle
        final Process proc = processBuilder.start();
        final int pid = this.getProcessId(proc);
        this.jobService.setProcessIdForJob(this.job.getId(), pid);

        // set off monitor thread for the job
        this.jobMonitor.setJob(this.job);
        this.jobMonitor.setProcess(proc);
        this.jobMonitor.setWorkingDir(this.jobDir);
        this.jobMonitor.setThreadSleepTime(sleepTime);
        this.jobMonitorThread.start();
        this.jobService.setJobStatus(this.job.getId(), JobStatus.RUNNING, "Job is running");
        LOG.info("Successfully launched the job with PID = " + pid);
    } catch (final IOException e) {
        final String msg = "Failed to launch the job";
        LOG.error(msg, e);
        this.jobService.setJobStatus(this.job.getId(), JobStatus.FAILED, msg);
        throw new GenieServerException(msg, e);
    }
}

From source file:com.datasalt.pangool.solr.SolrRecordWriter.java

private Path findSolrConfig(Configuration conf) throws IOException {
    Path solrHome = null;/*ww w  .j  a v a  2s.  co  m*/

    // we added these lines to make this patch work on Hadoop 0.20.2
    FileSystem localFs = FileSystem.getLocal(conf);
    if (FileSystem.get(conf).equals(localFs)) {
        return new Path(localSolrHome);
    }
    // end-of-addition
    Path[] localArchives = DistributedCache.getLocalCacheArchives(conf);

    if (localArchives.length == 0) {
        throw new IOException(String.format("No local cache archives, where is %s", zipName));
    }
    for (Path unpackedDir : localArchives) {
        // Only logged if debugging
        if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Examining unpack directory %s for %s", unpackedDir, zipName));

            ProcessBuilder lsCmd = new ProcessBuilder(
                    new String[] { "/bin/ls", "-lR", unpackedDir.toString() });
            lsCmd.redirectErrorStream();
            Process ls = lsCmd.start();
            try {
                byte[] buf = new byte[16 * 1024];
                InputStream all = ls.getInputStream();
                int count;
                while ((count = all.read(buf)) > 0) {
                    System.err.write(buf, 0, count);
                }
            } catch (IOException ignore) {
            }
            System.err.format("Exit value is %d%n", ls.exitValue());
        }
        if (unpackedDir.getName().equals(zipName)) {

            solrHome = unpackedDir;
            break;
        }
    }
    return solrHome;
}

From source file:de.uni_luebeck.inb.knowarc.usecases.invocation.local.LocalUseCaseInvocation.java

private String setOneBinaryInput(ReferenceService referenceService, T2Reference t2Reference, ScriptInput input,
        String targetSuffix) throws InvocationException {

    if (input.isFile() || input.isTempFile()) {
        // Try to get it as a file
        String target = tempDir.getAbsolutePath() + "/" + targetSuffix;
        FileReference fileRef = getAsFileReference(referenceService, t2Reference);
        if (fileRef != null) {

            if (!input.isForceCopy()) {
                if (linkCommand != null) {
                    String source = fileRef.getFile().getAbsolutePath();
                    String actualLinkCommand = getActualOsCommand(linkCommand, source, targetSuffix, target);
                    logger.info("Link command is " + actualLinkCommand);
                    String[] splitCmds = actualLinkCommand.split(" ");
                    ProcessBuilder builder = new ProcessBuilder(splitCmds);
                    builder.directory(tempDir);
                    try {
                        int code = builder.start().waitFor();
                        if (code == 0) {
                            return target;
                        } else {
                            logger.error("Link command gave errorcode: " + code);
                        }/*from   w  w w . j  av a  2 s .c o m*/

                    } catch (InterruptedException e) {
                        // go through
                    } catch (IOException e) {
                        // go through
                    }

                }
            }
        }

        InputStream is = null;
        OutputStream os = null;
        is = getAsStream(referenceService, t2Reference);

        try {
            os = new FileOutputStream(target);
        } catch (FileNotFoundException e) {
            throw new InvocationException(e);
        }

        try {
            IOUtils.copyLarge(is, os);
        } catch (IOException e) {
            throw new InvocationException(e);
        }
        try {
            is.close();
            os.close();
        } catch (IOException e) {
            throw new InvocationException(e);
        }
        return target;
    } else {
        String value = (String) referenceService.renderIdentifier(t2Reference, String.class, this.getContext());
        return value;
    }
}

From source file:com.google.dart.tools.debug.core.configs.DartServerLaunchConfigurationDelegate.java

protected void launchVM(ILaunch launch, DartLaunchConfigWrapper launchConfig, boolean enableDebugging,
        IProgressMonitor monitor) throws CoreException {
    // Usage: dart [options] script.dart [arguments]

    File currentWorkingDirectory = getCurrentWorkingDirectory(launchConfig);

    String scriptPath = launchConfig.getApplicationName();

    scriptPath = translateToFilePath(currentWorkingDirectory, scriptPath);

    String vmExecPath = "";

    if (DartSdkManager.getManager().hasSdk()) {
        File vmExec = DartSdkManager.getManager().getSdk().getVmExecutable();

        if (vmExec != null) {
            vmExecPath = vmExec.getAbsolutePath().toString();
        }//from ww w  .  j  a va 2s. co  m
    } else {
        vmExecPath = DartDebugCorePlugin.getPlugin().getDartVmExecutablePath();
    }

    if (vmExecPath.length() == 0) {
        throw new CoreException(
                DartDebugCorePlugin.createErrorStatus("The executable path for the Dart VM has not been set."));
    }

    List<String> commandsList = new ArrayList<String>();

    int connectionPort = NetUtils.findUnusedPort(DEFAULT_PORT_NUMBER);

    commandsList.add(vmExecPath);
    commandsList.addAll(Arrays.asList(launchConfig.getVmArgumentsAsArray()));

    if (enableDebugging) {
        commandsList.add("--debug:" + connectionPort);
    }

    observatoryPort = NetUtils.findUnusedPort(0);

    launchConfig.setObservatoryPort(observatoryPort);
    launchConfig.save();

    commandsList.add("--enable-vm-service:" + observatoryPort);
    commandsList.add("--trace_service_pause_events");

    if (launchConfig.getPauseIsolateOnExit()) {
        commandsList.add("--pause-isolates-on-exit");
    }

    if (launchConfig.getPauseIsolateOnStart()) {
        commandsList.add("--pause-isolates-on-start");
    }

    // This lets us debug isolates.
    if (enableDebugging) {
        commandsList.add("--break-at-isolate-spawn");
    }

    String coverageTempDir = null;
    if (DartCoreDebug.ENABLE_COVERAGE) {
        coverageTempDir = CoverageManager.createTempDir();
        commandsList.add("--coverage_dir=" + coverageTempDir);
    }

    String packageRoot = DartCore.getPlugin().getVmPackageRoot(launchConfig.getProject());
    if (packageRoot != null) {
        String fileSeparator = System.getProperty("file.separator");
        if (!packageRoot.endsWith(fileSeparator)) {
            packageRoot += fileSeparator;
        }
        commandsList.add("--package-root=" + packageRoot);
    }

    commandsList.add(scriptPath);
    commandsList.addAll(Arrays.asList(launchConfig.getArgumentsAsArray()));
    String[] commands = commandsList.toArray(new String[commandsList.size()]);
    ProcessBuilder processBuilder = new ProcessBuilder(commands);

    if (currentWorkingDirectory != null) {
        processBuilder.directory(currentWorkingDirectory);
    }

    Process runtimeProcess = null;

    try {
        runtimeProcess = processBuilder.start();
        if (coverageTempDir != null) {
            UriToFileResolver uriToFileResolver = new UriToFileResolver(launch);
            CoverageManager.registerProcess(uriToFileResolver, coverageTempDir,
                    launchConfig.getApplicationName(), runtimeProcess);
        }
    } catch (IOException ioe) {
        throw new CoreException(
                new Status(IStatus.ERROR, DartDebugCorePlugin.PLUGIN_ID, ioe.getMessage(), ioe));
    }

    IProcess eclipseProcess = null;

    Map<String, String> processAttributes = new HashMap<String, String>();

    String programName = "dart";
    processAttributes.put(IProcess.ATTR_PROCESS_TYPE, programName);
    processAttributes.put(IProcess.ATTR_CMDLINE, describe(processBuilder));

    if (runtimeProcess != null) {
        monitor.beginTask("Dart", IProgressMonitor.UNKNOWN);

        eclipseProcess = DebugPlugin.newProcess(launch, runtimeProcess,
                launchConfig.getApplicationName() + " (" + new Date() + ")", processAttributes);
    }

    if (runtimeProcess == null || eclipseProcess == null) {
        if (runtimeProcess != null) {
            runtimeProcess.destroy();
        }

        throw new CoreException(DartDebugCorePlugin.createErrorStatus("Error starting Dart VM process"));
    }

    eclipseProcess.setAttribute(IProcess.ATTR_CMDLINE, describe(processBuilder));

    if (enableDebugging) {
        ServerDebugTarget debugTarget = new ServerDebugTarget(launch, eclipseProcess, connectionPort);

        try {
            debugTarget.connect();

            launch.addDebugTarget(debugTarget);
        } catch (DebugException ex) {
            // We don't throw an exception if the process died before we could connect.
            if (!isProcessDead(runtimeProcess)) {
                throw ex;
            }
        }
    }

    monitor.done();
}

From source file:dk.netarkivet.harvester.heritrix3.controller.HeritrixController.java

@Override
public void stopHeritrix() {
    log.debug("Stopping Heritrix3");
    try {//from  www. j a  va2s  . c o  m
        // Check if a heritrix3 process still exists for this jobName
        ProcessBuilder processBuilder = new ProcessBuilder("pgrep", "-f", jobName);
        log.info("Looking up heritrix3 process with. " + processBuilder.command());
        if (processBuilder.start().waitFor() == 0) { // Yes, ask heritrix3 to shutdown, ignoring any jobs named jobName
            log.info("Heritrix running, requesting heritrix to stop and ignoring running job '{}'", jobName);
            h3wrapper.exitJavaProcess(Arrays.asList(new String[] { jobName }));
        } else {
            log.info("Heritrix3 process not running for job '{}'", jobName);
        }
        // Check again
        if (processBuilder.start().waitFor() == 0) { // The process is still alive, kill it
            log.info("Heritrix3 process still running, pkill'ing heritrix3 ");
            ProcessBuilder killerProcessBuilder = new ProcessBuilder("pkill", "-f", jobName);
            int pkillExitValue = killerProcessBuilder.start().exitValue();
            if (pkillExitValue != 0) {
                log.warn("Non xero exit value ({}) when trying to pkill Heritrix3.", pkillExitValue);
            } else {
                log.info("Heritrix process terminated successfully with the pkill command {}",
                        killerProcessBuilder.command());
            }
        } else {
            log.info("Heritrix3 stopped successfully.");
        }
    } catch (IOException e) {
        log.warn("Exception while trying to shutdown heritrix", e);
    } catch (InterruptedException e) {
        log.debug("stopHeritrix call interupted", e);
    }
}

From source file:org.dawnsci.commandserver.core.process.ProgressableProcess.java

protected void pkill(int pid, String dir) throws Exception {

    // Use pkill, seems to kill all of the tree more reliably
    ProcessBuilder pb = new ProcessBuilder();

    // Can adjust env if needed:
    // Map<String, String> env = pb.environment();
    pb.directory(new File(dir));

    File log = new File(dir, "xia2_kill.txt");
    pb.redirectErrorStream(true);/*www .  j  a v  a  2  s. c o m*/
    pb.redirectOutput(Redirect.appendTo(log));

    pb.command("bash", "-c", "pkill -9 -s " + pid);

    Process p = pb.start();
    p.waitFor();
}

From source file:com.att.aro.datacollector.ioscollector.utilities.AppSigningHelper.java

public void executeCmd(String cmd) {
    System.out.println(cmd);//from  www .j a  va 2  s.c  om
    ProcessBuilder pbldr = new ProcessBuilder();
    if (!Util.isWindowsOS()) {
        pbldr.command(new String[] { "bash", "-c", cmd });
    } else {
        pbldr.command(new String[] { "CMD", "/C", cmd });
    }
    try {
        Process proc = pbldr.start();
        try {
            Thread.sleep(1000 * 2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        proc.destroy();
    } catch (IOException e) {
        //Do nothing
    }
}