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.netflix.dynomitemanager.defaultimpl.FloridaProcessManager.java

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

From source file:com.c4om.autoconf.ulysses.configanalyzer.guilauncher.ChromeAppEditorGUILauncher.java

/**
 * @see com.c4om.autoconf.ulysses.interfaces.configanalyzer.core.GUILauncher#launchGUI(com.c4om.autoconf.ulysses.interfaces.configanalyzer.core.datastructures.ConfigurationAnalysisContext, com.c4om.autoconf.ulysses.interfaces.Target)
 *///from w  w w .  j  a  va 2s .co  m
@SuppressWarnings("resource")
@Override
public void launchGUI(ConfigurationAnalysisContext context, Target target) throws GUILaunchException {
    try {
        List<File> temporaryFolders = this.getTemporaryStoredChangesetsAndConfigs(context, target);

        for (File temporaryFolder : temporaryFolders) {

            //The temporary folder where one subfolder per analyzer execution will be stored (and removed).
            File temporaryFolderRoot = temporaryFolder.getParentFile().getParentFile();

            System.out.println("Writing launch properties.");

            //Now, we build the properties file
            Properties launchProperties = new Properties();
            String relativeTemporaryFolder = temporaryFolder.getAbsolutePath()
                    .replaceAll("^" + Pattern.quote(temporaryFolderRoot.getAbsolutePath()), "")
                    .replaceAll("^" + Pattern.quote(File.separator), "")
                    .replaceAll(Pattern.quote(File.separator) + "$", "")
                    .replaceAll(Pattern.quote(File.separator) + "+", "/");
            //            launchProperties.put(KEY_LOAD_RECOMMENDATIONS_FILE, relativeTemporaryFolder+CHANGESET_TO_APPLY);
            launchProperties.put(KEY_CATALOG, relativeTemporaryFolder + CATALOG_FILE_PATH);
            Writer writer = new OutputStreamWriter(
                    new FileOutputStream(new File(temporaryFolderRoot, LAUNCH_PROPERTIES_FILE_NAME)),
                    Charsets.UTF_8);
            launchProperties.store(writer, "");
            writer.close();
            System.out.println("Launch properties written!!!!");

            System.out.println("Launching XML editor Chrome app");

            Properties configurationAnalyzerProperties = context.getConfigurationAnalyzerSettings();
            String chromeLocation = configurationAnalyzerProperties.getProperty(PROPERTIES_KEY_CHROME_LOCATION);
            String editorChromeAppLocation = configurationAnalyzerProperties
                    .getProperty(PROPERTIES_KEY_EDITOR_CHROME_APP_LOCATION);

            ProcessBuilder chromeEditorPB = new ProcessBuilder(
                    ImmutableList.of(chromeLocation, "--load-and-launch-app=" + editorChromeAppLocation));
            chromeEditorPB.directory(new File(editorChromeAppLocation));
            chromeEditorPB.start();
            System.out.println("Editor started!!!");
            System.out.println("Now, make all your changes and press ENTER when finished...");
            new Scanner(System.in).nextLine();
            FileUtils.forceDeleteOnExit(temporaryFolder.getParentFile());

        }
    } catch (IOException e) {
        throw new GUILaunchException(e);
    }
}

From source file:de.uzk.hki.da.convert.PublishVideoConversionStrategy.java

/**
 * @author Daniel M. de Oliveira// w w  w .  j  a  va  2 s  . co  m
 * @author Christian Weitz
 * @author Thomas Kleinke
 * 
 * @param cmd The command to execute
 * @param targetFile The target file to check regularly
 * @return true if the conversion was successful, otherwise false
 */
private boolean executeConversionTool(String[] cmd, File targetFile) {

    logger.debug("Running cmd \"{}\"", Arrays.toString(cmd));

    Process p = null;
    try {
        ProcessBuilder pb = new ProcessBuilder(cmd);
        p = pb.start();

        long targetFileSize = 0;
        long previousTargetFileSize = 0;
        do {
            previousTargetFileSize = targetFileSize;
            Thread.sleep(processTimeout);
            targetFileSize = targetFile.length();
        } while (previousTargetFileSize < targetFileSize);

        p.destroy();
    } catch (FileNotFoundException e) {
        logger.error("File not found in runShellCommand", e);
        return false;
    } catch (Exception e) {
        logger.error("Error in runShellCommand", e);
        return false;
    } finally {
        if (p != null)
            LinuxEnvironmentUtils.closeStreams(p);
    }

    return true;
}

From source file:edu.rice.dca.soaplabPBS.PBSJob.java

/**************************************************************************
 * Create and return a ProcessBuilder filled with the command-line
 * arguments and environment as defined in the metadata and user
 * input data for this job.//from w  w w .ja va2s  .  com
 *
 * It throws an exception when it was not able to fill the
 * ProcessBuilder.
 **************************************************************************/
protected ProcessBuilder getProcessBuilder() throws SoaplabException {

    // command-line arguments
    ProcessBuilder pb = new ProcessBuilder(createArgs());
    pb.command().add(0, getExecutableName());

    // environment from several sources...
    Map<String, String> env = pb.environment();
    // ...from the user (as defined by the service metadata)
    addProperties(env, createEnvs());
    // ...from the service configuration
    addProperties(env, Config.getMatchingProperties(Config.PROP_ENVAR, getServiceName(), this));
    // ...combine the current PATH and Soaplab's addtopath properties
    addToPath(env, Config.getStrings(Config.PROP_ADDTOPATH_DIR, null, getServiceName(), this));

    // working directory
    pb.directory(getJobDir());

    return pb;
}

From source file:cognition.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 www  .  java 2 s.  c om*/
    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();
        waitTask.cancel(true);
    } finally {
        IOUtils.closeQuietly(processInputStream);
        process.destroy();
        waitThread.interrupt();
        waitTask.cancel(true);
    }
    return null;
}

From source file:net.pms.util.ProcessUtil.java

public static String run(int[] expectedExitCodes, String... cmd) {
    try {/*from   w ww. ja v a2  s  .  com*/
        ProcessBuilder pb = new ProcessBuilder(cmd);
        pb.redirectErrorStream(true);
        Process p = pb.start();
        StringBuilder output;
        try (BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
            String line;
            output = new StringBuilder();
            while ((line = br.readLine()) != null) {
                output.append(line).append("\n");
            }
        }
        p.waitFor();
        boolean expected = false;
        if (expectedExitCodes != null) {
            for (int expectedCode : expectedExitCodes) {
                if (expectedCode == p.exitValue()) {
                    expected = true;
                    break;
                }
            }
        }
        if (!expected) {
            LOGGER.debug("Warning: command {} returned {}", Arrays.toString(cmd), p.exitValue());
        }
        return output.toString();
    } catch (Exception e) {
        LOGGER.error("Error running command " + Arrays.toString(cmd), e);
    }
    return "";
}

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

/**
 * Launches the Signature tool. It passes the .csi file to the signature tool.
 *///www .  j a  v a2  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:au.edu.unsw.cse.soc.federatedcloud.community.driven.cloudbase.connectors.docker.DockerConnector.java

@Override
public Result deploy(int resourceID) {
    String scriptFileLocation = "./tmp/" + resourceID + ".sh";
    //run the deployment script
    ProcessBuilder pb = new ProcessBuilder(scriptFileLocation);
    Map<String, String> env = pb.environment();
    pb.directory(new File("."));
    try {/*  w  ww  .j av  a2  s.  co  m*/
        Process p = pb.start();

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        // read the output from the command
        System.out.println("Here is the standard output of the command:\n");
        String s = null;
        while ((s = stdInput.readLine()) != null) {
            log.info(s);
        }

        // read any errors from the attempted command
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            log.info(s);
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

    return null;
}

From source file:com.l2jfree.sql.L2DataSourceMySQL.java

@Override
public void backup() {
    final String databaseName = getComboPooledDataSource().getJdbcUrl().replaceAll("^.*/", "");

    _log.info("DatabaseBackupManager: backing up `" + databaseName + "`...");

    final Process run;
    try {/*from  w  w w  .j a v a2s.c  om*/
        final ArrayList<String> commands = new ArrayList<String>();
        commands.add("mysqldump");
        commands.add(" --user=" + getComboPooledDataSource().getUser()); // The MySQL user name to use when connecting to the server
        commands.add(" --password=" + getComboPooledDataSource().getPassword()); // The password to use when connecting to the server
        commands.add("--compact"); // Produce more compact output.
        commands.add("--complete-insert"); // Use complete INSERT statements that include column names
        commands.add("--default-character-set=utf8"); // Use charset_name as the default character set
        commands.add("--extended-insert"); // Use multiple-row INSERT syntax that include several VALUES lists
        commands.add("--lock-tables"); // Lock all tables before dumping them
        commands.add("--quick"); // Retrieve rows for a table from the server a row at a time
        commands.add("--skip-triggers"); // Do not dump triggers
        commands.add(databaseName); // db_name

        final ProcessBuilder pb = new ProcessBuilder(commands);
        pb.directory(new File("."));

        run = pb.start();
    } catch (Exception e) {
        _log.warn("DatabaseBackupManager: Could not execute mysqldump!", e);
        return;
    }

    writeBackup(databaseName, run);
}

From source file:ml.shifu.shifu.core.alg.TensorflowTrainer.java

public void train() throws IOException {
    List<String> commands = buildCommands();
    ProcessBuilder pb = new ProcessBuilder(commands);

    pb.directory(new File("./"));
    pb.redirectErrorStream(true);//from ww w .j av  a2s.  c om
    LOGGER.info("Start trainning sub process. Commands {}", commands.toString());
    Process process = pb.start();
    StreamCollector sc = new StreamCollector(process.getInputStream());
    sc.start();

    try {
        process.waitFor();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } finally {
        if (sc != null) {
            sc.close();
        }
    }
}