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:com.scooter1556.sms.server.io.StreamProcess.java

private void run(String[] command) throws IOException {
    LogService.getInstance().addLogEntry(LogService.Level.DEBUG, CLASS_NAME, StringUtils.join(command, " "),
            null);/*from   w  w w . j  av a  2  s  .  c o  m*/

    ProcessBuilder processBuilder = new ProcessBuilder(command);

    process = processBuilder.start();
    InputStream input = process.getInputStream();
    OutputStream output = response.getOutputStream();
    new NullStream(process.getErrorStream()).start();

    // Buffer
    byte[] buffer = new byte[BUFFER_SIZE];
    int length;

    // Write stream to output
    while ((length = input.read(buffer)) != -1) {
        output.write(buffer, 0, length);
        bytesTransferred += length;
    }
}

From source file:com.laex.cg2d.screeneditor.handlers.RenderHandler.java

/**
 * the command has been executed, so extract extract the needed information
 * from the application context./*  ww w . j ava  2  s .  c  o  m*/
 * 
 * @param event
 *          the event
 * @return the object
 * @throws ExecutionException
 *           the execution exception
 */
public Object execute(ExecutionEvent event) throws ExecutionException {
    IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
    final IEditorPart editorPart = window.getActivePage().getActiveEditor();

    editorPart.doSave(new NullProgressMonitor());

    validate(window.getShell());

    // Eclipse Jobs API
    final Job job = new Job("Render Game") {
        @Override
        protected IStatus run(IProgressMonitor monitor) {

            if (monitor.isCanceled()) {
                return Status.CANCEL_STATUS;
            }

            try {
                IFile file = ((IFileEditorInput) editorPart.getEditorInput()).getFile();

                monitor.beginTask("Building rendering command", 5);
                ILog log = Activator.getDefault().getLog();

                String mapFile = file.getLocation().makeAbsolute().toOSString();
                String controllerFile = file.getLocation().removeFileExtension().addFileExtension("lua")
                        .makeAbsolute().toOSString();

                String[] command = buildRunnerCommandFromProperties(mapFile, controllerFile);
                monitor.worked(5);

                monitor.beginTask("Rendering external", 5);

                ProcessBuilder pb = new ProcessBuilder(command);
                Process p = pb.start();

                monitor.worked(4);
                Scanner scn = new Scanner(p.getErrorStream());
                while (scn.hasNext() && !monitor.isCanceled()) {

                    if (monitor.isCanceled()) {
                        throw new InterruptedException("Cancelled");
                    }

                    log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, scn.nextLine()));
                }
                monitor.worked(5);

                monitor.done();
                this.done(Status.OK_STATUS);
                return Status.OK_STATUS;

            } catch (RuntimeException e) {
                return handleException(e);
            } catch (IOException e) {
                return handleException(e);
            } catch (CoreException e) {
                return handleException(e);
            } catch (InterruptedException e) {
                return handleException(e);
            }
        }

        private IStatus handleException(Exception e) {
            Activator.log(e);
            return Status.CANCEL_STATUS;
        }
    };

    job.setUser(true);
    job.setPriority(Job.INTERACTIVE);
    job.schedule();

    return null;
}

From source file:cz.cuni.mff.ksi.jinfer.autoeditor.automatonvisualizer.layouts.graphviz.GraphvizLayoutFactory.java

@SuppressWarnings("PMD")
private <T> Map<State<T>, Point2D> getGraphvizPositions(final byte[] graphInDotFormat,
        final Set<State<T>> automatonStates) throws GraphvizException, IOException {
    final Map<State<T>, Point2D> result = new HashMap<State<T>, Point2D>();

    // creates new dot process.
    final ProcessBuilder processBuilder = new ProcessBuilder(Arrays.asList(GraphvizUtils.getPath(), "-Tplain"));
    final Process process = processBuilder.start();

    // write our graph into dot binary standart input
    process.getOutputStream().write(graphInDotFormat);
    process.getOutputStream().flush();//from   w ww.  j a  v  a 2s  .  c  o  m

    // read from dot binary standard output
    final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    process.getOutputStream().close();

    final Scanner scanner = new Scanner(reader);
    // jumps some unnecessary information from output
    scanner.next();
    scanner.next();

    // get width and height of graph
    windowWidth = 100 + (int) Double.parseDouble(scanner.next());
    windowHeight = 100 + (int) Double.parseDouble(scanner.next());

    // parse output for graph vertex positions
    while (scanner.hasNext()) {
        final String n = scanner.next();
        if (n.equals("node")) {
            final int nodeName = Integer.parseInt(scanner.next());
            final double x = Double.parseDouble(scanner.next());
            final double y = Double.parseDouble(scanner.next());
            boolean found = false;
            for (State<T> state : automatonStates) {
                if (state.getName() == nodeName) {
                    result.put(state, new Point(50 + (int) (x), 50 + (int) (y)));
                    found = true;
                    break;
                }
            }
            if (!found) {
                throw new GraphvizException("Node with name " + nodeName + " was not found in automaton.");
            }
        }
    }

    return result;
}

From source file:ch.ledcom.maven.sitespeed.analyzer.SiteSpeedAnalyzer.java

public Document analyze(URL url) throws IOException, JDOMException, InterruptedException {
    InputStream in = null;//from w  w  w.  j av  a  2s .c  o m
    boolean threw = true;
    try {
        log.info("Starting analysis of [" + url.toExternalForm() + "]");

        List<String> command = constructCommand(url);

        logCommand(command);

        ProcessBuilder pb = new ProcessBuilder(command);
        pb.redirectErrorStream();
        Process p = pb.start();
        // FIXME: we need to filter the InputStream as it seems we can get
        // content outside of the XML document (see sitespeed.io)
        in = p.getInputStream();
        byte[] result = IOUtils.toByteArray(in);

        log.info("Result of analysis:" + ArrayUtils.toString(result));

        Document doc = docBuilder.get().build(new ByteArrayInputStream(result));

        log.info(XmlPrettyPrinter.prettyPrint(doc));

        int status = p.waitFor();
        if (status != 0) {
            throw new RuntimeException("PhantomJS returned with status [" + status + "]");
        }
        threw = false;
        return doc;
    } finally {
        Closeables.close(in, threw);
    }
}

From source file:com.cisco.oss.foundation.monitoring.RegistryFinder.java

private Registry internalProcessStart(final Configuration configuration, final int port, final String command)
        throws IOException, RemoteException, AccessException {

    String maxHeapArg = "-J-Xmx" + configuration.getInt(FoundationMonitoringConstants.RMIREGISTRY_MAXHEAPSIZE)
            + "m";
    // start rmiregistry process
    if (System.getProperty("os.name").toLowerCase(Locale.getDefault()).contains("windows")) {
        String[] commandArgsArr = new String[] { command, maxHeapArg, String.valueOf(port) };
        List<String> commandArgs = Arrays.asList(commandArgsArr);
        LOGGER.info("running command: " + commandArgs);
        new ProcessBuilder(commandArgsArr).start();
    } else {/* w  w w.j  a  v  a2s.  c  o  m*/
        // support background process to prevent zombies

        String[] commandArgsArr = new String[] { "/bin/sh", "-c", command + maxHeapArg + " " + port + "&" };
        List<String> commandArgs = Arrays.asList(commandArgsArr);
        LOGGER.info("running command: " + commandArgs);
        new ProcessBuilder(commandArgsArr).start();
    }

    try {
        // wait for the process to start properly
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        LOGGER.warn("The sleep for  rmi registry to end has been interrupted: " + e.toString());
    }

    // get registry
    final Registry registry = LocateRegistry.getRegistry(port);

    // test registry
    registry.list();

    LOGGER.info("New RMI  Registry created using port: " + port);

    return registry;
}

From source file:com.google.dart.server.internal.remote.StdioServerSocket.java

@Override
public void start() throws Exception {
    String[] arguments = computeProcessArguments();
    if (debugStream != null) {
        StringBuilder builder = new StringBuilder();
        builder.append("  ");
        int count = arguments.length;
        for (int i = 0; i < count; i++) {
            if (i > 0) {
                builder.append(' ');
            }//from   w w w .j  av a  2  s  .  c om
            builder.append(arguments[i]);
        }
        debugStream.println(System.currentTimeMillis() + " started analysis server:");
        debugStream.println(builder.toString());
    }
    ProcessBuilder processBuilder = new ProcessBuilder(arguments);
    process = processBuilder.start();
    requestSink = new ByteRequestSink(process.getOutputStream(), debugStream);
    responseStream = new ByteResponseStream(process.getInputStream(), debugStream);
    errorStream = new ByteLineReaderStream(process.getErrorStream());
}

From source file:com.pentaho.ctools.utils.BAServerService.java

/**
 * This method shall execute a windows command to start/stop/query 
 * windows services/*from w ww  . j  a va 2s .  com*/
 * 
 * @param command
 * @return Output of the command execution.
 */
private static String ExecuteCommand(String[] command) {
    String output = "";
    try {
        Process process = new ProcessBuilder(command).start();

        try (InputStream inputStream = process.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);) {

            String line;
            while ((line = bufferedReader.readLine()) != null) {
                LOG.debug("OUTPUT:: " + line);
                output += line;
            }
        } catch (Exception ex) {//InputStream
            LOG.debug("InputStream Exception : " + ex);
        }
    } catch (Exception ex) { //Process
        LOG.debug("Process Exception : " + ex);
    }
    return output;
}

From source file:com.netflix.raigad.defaultimpl.ElasticSearchProcessManager.java

public void stop() throws IOException {
    logger.info("Stopping Elasticsearch server ....");
    List<String> command = Lists.newArrayList();
    if (!"root".equals(System.getProperty("user.name"))) {
        command.add(SUDO_STRING);//ww  w  . j  a va2 s. co  m
        command.add("-n");
        command.add("-E");
    }
    for (String param : config.getElasticsearchStopScript().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("Elasticsearch server has been stopped");
        else {
            logger.error("Unable to stop Elasticsearch server. Error code: {}", code);
            logProcessOutput(stopper);
        }
    } catch (Exception e) {
        logger.warn("couldn't shut down Elasticsearch correctly", e);
    }
}

From source file:ai.h2o.servicebuilder.Util.java

/**
 * Run command cmd in separate process in directory
 *
 * @param directory    run in this directory
 * @param cmd          command to run//from w  w  w  .  j  av  a  2s.  com
 * @param errorMessage error message if process didn't finish with exit value 0
 * @return stdout combined with stderr
 * @throws Exception
 */
public static String runCmd(File directory, List<String> cmd, String errorMessage) throws Exception {
    ProcessBuilder pb = new ProcessBuilder(cmd);
    pb.directory(directory);
    pb.redirectErrorStream(true); // error sent to output stream
    Process p = pb.start();

    // get output stream to string
    String s;
    StringBuilder sb = new StringBuilder();
    BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));
    while ((s = stdout.readLine()) != null) {
        logger.info(s);
        sb.append(s);
        sb.append('\n');
    }
    String sbs = sb.toString();
    int exitValue = p.waitFor();
    if (exitValue != 0)
        throw new Exception(errorMessage + " exit value " + exitValue + "  " + sbs);
    return sbs;
}

From source file:com.cedarsoft.io.LinkUtils.java

/**
 * Creates a link.//from w w  w  .  j av a  2  s  . co  m
 * Returns true if the link has been created, false if the link (with the same link source) still exists.
 *
 * @param linkTarget the link source
 * @param linkFile   the link file
 * @param symbolic   whether to create a symbolic link
 * @return whether the link has been created (returns false if the link still existed)
 *
 * @throws IOException if something went wrong
 */
public static boolean createLink(@Nonnull File linkTarget, @Nonnull File linkFile, boolean symbolic)
        throws IOException {
    if (linkFile.exists()) {
        //Maybe the hard link still exists - we just don't know, so throw an exception
        if (!symbolic) {
            throw new IOException("link still exists " + linkFile.getAbsolutePath());
        }

        if (linkFile.getCanonicalFile().equals(linkTarget.getCanonicalFile())) {
            //still exists - that is ok, since it points to the same directory
            return false;
        } else {
            //Other target
            throw new IOException("A link still exists at <" + linkFile.getAbsolutePath()
                    + "> but with different target: <" + linkTarget.getCanonicalPath() + "> exected <"
                    + linkFile.getCanonicalPath() + ">");
        }
    }

    List<String> args = new ArrayList<String>();
    args.add("ln");
    if (symbolic) {
        args.add("-s");
    }
    args.add(linkTarget.getPath());
    args.add(linkFile.getAbsolutePath());

    ProcessBuilder builder = new ProcessBuilder(args);
    Process process = builder.start();
    try {
        int result = process.waitFor();
        if (result != 0) {
            throw new IOException("Creation of link failed: " + IOUtils.toString(process.getErrorStream()));
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

    return true;
}