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:Main.java

public static String executeCommand(String[] args) {
    String result = new String();
    ProcessBuilder processBuilder = new ProcessBuilder(args);
    Process process = null;//from   w ww  . ja v  a  2s  .c  o m
    InputStream errIs = null;
    InputStream inIs = null;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int read = -1;
        process = processBuilder.start();
        errIs = process.getErrorStream();
        while ((read = errIs.read()) != -1) {
            baos.write(read);
        }
        baos.write('\n');
        inIs = process.getInputStream();
        while ((read = inIs.read()) != -1) {
            baos.write(read);
        }
        byte[] data = baos.toByteArray();
        result = new String(data);
    } catch (Exception e) {
        Log.e(TAG, e.getMessage(), e);
    } finally {
        try {
            if (errIs != null) {
                errIs.close();
            }
            if (inIs != null) {
                inIs.close();
            }
        } catch (IOException e) {
            Log.e(TAG, e.getMessage(), e);
        }
        if (process != null) {
            process.destroy();
        }
    }
    return result;
}

From source file:net.dv8tion.discord.Yui.java

private static void relaunchInUTF8() throws InterruptedException, UnsupportedEncodingException {
    System.out.println("BotLauncher: We are not running in UTF-8 mode! This is a problem!");
    System.out.println("BotLauncher: Relaunching in UTF-8 mode using -Dfile.encoding=UTF-8");

    String[] command = new String[] { "java", "-Dfile.encoding=UTF-8", "-jar",
            Yui.getThisJarFile().getAbsolutePath() };

    //Relaunches the bot using UTF-8 mode.
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.inheritIO(); //Tells the new process to use the same command line as this one.
    try {/*from w  w w. j  ava 2  s. c  o m*/
        Process process = processBuilder.start();
        process.waitFor(); //We wait here until the actual bot stops. We do this so that we can keep using the same command line.
        System.exit(process.exitValue());
    } catch (IOException e) {
        if (e.getMessage().contains("\"java\"")) {
            System.out.println(
                    "BotLauncher: There was an error relaunching the bot. We couldn't find Java to launch with.");
            System.out.println("BotLauncher: Attempted to relaunch using the command:\n   "
                    + StringUtils.join(command, " ", 0, command.length));
            System.out.println(
                    "BotLauncher: Make sure that you have Java properly set in your Operating System's PATH variable.");
            System.out.println("BotLauncher: Stopping here.");
        } else {
            e.printStackTrace();
        }
    }
}

From source file:jmupen.JMupenUpdater.java

public static void startWinUpdaterApplication() {
    final String javaBin;
    javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java.exe";
    File updaterJar = new File(tmpDir.getAbsolutePath() + File.separator + "bin" + File.separator + "win"
            + File.separator + "JMupenWinupdater.jar");

    File currentJarPathTxt = new File(
            tmpDir.getAbsolutePath() + File.separator + "bin" + File.separator + "currentjar.txt");
    try {/*from  www  .  ja v a  2  s  . c om*/
        FileUtils.writeStringToFile(currentJarPathTxt, getJarFile().getAbsolutePath());
    } catch (IOException e) {
        System.err.println("Error writing jar filepath " + e.getLocalizedMessage());
        JMupenGUI.getInstance().showError("Error writing jar filepath to txt", e.getLocalizedMessage());
    } catch (URISyntaxException ex) {
        System.err.println("Error writing jar filepath " + ex.getLocalizedMessage());

    }
    if (!updaterJar.exists()) {
        JMupenGUI.getInstance().showError("WinUpdater not found", "in folder: " + updaterJar.getAbsolutePath());
        return;
    }

    /* is it a jar file? */
    if (!updaterJar.getName().endsWith(".jar")) {
        JMupenGUI.getInstance().showError("WinUpdater does not end with .jar????",
                updaterJar.getAbsolutePath());
        return;
    }

    /* Build command: java -jar application.jar */
    final ArrayList<String> command = new ArrayList<String>();
    command.add(javaBin);
    command.add("-jar");
    command.add(updaterJar.getPath());

    final ProcessBuilder builder = new ProcessBuilder(command);
    try {
        builder.start();
    } catch (IOException ex) {
        System.err.println("Error starting updater. " + ex.getLocalizedMessage());
        JMupenGUI.getInstance().showError("Error starting updater", ex.getLocalizedMessage());
    }
    System.gc();
    System.exit(0);
}

From source file:minij.assembler.Assembler.java

public static void assemble(Configuration config, String assembly) throws AssemblerException {

    try {//  w ww  .j  a va2  s .co m
        new File(FilenameUtils.getPath(config.outputFile)).mkdirs();

        // -xc specifies the input language as C and is required for GCC to read from stdin
        ProcessBuilder processBuilder = new ProcessBuilder("gcc", "-o", config.outputFile, "-m32", "-xc",
                MiniJCompiler.RUNTIME_DIRECTORY.toString() + File.separator + "runtime_32.c", "-m32",
                "-xassembler", "-");
        Process gccCall = processBuilder.start();
        // Write C code to stdin of C Compiler
        OutputStream stdin = gccCall.getOutputStream();
        stdin.write(assembly.getBytes());
        stdin.close();

        gccCall.waitFor();

        // Print error messages of GCC
        if (gccCall.exitValue() != 0) {

            StringBuilder errOutput = new StringBuilder();
            InputStream stderr = gccCall.getErrorStream();
            String line;
            BufferedReader bufferedStderr = new BufferedReader(new InputStreamReader(stderr));
            while ((line = bufferedStderr.readLine()) != null) {
                errOutput.append(line + System.lineSeparator());
            }
            bufferedStderr.close();
            stderr.close();

            throw new AssemblerException(
                    "Failed to compile assembly:" + System.lineSeparator() + errOutput.toString());
        }

        Logger.logVerbosely("Successfully compiled assembly");
    } catch (IOException e) {
        throw new AssemblerException("Failed to transfer assembly to gcc", e);
    } catch (InterruptedException e) {
        throw new AssemblerException("Failed to invoke gcc", e);
    }

}

From source file:br.on.daed.services.pdf.DadosMagneticos.java

public static byte[] gerarPDF(String ano, String tipo)
        throws IOException, InterruptedException, UnsupportedOperationException {

    File tmpFolder;/* w ww. ja v a 2s .c  o m*/
    String folderName;

    Double anoDouble = Double.parseDouble(ano);
    List<String> dados = Arrays.asList(TIPO_DADOS_MAGNETICOS);

    byte[] ret = null;

    if (anoDouble >= ANO_MAGNETICO[0] && anoDouble < ANO_MAGNETICO[1] && dados.contains(tipo)) {

        do {

            folderName = "/tmp/dislin" + Double.toString(System.currentTimeMillis() * Math.random());
            tmpFolder = new File(folderName);

        } while (tmpFolder.exists());

        tmpFolder.mkdir();

        ProcessBuilder processBuilder = new ProcessBuilder("/opt/declinacao-magnetica/./gerar", ano, tipo);

        processBuilder.directory(tmpFolder);

        processBuilder.environment().put("LD_LIBRARY_PATH", "/usr/local/dislin");

        Process proc = processBuilder.start();

        proc.waitFor();

        ProcessHelper.outputProcess(proc);

        File arquivoServido = new File(folderName + "/dislin.pdf");

        FileInputStream fis = new FileInputStream(arquivoServido);

        ret = IOUtils.toByteArray(fis);

        processBuilder = new ProcessBuilder("rm", "-r", folderName);

        tmpFolder = new File("/");

        processBuilder.directory(tmpFolder);

        Process delete = processBuilder.start();

        delete.waitFor();

    } else {
        throw new UnsupportedOperationException("Entrada invlida");
    }
    return ret;
}

From source file:edu.uci.ics.asterix.installer.test.AsterixClusterLifeCycleIT.java

private static Process remoteInvoke(String cmd) throws Exception {
    ProcessBuilder pb = new ProcessBuilder("vagrant", "ssh", "cc", "-c", "MANAGIX_HOME=/tmp/asterix/ " + cmd);
    File cwd = new File(asterixProjectDir.toString() + "/" + CLUSTER_BASE);
    pb.directory(cwd);/*  ww w  .  j av a2 s. c  o  m*/
    pb.redirectErrorStream(true);
    Process p = pb.start();
    return p;
}

From source file:com.ikon.util.ExecutionUtils.java

/**
 * Execute command line: implementation/*from   w  ww. j a v  a2s.c o  m*/
 */
private static ExecutionResult runCmdImpl(final String cmd[], final long timeout)
        throws SecurityException, InterruptedException, IOException {
    log.debug("runCmdImpl({}, {})", Arrays.toString(cmd), timeout);
    ExecutionResult ret = new ExecutionResult();
    long start = System.currentTimeMillis();
    final ProcessBuilder pb = new ProcessBuilder(cmd);
    final Process process = pb.start();

    Timer t = new Timer("Process Execution Timeout");
    t.schedule(new TimerTask() {
        @Override
        public void run() {
            process.destroy();
            log.warn("Process killed due to timeout.");
            log.warn("CommandLine: {}", Arrays.toString(cmd));
        }
    }, timeout);

    try {
        ret.setStdout(IOUtils.toString(process.getInputStream()));
        ret.setStderr(IOUtils.toString(process.getErrorStream()));
    } catch (IOException e) {
        // Ignore
    }

    process.waitFor();
    t.cancel();
    ret.setExitValue(process.exitValue());

    // Check return code
    if (ret.getExitValue() != 0) {
        log.warn("Abnormal program termination: {}", ret.getExitValue());
        log.warn("CommandLine: {}", Arrays.toString(cmd));
        log.warn("STDERR: {}", ret.getStderr());
    } else {
        log.debug("Normal program termination");
    }

    process.destroy();
    log.debug("Elapse time: {}", FormatUtil.formatSeconds(System.currentTimeMillis() - start));
    return ret;
}

From source file:it.crs4.pydoop.mapreduce.pipes.Application.java

/**
 * Run a given command in a subprocess, including threads to copy its stdout
 * and stderr to our stdout and stderr.//  www  . ja  v  a  2 s. c  om
 * @param command the command and its arguments
 * @param env the environment to run the process in
 * @return a handle on the process
 * @throws IOException
 */
static Process runClient(List<String> command, Map<String, String> env) throws IOException {
    ProcessBuilder builder = new ProcessBuilder(command);
    if (env != null) {
        builder.environment().putAll(env);
    }
    Process result = builder.start();
    return result;
}

From source file:de.bamamoto.mactools.png2icns.Scaler.java

protected static String runProcess(String[] commandLine) throws IOException {
    StringBuilder cl = new StringBuilder();
    for (String i : commandLine) {
        cl.append(i);//  w w  w. ja v a 2  s .c o  m
        cl.append(" ");
    }

    String result = "";

    ProcessBuilder builder = new ProcessBuilder(commandLine);
    Map<String, String> env = builder.environment();
    env.put("PATH", "/usr/sbin:/usr/bin:/sbin:/bin");
    builder.redirectErrorStream(true);
    Process process = builder.start();

    String line;

    InputStream stdout = process.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));

    while ((line = reader.readLine()) != null) {
        result += line + "\n";
    }

    boolean isProcessRunning = true;
    int maxRetries = 60;

    do {
        try {
            isProcessRunning = process.exitValue() < 0;
        } catch (IllegalThreadStateException ex) {
            System.out.println("Process not terminated. Waiting ...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException iex) {
                //nothing todo
            }
            maxRetries--;
        }
    } while (isProcessRunning && maxRetries > 0);
    System.out.println("Process has terminated");
    if (process.exitValue() != 0) {
        throw new IllegalStateException("Exit value not equal to 0: " + result);
    }
    if (maxRetries == 0 && isProcessRunning) {
        System.out.println("Process does not terminate. Try to kill the process now.");
        process.destroy();
    }

    return result;
}

From source file:com.google.dart.tools.designer.model.HtmlRenderHelper.java

/**
 * @return the image of given HTML content, may be <code>null</code>.
 *///from w ww  .  j a  va  2  s.  c om
public static Image renderImage(final String content) {
    try {
        File tempFile = File.createTempFile("htmlRender", ".html");
        try {
            IOUtils2.writeBytes(tempFile, content.getBytes());
            // start DumpRenderTree
            if (processOutputStream == null) {
                String path;
                {
                    Bundle bundle = DartDesignerPlugin.getDefault().getBundle();
                    URL url = bundle.getEntry("lib/DumpRenderTree.app/Contents/MacOS/DumpRenderTree");
                    path = FileLocator.toFileURL(url).getPath();
                }
                //        ProcessBuilder builder = new ProcessBuilder(path, "-p", tempFile.getAbsolutePath());
                ProcessBuilder builder = new ProcessBuilder(path, "-p", "-");
                builder.redirectErrorStream(true);
                Process process = builder.start();
                processOutputStream = process.getOutputStream();
                processInputStream = process.getInputStream();
                processReader = new BufferedReader(new InputStreamReader(processInputStream));
            }
            long start = System.nanoTime();
            // XXX
            //        processOutputStream.write((tempFile.getAbsolutePath() + "\n").getBytes());
            processOutputStream
                    .write(("http://127.0.0.1:3030/Users/scheglov/dart/dwc_first/web/out/dwc_first.html\n")
                            .getBytes());
            processOutputStream.flush();
            // read tree
            while (true) {
                String line = processReader.readLine();
                System.out.println(line);
                if (line.isEmpty()) {
                    break;
                }
            }
            // read image
            {
                processReader.readLine(); // ActualHash:
                processReader.readLine(); // Content-Type: image/png
                String lengthLine = processReader.readLine(); // Content-Length: 5546
                int pngLength = Integer.parseInt(StringUtils.removeStart(lengthLine, "Content-Length: "));
                //          System.out.println("pngLength: " + pngLength);
                char[] pngChars = new char[pngLength];
                readFully(processReader, pngChars);
                byte[] pngBytes = new String(pngChars).getBytes();
                Image image = new Image(null, new ByteArrayInputStream(pngBytes));
                System.out.println("imageTime: " + (System.nanoTime() - start) / 1000000.0);
                return image;
            }
            //
            //        {
            //          SessionInputBuffer buffer = new AbstractSessionInputBuffer() {
            //            {
            //              init(processInputStream, 1024, new BasicHttpParams());
            //            }
            //
            //            @Override
            //            public boolean isDataAvailable(int timeout) throws IOException {
            //              return false;
            //            }
            //          };
            //          LineParser lineParser = new BasicLineParser(new ProtocolVersion("HTTP", 1, 1));
            //          HttpMessageParser<HttpResponse> parser = new DefaultHttpResponseParser(
            //              buffer,
            //              lineParser,
            //              new DefaultHttpResponseFactory(),
            //              new BasicHttpParams());
            //          HttpResponse response = parser.parse();
            //          System.out.println(response);
            //          HttpParams params = new BasicHttpParams();
            //          SessionInputBuffer inbuffer = new SessionInputBufferMockup(s, "US-ASCII", params);
            //          HttpMessageParser<BasicHttpResponse> parser = new DefaultResponseParser(
            //              inbuffer,
            //              BasicLineParser.DEFAULT,
            //              new DefaultHttpResponseFactory(),
            //              params);
            //
            //          HttpResponse response = parser.parse();
            //        }
            //        while (true) {
            //          String line = processReader.readLine();
            //          System.out.println(line);
            //        }
            //
            //        byte[] bytes = IOUtils2.readBytes(processInputStream);
            //        int exitValue = process.exitValue();
            //        System.out.println("bytes: " + bytes.length);
            //        System.out.println("bytesTime: " + (System.nanoTime() - start) / 1000000.0);
            //        String output = new String(bytes);
            //        System.out.println(StringUtils.substring(output, -10, 0));
            ////        System.out.println(output);
            //        //
            //        int pngOffset = output.indexOf("Content-Type: image/png");
            //        pngOffset = output.indexOf('\n', pngOffset) + 1;
            //        pngOffset = output.indexOf('\n', pngOffset) + 1;
            //        Image image = new Image(null, new ByteArrayInputStream(bytes, pngOffset, bytes.length
            //            - pngOffset));
            //        System.out.println("imageTime: " + (System.nanoTime() - start) / 1000000.0);
            //        return image;
        } finally {
            tempFile.delete();
        }
    } catch (Throwable e) {
        e.printStackTrace();
    }
    return null;
}