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:gui.sqlmap.SqlmapUi.java

private void startSqlmap() {
    String python = textfieldPython.getText();
    String workingDir = textfieldWorkingdir.getText();
    String sqlmap = textfieldSqlmap.getText();

    // Do some basic tests
    File f;/*ww w.j a v a  2s  .  co  m*/
    f = new File(python);
    if (!f.exists()) {
        JOptionPane.showMessageDialog(this, "Python path does not exist: " + python);
        return;
    }
    f = new File(workingDir);
    if (!f.exists()) {
        JOptionPane.showMessageDialog(this, "workingDir path does not exist: " + workingDir);
        return;
    }
    f = new File(sqlmap);
    if (!f.exists()) {
        JOptionPane.showMessageDialog(this, "sqlmap path does not exist: " + sqlmap);
        return;
    }

    // Write request file
    String requestFile = workingDir + "request.txt";
    try {
        FileOutputStream fos = new FileOutputStream(requestFile);
        fos.write(httpMessage.getRequest());
        fos.close();
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, "could not write request: " + workingDir + "request.txt");
        BurpCallbacks.getInstance().print("Error: " + e.getMessage());
    }

    // Start sqlmap
    args = new ArrayList<String>();
    args.add(python);
    args.add(sqlmap);
    args.add("-r");
    args.add(requestFile);
    args.add("--batch");

    args.add("-p");
    args.add(attackParam.getName());

    String sessionFile = workingDir + "sessionlog.txt";
    args.add("-s");
    args.add(sessionFile);
    args.add("--flush-session");

    String traceFile = workingDir + "tracelog.txt";
    args.add("-t");
    args.add(traceFile);

    args.add("--disable-coloring");
    args.add("--cleanup");

    textareaCommand.setText(StringUtils.join(args, " "));

    SwingWorker worker = new SwingWorker<String, Void>() {
        @Override
        public String doInBackground() {
            ProcessBuilder pb = new ProcessBuilder(args);
            //BurpCallbacks.getInstance().print(pb.command().toString());
            pb.redirectErrorStream(true);
            Process proc;
            try {
                proc = pb.start();

                InputStream is = proc.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);

                String line;
                int exit = -1;

                while ((line = br.readLine()) != null) {
                    // Outputs your process execution
                    addLine(line);
                    try {
                        exit = proc.exitValue();
                        if (exit == 0) {
                            // Process finished
                        }
                    } catch (IllegalThreadStateException t) {
                        // The process has not yet finished. 
                        // Should we stop it?
                        //if (processMustStop()) // processMustStop can return true 
                        // after time out, for example.
                        //{
                        //    proc.destroy();
                        //}
                    }
                }
            } catch (IOException ex) {
                BurpCallbacks.getInstance().print(ex.getLocalizedMessage());
            }
            return "";
        }

        @Override
        public void done() {
        }
    };

    worker.execute();

}

From source file:jenkins.plugins.shiningpanda.ShiningPandaTestCase.java

/**
 * Create a VIRTUALENV.//  www.  ja va  2  s  .  c o m
 * 
 * @param home
 *            The home of this VIRTUALENV.
 * @return The home of the VIRTUALENV
 * @throws Exception
 */
protected File createVirtualenv(File home) throws Exception {
    // Clean
    deleteVirtualenv(home);
    // Create a process to create the VIRTUALENV
    ProcessBuilder pb = new ProcessBuilder("virtualenv", home.getAbsolutePath());
    // Start the process
    Process process = pb.start();
    // Check exit code
    assertEquals(0, process.waitFor());
    // Return the home folder
    return home;
}

From source file:com.asakusafw.testdriver.DefaultJobExecutor.java

private int runCommand(List<String> commandLine, Map<String, String> environmentVariables) throws IOException {
    LOG.info(MessageFormat.format(Messages.getString("DefaultJobExecutor.infoEchoCommandLine"), //$NON-NLS-1$
            toCommandLineString(commandLine)));

    ProcessBuilder builder = new ProcessBuilder(commandLine);
    builder.redirectErrorStream(true);/*w  w w.  java  2s. c o  m*/
    builder.environment().putAll(environmentVariables);
    File hadoopCommand = configurations.getHadoopCommand();
    if (hadoopCommand != null) {
        builder.environment().put("HADOOP_CMD", hadoopCommand.getAbsolutePath()); //$NON-NLS-1$
    }
    builder.directory(new File(System.getProperty("user.home", "."))); //$NON-NLS-1$ //$NON-NLS-2$

    int exitCode;
    Process process = builder.start();
    try (InputStream is = process.getInputStream()) {
        InputStreamThread it = new InputStreamThread(is);
        it.start();
        exitCode = process.waitFor();
        it.join();
    } catch (InterruptedException e) {
        throw new IOException(
                MessageFormat.format(Messages.getString("DefaultJobExecutor.errorExecutionInterrupted"), //$NON-NLS-1$
                        toCommandLineString(commandLine)),
                e);
    } finally {
        process.getOutputStream().close();
        process.getErrorStream().close();
        process.destroy();
    }
    return exitCode;
}

From source file:com.cloud.utils.script.Script.java

public String execute(OutputInterpreter interpreter) {
    String[] command = _command.toArray(new String[_command.size()]);

    if (_logger.isDebugEnabled()) {
        _logger.debug("Executing: " + buildCommandLine(command));
    }// w  w w . ja  v a  2s .c  o  m

    try {
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.redirectErrorStream(true);
        if (_workDir != null)
            pb.directory(new File(_workDir));

        _process = pb.start();
        if (_process == null) {
            _logger.warn("Unable to execute: " + buildCommandLine(command));
            return "Unable to execute the command: " + command[0];
        }

        BufferedReader ir = new BufferedReader(new InputStreamReader(_process.getInputStream()));

        _thread = Thread.currentThread();
        ScheduledFuture<String> future = null;
        if (_timeout > 0) {
            future = s_executors.schedule(this, _timeout, TimeUnit.MILLISECONDS);
        }

        Task task = null;
        if (interpreter != null && interpreter.drain()) {
            task = new Task(interpreter, ir);
            s_executors.execute(task);
        }

        while (true) {
            try {
                if (_process.waitFor() == 0) {
                    _logger.debug("Execution is successful.");
                    if (interpreter != null) {
                        return interpreter.drain() ? task.getResult() : interpreter.interpret(ir);
                    } else {
                        // null return exitValue apparently
                        return String.valueOf(_process.exitValue());
                    }
                } else {
                    break;
                }
            } catch (InterruptedException e) {
                if (!_isTimeOut) {
                    /*
                     * This is not timeout, we are interrupted by others,
                     * continue
                     */
                    _logger.debug("We are interrupted but it's not a timeout, just continue");
                    continue;
                }

                TimedOutLogger log = new TimedOutLogger(_process);
                Task timedoutTask = new Task(log, ir);

                timedoutTask.run();
                if (!_passwordCommand) {
                    _logger.warn("Timed out: " + buildCommandLine(command) + ".  Output is: "
                            + timedoutTask.getResult());
                } else {
                    _logger.warn("Timed out: " + buildCommandLine(command));
                }

                return ERR_TIMEOUT;
            } finally {
                if (future != null) {
                    future.cancel(false);
                }
                Thread.interrupted();
            }
        }

        _logger.debug("Exit value is " + _process.exitValue());

        BufferedReader reader = new BufferedReader(new InputStreamReader(_process.getInputStream()), 128);

        String error;
        if (interpreter != null) {
            error = interpreter.processError(reader);
        } else {
            error = String.valueOf(_process.exitValue());
        }

        if (_logger.isDebugEnabled()) {
            _logger.debug(error);
        }
        return error;
    } catch (SecurityException ex) {
        _logger.warn("Security Exception....not running as root?", ex);
        return stackTraceAsString(ex);
    } catch (Exception ex) {
        _logger.warn("Exception: " + buildCommandLine(command), ex);
        return stackTraceAsString(ex);
    } finally {
        if (_process != null) {
            IOUtils.closeQuietly(_process.getErrorStream());
            IOUtils.closeQuietly(_process.getOutputStream());
            IOUtils.closeQuietly(_process.getInputStream());
            _process.destroy();
        }
    }
}

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

@Override
public String setOneInput(ReferenceService referenceService, T2Reference t2Reference, ScriptInput input)
        throws InvocationException {

    if (input.getCharsetName() == null) {
        input.setCharsetName(Charset.defaultCharset().name());
    }/*from   ww  w.j av  a 2 s . c om*/
    String target = null;
    String targetSuffix = null;
    if (input.isFile()) {
        targetSuffix = input.getTag();
    } else if (input.isTempFile()) {
        targetSuffix = "tempfile." + (nTempFiles++) + ".tmp";
    }

    if (input.isBinary()) {
        return setOneBinaryInput(referenceService, t2Reference, input, targetSuffix);
    }

    logger.info("Target is " + target);
    if (input.isFile() || input.isTempFile()) {
        target = tempDir.getAbsolutePath() + "/" + targetSuffix;
        // Try to get it as a file
        Reader r;
        Writer w;
        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);
                        }

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

                }
            }

            if (fileRef.getDataNature().equals(ReferencedDataNature.TEXT)) {
                r = new InputStreamReader(fileRef.openStream(this.getContext()),
                        Charset.forName(fileRef.getCharset()));
            } else {
                try {
                    r = new FileReader(fileRef.getFile());
                } catch (FileNotFoundException e) {
                    throw new InvocationException(e);
                }
            }
        } else {
            r = new InputStreamReader(getAsStream(referenceService, t2Reference));
        }
        try {
            w = new OutputStreamWriter(new FileOutputStream(target), input.getCharsetName());
        } catch (UnsupportedEncodingException e) {
            throw new InvocationException(e);
        } catch (FileNotFoundException e) {
            throw new InvocationException(e);
        }
        try {
            IOUtils.copyLarge(r, w);
        } catch (IOException e) {
            throw new InvocationException(e);
        }
        try {
            r.close();
            w.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.smash.revolance.ui.materials.CmdlineHelper.java

public CmdlineHelper exec() throws InterruptedException, IOException {
    ProcessBuilder pb = new ProcessBuilder();

    if (dir != null) {
        pb.directory(dir);//from   w ww  .ja va2  s  .com
    }

    pb.command(cmd);

    pb.redirectError(ProcessBuilder.Redirect.to(err));
    pb.redirectOutput(ProcessBuilder.Redirect.to(out));
    pb.redirectInput(ProcessBuilder.Redirect.from(in));

    System.out.println("Executing cmd: " + cmd[0] + " from dir: " + dir);
    System.out.println("Redirecting out to: " + out.getAbsolutePath());
    System.out.println("Redirecting err to: " + err.getAbsolutePath());

    Process process = pb.start();
    if (sync) {
        process.waitFor();
    }

    this.process = process;

    return this;
}

From source file:com.yfiton.oauth.receiver.GraphicalReceiver.java

@Override
public AuthorizationData requestAuthorizationData(String authorizationUrl,
        String authorizationCodeParameterName, String... requestParameterNames) throws NotificationException {
    try {//  w  w  w .ja v  a  2 s.c om
        File tmpFile = File.createTempFile("yfiton", ".auth");

        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.inheritIO();
        processBuilder.command("java",
                //"-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005",
                "-classpath", getClasspath(), WebBrowser.class.getName(),
                "--authorization-code-parameter-name=" + authorizationCodeParameterName,
                "--authorization-file=" + tmpFile.getAbsolutePath(), "--authorization-url=" + authorizationUrl,
                "--debug=" + (debug ? "true" : "false"),
                "--webengine-listener-class=" + webEngineListenerClazz.getName());

        Process process = processBuilder.start();

        int returnCode = process.waitFor();

        switch (returnCode) {
        case 0:
            return OAuthUtils.readAuthorizationInfo(tmpFile.toPath());
        case 255:
            throw new NotificationException("Authorization process aborted");
        default:
            throw new NotificationException(
                    "Error occurred while waiting for process: return code " + returnCode);
        }
    } catch (ClassNotFoundException | ConfigurationException | IOException | InterruptedException e) {
        throw new NotificationException(e.getMessage());
    }
}

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

@Override
public void exportSchema(ExportParams params) throws MojoExecutionException {
    BufferedInputStream in = null;
    FileOutputStream out = null;/*from   ww  w.ja  v a2 s  .c  o m*/
    try {
        File dumpFile = params.getDumpFile();
        String user = params.getUser();
        String password = params.getPassword();
        String schema = params.getSchema();

        ProcessBuilder pb = new ProcessBuilder("pg_dump", "--host=" + getHost(), "--port=" + getPort(),
                "--username=" + user, "--schema=" + schema, "-c", getDatabase());
        pb.redirectErrorStream(true);
        if (StringUtils.isNotEmpty(password)) {
            // ??????????
            pb.environment().put("PGPASSWORD", password);
        }

        Process process = pb.start();
        in = new BufferedInputStream(process.getInputStream());

        out = FileOutputStreamUtil.create(dumpFile);
        byte[] buf = new byte[4096];
        while (true) {
            int res = in.read(buf);
            if (res <= 0)
                break;
            out.write(buf, 0, res);
        }

    } catch (IOException e) {
        throw new MojoExecutionException("??", e);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:org.generationcp.ibpworkbench.launcher.Launcher.java

protected void launchMySQLProcess() {
    File workingDirPath = new File(mysqlBinDir).getAbsoluteFile();
    String mysqldPath = "mysqld.exe";
    String myIniPath = "../my.ini";

    ProcessBuilder pb = new ProcessBuilder(workingDirPath.getAbsolutePath() + File.separator + mysqldPath,
            "--defaults-file=" + myIniPath);
    pb.directory(workingDirPath);/* w  w  w. j a  v  a  2 s .  c  o m*/
    try {
        mysqlProcess = pb.start();
    } catch (IOException e) {
        LOG.error("IOException", e);
    }
}

From source file:edu.cmu.cs.diamond.android.Filter.java

public Filter(int resourceId, Context context, String name, String[] args, byte[] blob) throws IOException {
    Resources r = context.getResources();
    String resourceName = r.getResourceEntryName(resourceId);
    File f = context.getFileStreamPath(resourceName);

    if (!f.exists()) {
        InputStream ins = r.openRawResource(resourceId);
        byte[] buf = IOUtils.toByteArray(ins);
        FileOutputStream fos = context.openFileOutput(resourceName, Context.MODE_PRIVATE);
        IOUtils.write(buf, fos);//w  w w  . j  a  v a  2s .c o m
        context.getFileStreamPath(resourceName).setExecutable(true);
        fos.close();
    }

    ProcessBuilder pb = new ProcessBuilder(f.getAbsolutePath());
    Map<String, String> env = pb.environment();
    tempDir = File.createTempFile("filter", null, context.getCacheDir());
    tempDir.delete(); // Delete file and create directory.
    if (!tempDir.mkdir()) {
        throw new IOException("Unable to create temporary directory.");
    }
    env.put("TEMP", tempDir.getAbsolutePath());
    env.put("TMPDIR", tempDir.getAbsolutePath());
    proc = pb.start();
    is = proc.getInputStream();
    os = proc.getOutputStream();

    sendInt(1);
    sendString(name);
    sendStringArray(args);
    sendBinary(blob);

    while (this.getNextToken().tag != TagEnum.INIT)
        ;
    Log.d(TAG, "Filter initialized.");
}