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:com.kurento.kmf.repository.test.OneRecordingServerTest.java

protected void uploadFileWithCURL(String uploadURL, File fileToUpload)
        throws FileNotFoundException, IOException {

    log.info("Start uploading file with curl");
    long startTime = System.currentTimeMillis();

    ProcessBuilder builder = new ProcessBuilder("curl", "-i", "-F",
            "filedata=@" + fileToUpload.getAbsolutePath(), uploadURL);
    builder.redirectOutput();//from  w  w w.j  ava2s. c o  m
    Process process = builder.start();
    try {
        process.waitFor();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    long duration = System.currentTimeMillis() - startTime;
    log.info("Finished uploading content in " + (((double) duration) / 1000) + " seconds.");
}

From source file:edu.wisc.doit.tcrypt.BouncyCastleFileEncrypterDecrypterIT.java

@Test
public void testOpenSSLEncJavaDec() throws Exception {
    //Encrypt with openssl
    final File encryptFileScript = setupTempFile("encryptFile.sh");
    encryptFileScript.setExecutable(true);

    final File publicKey = setupTempFile("my.wisc.edu-public.pem");
    final File testFile = setupTempFile("testFile.txt");

    final ProcessBuilder pb = new ProcessBuilder(encryptFileScript.getAbsolutePath(),
            publicKey.getAbsolutePath(), testFile.getAbsolutePath());

    final Process p = pb.start();
    final int ret = p.waitFor();
    if (ret != 0) {
        final String pOut = IOUtils.toString(p.getInputStream(), TokenEncrypter.CHARSET).trim();
        System.out.println(pOut);
        final String pErr = IOUtils.toString(p.getErrorStream(), TokenEncrypter.CHARSET).trim();
        System.out.println(pErr);
    }/*from ww  w  . ja  v a 2 s  .c  om*/
    assertEquals(0, ret);

    //Decrypt with java
    final File encryptedFile = new File(testFile.getParentFile(), "testFile.txt.tar");

    final InputStream encTestFileInStream = new FileInputStream(encryptedFile);
    final ByteArrayOutputStream testFileOutStream = new ByteArrayOutputStream();
    fileDecrypter.decrypt(encTestFileInStream, testFileOutStream);
    final String actual = new String(testFileOutStream.toByteArray(), Charset.defaultCharset()).trim();

    //Verify
    final String expected = FileUtils.readFileToString(testFile);
    assertEquals(expected, actual);
}

From source file:net.rim.ejde.internal.signing.ImportCSIFilesAction.java

/**
 * Launches the Signature tool. It passes the .csi file to the signature tool.
 *//*from   w  ww .  j  a v a 2 s.c o  m*/
private void launchSignatureTool(String csiFile) {
    log.debug("Entering SignatureToolAction launchSignatureTool()");

    // This is a list of the commands to run. The first position is the
    // actual command; subsequent entries are arguments.
    List<String> commands = new LinkedList<String>();

    // Find the path to java.exe
    String javaHome = System.getProperty("java.home");
    IPath javaBinPath = new Path(javaHome).append(IConstants.BIN_FOLD_NAME).append(IConstants.JAVA_CMD);
    commands.add(javaBinPath.toOSString());

    // Use the system look and feel
    String lookAndFeelClass = UIManager.getSystemLookAndFeelClassName();
    commands.add("-Dswing.defaultlaf=" + lookAndFeelClass);

    // Load from a jar
    commands.add("-jar");

    IPath sigPath;
    String sigPathString = IConstants.EMPTY_STRING;
    try {
        sigPath = VMToolsUtils.getSignatureToolPath();
        // check signature tool again
        if (!VMToolsUtils.isVMToolValid()) {
            Display.getDefault().syncExec(new Runnable() {
                public void run() {
                    Shell shell = ContextManager.getActiveWorkbenchShell();
                    MessageDialog.openError(shell, Messages.ErrorHandler_DIALOG_TITLE,
                            Messages.SignatureTool_Not_Found_Msg);
                }
            });
            log.error(Messages.SignatureTool_Not_Found_Msg);
            return;
        }
        sigPathString = sigPath.toOSString();
        commands.add(sigPathString);
        commands.add(csiFile);

    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

    // Run the command
    ProcessBuilder processBuilder = new ProcessBuilder(commands);
    try {
        process = processBuilder.start();
        BufferedReader is = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String buffer;
        while ((buffer = is.readLine()) != null) {
            // Print out console output for debugging purposes...
            System.out.println(buffer);
        }
        process = null;
    } catch (IOException e) {
        e.printStackTrace();
    }

    log.debug("Leaving SignatureToolAction launchSignatureTool()");
}

From source file:es.amplia.research.maven.protodocbook.cmd.Factory.java

private void execute(File directory, String... cmd) throws Exception {
    ProcessBuilder pb = new ProcessBuilder(cmd);
    Map<String, String> env = pb.environment();
    pb.directory(directory);//www  .ja  va2  s .co m
    pb.redirectErrorStream(true);
    Process p = pb.start();
    p.waitFor();
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = null;
    while ((line = br.readLine()) != null) {
        if (this.log.isInfoEnabled())
            this.log.info(line);
    }
}

From source file:edu.wisc.doit.tcrypt.BouncyCastleFileEncrypterDecrypterIT.java

@Test
public void testJavaEncOpenSSLDec() throws Exception {
    //Encrypt with Java
    final File testFile = setupTempFile("testFile.txt");

    InputStream testFileInStream = new FileInputStream(testFile);

    final File encFile = this.testFolder.newFile("testFile.txt.tar");
    this.fileEncrypter.encrypt("testFile.txt", (int) testFile.length(), testFileInStream,
            new FileOutputStream(encFile));

    //Decrypt with OpenSSL
    final File decryptFileScript = setupTempFile("decryptFile.sh");
    decryptFileScript.setExecutable(true);

    final File privateKey = setupTempFile("my.wisc.edu-private.pem");

    final ProcessBuilder pb = new ProcessBuilder(decryptFileScript.getAbsolutePath(),
            privateKey.getAbsolutePath(), encFile.getAbsolutePath());

    final Process p = pb.start();
    final int ret = p.waitFor();
    if (ret != 0) {
        final String pOut = IOUtils.toString(p.getInputStream(), TokenEncrypter.CHARSET).trim();
        System.out.println(pOut);
        final String pErr = IOUtils.toString(p.getErrorStream(), TokenEncrypter.CHARSET).trim();
        System.out.println(pErr);
    }//from  w w w  .  j a  v a  2s.c  o m
    assertEquals(0, ret);

    final File decryptedFile = new File(encFile.getParentFile(), "testFile.txt");

    //Verify
    final String expected = FileUtils.readFileToString(testFile);
    final String actual = FileUtils.readFileToString(decryptedFile);
    assertEquals(expected, actual);
}

From source file:de.tudarmstadt.ukp.csniper.webapp.search.tgrep.TgrepQuery.java

@Override
public List<EvaluationItem> execute() {
    BufferedReader brInput = null;
    BufferedReader brError = null;
    List<String> output = new ArrayList<String>();
    List<String> error = new ArrayList<String>();

    try {//from   ww  w  . j  a v a  2s.  co m
        List<String> cmd = new ArrayList<String>();

        File exe = engine.getTgrepExecutable();
        if (!exe.canExecute()) {
            exe.setExecutable(true);
        }

        cmd.add(exe.getAbsolutePath());
        // specify corpus
        cmd.add("-c");
        cmd.add(engine.getCorpusPath(corpus));
        // only one match per sentence
        cmd.add("-f");
        // print options
        cmd.add("-m");
        // comment
        // full sentence
        // match begin token index
        // match end token index
        cmd.add("%c\\n%tw\\n%ym\\n%zm\\n");
        // pattern to search for
        cmd.add(query);
        if (log.isTraceEnabled()) {
            log.trace("Invoking [" + StringUtils.join(cmd, " ") + "]");
        }

        final ProcessBuilder pb = new ProcessBuilder(cmd);
        tgrep = pb.start();

        brInput = new BufferedReader(new InputStreamReader(tgrep.getInputStream(), "UTF-8"));
        brError = new BufferedReader(new InputStreamReader(tgrep.getErrorStream(), "UTF-8"));

        String line;
        while ((line = brInput.readLine()) != null) {
            if (log.isTraceEnabled()) {
                log.trace("<< " + line);
            }
            output.add(line);
        }

        while ((line = brError.readLine()) != null) {
            if (log.isErrorEnabled()) {
                log.error(line);
            }
            error.add(line);
        }

        if (!error.isEmpty()) {
            throw new IOException(StringUtils.join(error, " "));
        }
    } catch (IOException e) {
        throw new DataAccessResourceFailureException("Unable to start Tgrep process.", e);
    } finally {
        IOUtils.closeQuietly(brInput);
        IOUtils.closeQuietly(brError);
    }

    size = output.size() / LINES_PER_MATCH;
    if (maxResults >= 0 && size > maxResults) {
        return parseOutput(output.subList(0, LINES_PER_MATCH * maxResults));
    } else {
        return parseOutput(output);
    }
}

From source file:com.openshift.internal.restclient.capability.resources.AbstractOpenShiftBinaryCapability.java

private void startProcess(String location) {
    String cmdLine = new StringBuilder(location).append(' ').append(buildArgs()).toString();
    String[] args = StringUtils.split(cmdLine, " ");
    ProcessBuilder builder = new ProcessBuilder(args);
    LOG.debug("OpenShift binary args: {}", builder.command());
    try {/*from  w w w .  j a v a 2 s  . c o  m*/
        process = builder.start();
        checkProcessIsAlive();
    } catch (IOException e) {
        LOG.error("Could not start process for {}.", new Object[] { getName(), e });
        throw new OpenShiftException(e, "Does your OpenShift binary location exist? Error starting process: %s",
                e.getMessage());
    }
}

From source file:com.temetra.vroomapi.RouteController.java

@RequestMapping(value = "/route", produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public JsonNode route(@RequestParam(value = "loc") String[] locs,
        @RequestParam(value = "startAtFirst", defaultValue = "true") boolean startAtFirst,
        @RequestParam(value = "endAtLast", defaultValue = "false") boolean endAtLast,
        @RequestParam(value = "includeGeometry", defaultValue = "false") boolean includeGeometry)
        throws Exception {
    long millis = System.currentTimeMillis();

    File vroomBinFile = new File(vroomBinary);
    if (!vroomBinFile.exists()) {
        log.error("Vroom binary file doesn't exist");
        throw new Exception("Vroom binary file doesn't exist");
    }/*from ww w.  ja  v a 2 s  .co  m*/

    if (!vroomBinFile.canExecute()) {
        log.error("Cannot execute Vroom binary file");
        throw new Exception("Cannot execute Vroom binary file");
    }

    if (locs.length < 2) {
        log.error("Zero or one location sent");
        throw new Exception("Must send more than one location");
    }

    List<String> progArgs = new ArrayList<>();
    progArgs.add("./" + vroomBinFile.getName());
    if (startAtFirst) {
        progArgs.add("-s");
    }
    if (endAtLast) {
        progArgs.add("-e");
    }
    if (includeGeometry) {
        progArgs.add("-g");
    }

    progArgs.add("loc=" + Joiner.on("&loc=").join(locs) + "");
    log.info("Run (" + millis + "): " + Joiner.on(' ').join(progArgs));

    StringBuilder output = new StringBuilder();
    ProcessBuilder builder = new ProcessBuilder(progArgs);
    builder.directory(vroomBinFile.getParentFile());
    builder.redirectErrorStream(true);
    Process process = builder.start();

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
        String line;
        while ((line = reader.readLine()) != null) {
            output.append(line);
        }
        process.waitFor();
    }

    log.info("Output (" + millis + "): " + output.toString());
    return jsonMapper.readTree(output.toString());
}

From source file:com.netflix.dynomitemanager.defaultimpl.StorageProcessManager.java

public void start() throws IOException {
    logger.info(String.format("Starting Storage process"));

    List<String> command = Lists.newArrayList();
    if (!"root".equals(System.getProperty("user.name"))) {
        command.add(SUDO_STRING);/*from  w w  w . j a  va  2  s.co m*/
        command.add("-n");
        command.add("-E");
    }
    command.addAll(getStartCommand());

    ProcessBuilder startStorage = new ProcessBuilder(command);

    startStorage.directory(new File("/"));
    startStorage.redirectErrorStream(true);
    Process starter = startStorage.start();

    try {
        sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS);
        int code = starter.exitValue();
        if (code == 0) {
            logger.info("Storage process has been started");
            instanceState.setStorageProxyAlive(true);
        } else {
            logger.error("Unable to start Storage process. Error code: {}", code);
        }

        logProcessOutput(starter);
    } catch (Exception e) {
        logger.warn("Starting Storage process has an error", e);
    }
}

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 w  w .ja  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;
}