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:it.isislab.dmason.util.SystemManagement.Worker.Updater.java

public static void updateNoGUI(Address ftpAddress, String name, String myTopic, Address address) {

    logger.debug("Update (with CLI) command received");

    FTPIP = ftpAddress.getIPaddress();// ww  w  .j ava2s . co m
    FTPPORT = ftpAddress.getPort();
    jarName = name;

    setSeparator();

    downloadJar(jarName, "upd");

    //DOWNLOADED_JAR_PATH+SEPARATOR+
    File fDown = new File(DOWNLOADED_JAR_PATH + SEPARATOR + jarName);
    File fDest = new File(jarName);

    try {

        //FileUtils.copyFile(fDown, fDest);
        copyFile(fDown, fDest);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        ArrayList<String> command = new ArrayList<String>();

        command.add("java");
        //command.add("-jar");
        command.add("-cp");
        command.add(fDest.getAbsolutePath());
        command.add(DMasonWorker.class.getName());
        command.add(address.getIPaddress());
        command.add(address.getPort());
        command.add(myTopic);
        command.add("update");

        System.out.println(command);

        logger.info("Restarting with command: " + command.toString());

        ProcessBuilder builder = new ProcessBuilder(command);
        Process process = builder.start();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    /*Timer timer = new Timer(4000, new ActionListener() {
    public void actionPerformed(ActionEvent e) {
       System.exit(0);
            
    }
    });
            
    timer.start();
    */

}

From source file:com.serena.rlc.provider.filesystem.client.FilesystemClient.java

public void localExec(String execScript, String execDir, String execParams, boolean ignoreErrors)
        throws FilesystemClientException {
    Path script = Paths.get(execDir + File.separatorChar + execScript);

    try {/* w w w.  j av a 2s  . c o  m*/
        if (!Files.exists(script)) {
            if (ignoreErrors) {
                logger.debug("Execution script " + script.toString() + " does not exist, ignoring...");
            } else {
                throw new FilesystemClientException(
                        "Execution script " + script.toString() + " does not exist");
            }
        } else {
            ProcessBuilder pb = new ProcessBuilder(script.toString());
            pb.directory(new File(script.getParent().toString()));
            System.out.println(pb.directory().toString());
            logger.debug("Executing script " + execScript + " in directory " + execDir + " with parameters: "
                    + execParams);
            Process p = pb.start(); // Start the process.
            p.waitFor(); // Wait for the process to finish.
            logger.debug("Executed script " + execScript + " successfully.");
        }
    } catch (Exception e) {
        logger.debug(e.getLocalizedMessage());
        throw new FilesystemClientException(e.getLocalizedMessage());
    }

}

From source file:de.knowwe.visualization.util.Utils.java

private static boolean isFileClosedUnix(File file) {
    try {//  w  w w .j a  v  a 2 s . c o m
        Process plsof = new ProcessBuilder(new String[] { "lsof", "|", "grep", file.getAbsolutePath() })
                .start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(plsof.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            if (line.contains(file.getAbsolutePath())) {
                reader.close();
                plsof.destroy();
                return false;
            }
        }
        reader.close();
        plsof.destroy();
    } catch (Exception ignore) {
    }
    return true;
}

From source file:Model.RaptorUCIEngine.java

/**
 * Connects to the engine. After this method is invoked the engine name,
 * engine author, and options will be populated in this object.
 * /*ww  w .ja v a 2  s  .  c om*/
 * @return true if connection was successful, false otherwise.
 */
public boolean connect() {
    if (isConnected()) {
        return true;
    }

    resetConnectionState();

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            logger.error("The engine could not load before timeout of 15 sec!");
            disconnect();
        }

    }, CONNECTION_TIMEOUT);

    try {

        process = new ProcessBuilder(processPath).directory(new File(new File(processPath).getParent()))
                .start();

        Runtime.getRuntime().addShutdownHook(new Thread() {
            public void run() {
                if (process != null) {
                    logger.info("Destroying UCI Engine");
                    process.destroy();
                }
            }
        });

        in = new BufferedReader(new InputStreamReader(process.getInputStream()), 10000);
        out = new PrintWriter(process.getOutputStream());

        send("uci");

        String currentLine = null;
        while ((currentLine = readLine()) != null) {

            if (currentLine.startsWith("id")) {
                parseIdLine(currentLine);
            } else if (currentLine.startsWith("option ")) {
                parseOptionLine(currentLine);
            } else if (currentLine.startsWith("uciok")) {
                break;
            } else {

            }
        }

        sendAllNonDefaultOptions();
        isReady();

        timer.cancel();

        return true;
    } catch (Throwable t) {
        disconnect();
        return false;
    }
}

From source file:edu.stolaf.cs.wmrserver.streaming.PipeMapRed.java

public void configure(JobConf job) {
    try {//  w w  w. j a va 2 s . c  o  m
        String argv = getPipeCommand(job);

        joinDelay_ = job.getLong("stream.joindelay.milli", 0);

        job_ = job;
        fs_ = FileSystem.get(job_);

        nonZeroExitIsFailure_ = job_.getBoolean("stream.non.zero.exit.is.failure", true);

        doPipe_ = getDoPipe();
        if (!doPipe_)
            return;

        setStreamJobDetails(job);

        String[] argvSplit = splitArgs(argv);
        String prog = argvSplit[0];
        File currentDir = new File(".").getAbsoluteFile();
        if (new File(prog).isAbsolute()) {
            // we don't own it. Hope it is executable
        } else {
            // Try to find executable in unpacked job JAR and make absolute if
            // present. Otherwise, leave it as relative to be resolved against PATH
            File jarDir = new File(job.getJar()).getParentFile();
            File progFile = new File(jarDir, argvSplit[0]);
            if (progFile.isFile()) {
                progFile.setExecutable(true);
                argvSplit[0] = progFile.getAbsolutePath();
            }
        }

        logprintln("PipeMapRed exec " + Arrays.asList(argvSplit));
        Hashtable<String, String> childEnv = new Hashtable();
        addJobConfToEnvironment(job_, childEnv);
        addEnvironment(childEnv, job_.get("stream.addenvironment"));
        // add TMPDIR environment variable with the value of java.io.tmpdir
        envPut(childEnv, "TMPDIR", System.getProperty("java.io.tmpdir"));

        // Start the process
        ProcessBuilder builder = new ProcessBuilder(argvSplit);
        // The process' environment initially inherits all vars from the parent --
        // only setting those we add/override
        builder.environment().putAll(childEnv);
        // Set the working directory to the job jars directory
        // This is a bad idea... fix this.
        builder.directory(new File(job.getJar()).getParentFile());
        sim = builder.start();

        clientOut_ = new DataOutputStream(new BufferedOutputStream(sim.getOutputStream(), BUFFER_SIZE));
        clientIn_ = new DataInputStream(new BufferedInputStream(sim.getInputStream(), BUFFER_SIZE));
        clientErr_ = new DataInputStream(new BufferedInputStream(sim.getErrorStream()));
        startTime_ = System.currentTimeMillis();

        errThread_ = new MRErrorThread();
        errThread_.start();
    } catch (Exception e) {
        logStackTrace(e);
        LOG.error("configuration exception", e);
        throw new RuntimeException("configuration exception", e);
    }
}

From source file:ee.ria.xroad.proxy.messagelog.TestUtil.java

static ShellCommandOutput runShellCommand(String command) {
    if (isBlank(command)) {
        return null;
    }/*from w w w  .j av a2  s.c  o  m*/

    log.info("Executing shell command: \t{}", command);

    try {
        Process process = new ProcessBuilder(command.split("\\s+")).start();

        StandardErrorCollector standardErrorReader = new StandardErrorCollector(process);

        StandardOutputReader standardOutputReader = new StandardOutputReader(process);

        standardOutputReader.start();
        standardErrorReader.start();

        standardOutputReader.join();
        standardErrorReader.join();
        process.waitFor();

        int exitCode = process.exitValue();

        return new ShellCommandOutput(exitCode, standardOutputReader.getStandardOutput(),
                standardErrorReader.getStandardError());
    } catch (Exception e) {
        log.error("Failed to execute archive transfer command '{}'", command);
        throw new RuntimeException(e);
    }
}

From source file:com.photon.phresco.plugins.xcode.AppDeploy.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {//from w  w w  . j  av  a 2s.  co m
        if (!deviceDeploy && !SdkVerifier.isAvailable(simVersion)) {
            throw new MojoExecutionException("Selected version " + simVersion + " is not available!");
        }
    } catch (IOException e2) {
        throw new MojoExecutionException("SDK verification failed!");
    } catch (InterruptedException e2) {
        throw new MojoExecutionException("SDK verification interrupted!");
    }
    //get the correct simhome if xCode 4.3 is installed simhome is in /Application/Xcode.app/Contents
    //Fix for artf462004
    File simHomeFile = new File(simHome);
    if (!simHomeFile.exists()) {
        simHome = "/Applications/Xcode.app/Contents" + simHome;
    }

    getLog().info("Simulator home" + simHome);

    if (!deviceDeploy) {
        //copy the files into simulation directory
        String home = System.getProperty("user.home");
        getLog().info("Application.path = " + appPath);
        appName = getAppFileName(appPath);
        getLog().info("Application name = " + appName);
        String deployHome = "";
        if (StringUtils.isNotBlank(appDeployHome)) {
            deployHome = appDeployHome;
        } else {
            deployHome = home + "/Library/Application Support/iPhone Simulator/" + simVersion + "/Applications";
        }
        simHomeAppLocation = new File(
                deployHome + File.separator + project.getName() + File.separator + appName);
        if (!simHomeAppLocation.exists()) {
            getLog().info("directory created");
            simHomeAppLocation.mkdirs();
        }
        getLog().info("Desired location " + simHomeAppLocation.getAbsolutePath());
        try {
            String alignedPath = alignedPath(appPath);
            getLog().info("path to copy source :" + alignedPath);
            XcodeUtil.copyFolder(new File(alignedPath), simHomeAppLocation);
            getLog().info("copy the application " + appPath + " to " + simHomeAppLocation);
        } catch (IOException e1) {
            getLog().error("couldn't copy the application " + appPath + " to " + simHomeAppLocation);
        }
    }
    Runnable runnable = new Runnable() {
        public void run() {

            ProcessBuilder pb;
            if (deviceDeploy) {
                pb = new ProcessBuilder("transporter_chief.rb");
                pb.command().add(appPath);
            } else {
                pb = new ProcessBuilder(simHome);
                // Include errors in output
                pb.redirectErrorStream(true);

                pb.command().add(action);
                pb.command()
                        .add(simHomeAppLocation + File.separator + appName.substring(0, appName.indexOf('.')));
            }
            //               pb.command().add(appName);
            getLog().info("List of commands" + pb.command());
            Process child;
            try {
                //               if(ProcessHelper.isProcessRunning()) {
                //                  ProcessHelper.killSimulatorProcess();
                //               }
                child = pb.start();
                // Consume subprocess output and write to stdout for debugging
                InputStream is = new BufferedInputStream(child.getInputStream());
                int singleByte = 0;
                while ((singleByte = is.read()) != -1) {
                    System.out.write(singleByte);
                }
            } catch (IOException e) {
                getLog().error("error occured in launching simulator ");
                getLog().error(e);
            }
        }
    };

    Thread t = new Thread(runnable, "iPhoneSimulator");
    t.start();
    try {
        t.join(5000);
    } catch (InterruptedException e1) {
        //Intentionally left blank.
    }

}

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 ww w.  ja va  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:uk.ac.kcl.iop.brc.core.pipeline.common.service.DocumentConversionService.java

private File makeTiffFromPDF(DNCWorkCoordinate coordinate, File input) throws IOException, TikaException {
    File output = File.createTempFile(coordinate.getFileName(), ".tiff");
    String[] cmd = { getImageMagickProg(), "-density", "300", input.getPath(), "-depth", "8", "-quality", "1",
            output.getPath() };/*from w w  w . ja  v  a  2  s. c o  m*/
    Process process = new ProcessBuilder(cmd).start();
    IOUtils.closeQuietly(process.getOutputStream());
    InputStream processInputStream = process.getInputStream();
    logStream(processInputStream);
    FutureTask<Integer> waitTask = new FutureTask<>(process::waitFor);
    Thread waitThread = new Thread(waitTask);
    waitThread.start();
    try {
        waitTask.get(240, TimeUnit.SECONDS);
        return output;
    } catch (Exception e) {
        logger.error(e.getMessage());
        waitThread.interrupt();
        process.destroy();
        Thread.currentThread().interrupt();
        waitTask.cancel(true);
    } finally {
        IOUtils.closeQuietly(processInputStream);
        process.destroy();
        waitThread.interrupt();
        waitTask.cancel(true);
    }
    return null;
}

From source file:net.fenyo.gnetwatch.actions.ExternalCommand.java

/**
 * Launches a process but do not wait for its completion.
 * any thread./*from w  ww .  j a va  2 s . c o  m*/
 * @param none.
 * @return void.
 * @throws IOException i/o exception <bold>before</bold> reading the process output stream.
 */
public synchronized void fork() throws IOException {
    final ProcessBuilder pb = new ProcessBuilder(cmdLine);
    pb.directory(new File(directory));
    pb.redirectErrorStream(merge);
    process = pb.start();

    if (process == null)
        throw new IOException("null process");

    reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
}