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:net.solarnetwork.node.dao.jdbc.derby.DerbyOnlineSyncJob.java

private void performSync(String dbPath) {
    assert syncCommand != null;
    List<String> cmd = new ArrayList<String>(syncCommand.size());
    for (String param : syncCommand) {
        param = param.replace(SOURCE_DIRECTORY_PLACEHOLDER, dbPath);
        param = param.replace(DESTINATION_DIRECTORY_PLACEHOLDER, destinationPath);
        cmd.add(param);/*ww w .  j ava 2 s . c  o m*/
    }
    if (log.isDebugEnabled()) {
        StringBuilder buf = new StringBuilder();
        for (String p : cmd) {
            if (buf.length() > 0) {
                buf.append(' ');
            }
            buf.append(p);
        }
        log.debug("Derby sync command: {}", buf.toString());
    }
    ProcessBuilder pb = new ProcessBuilder(cmd);
    BufferedReader in = null;
    PrintWriter out = null;
    try {
        Process pr = pb.start();
        pr.waitFor();
        if (pr.exitValue() == 0) {
            if (log.isDebugEnabled()) {
                in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
                StringBuilder buf = new StringBuilder();
                String line = null;
                while ((line = in.readLine()) != null) {
                    buf.append(line).append('\n');
                }
                log.debug("Derby sync command output:\n{}", buf.toString());
            }
            log.info("Derby backup sync complete");
        } else {
            StringBuilder buf = new StringBuilder();
            in = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                buf.append(line).append('\n');
            }
            log.error("Sync command returned non-zero exit code {}: {}", pr.exitValue(), buf.toString().trim());
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                // ignore
            }
        }
        if (out != null) {
            out.flush();
            out.close();
        }
    }

}

From source file:hydrograph.ui.perspective.ApplicationWorkbenchWindowAdvisor.java

/**
 * This function will be return process ID which running on defined port
 *
 *//*from   w w w. j ava 2  s  .  c om*/
public String getServicePortPID(String portNumber) throws IOException {
    if (OSValidator.isWindows()) {
        ProcessBuilder builder = new ProcessBuilder(
                new String[] { "cmd", "/c", "netstat -a -o -n |findstr :" + portNumber });
        Process process = builder.start();
        InputStream inputStream = process.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String str = bufferedReader.readLine();
        str = StringUtils.substringAfter(str, "LISTENING");
        str = StringUtils.trim(str);
        return str;
    }
    return "";
}

From source file:io.github.jeremgamer.preview.actions.Launch.java

private void launch() {
    try {/*from   w  w  w  .  j a va 2  s . co m*/
        extractNatives();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    final Gson gson = new Gson();
    List<String> command = new ArrayList<String>();
    command.add(JAVA_DIR);
    command.add("-Djava.library.path=" + VANILLA_NATIVE_DIR.replaceAll("<version>", "1.8.1"));
    command.add("-cp");
    command.add(LIBRARIES + VANILLA_PATH.replaceAll("<version>", "1.8.1"));
    command.add(MAIN_CLASS);
    command.add("--username=" + name);
    command.add("--version=1.8.1");
    command.add("--gameDir=" + VANILLA_GAME_DIRECTORY);
    command.add("--assetsDir=" + VANILLA_GAME_DIRECTORY + "\\assets");
    command.add("--assetIndex=" + "1.8.1");
    command.add("--uuid=" + userID);
    command.add("--accessToken=" + accessToken);
    command.add("--userProperties=" + gson.toJson(user));
    command.add("--userType=mojang");
    for (String s : command) {
        System.out.println(s);
    }
    try {
        ProcessBuilder pb = new ProcessBuilder(command.toArray(new String[command.size()]))
                .directory(new File(VANILLA_GAME_DIRECTORY));
        final Process process = pb.start();
        StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "ERROR");
        errorGobbler.start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:de.tarent.maven.plugins.pkg.Utils.java

/**
 * A method which makes executing programs easier.
 * /*from   w  w  w  . ja  va2 s  .co  m*/
 * @param args
 * @param failureMsg
 * @param ioExceptionMsg
 * @throws MojoExecutionException
 */
public static InputStream exec(String[] args, File workingDir, String failureMsg, String ioExceptionMsg,
        String userInput) throws MojoExecutionException {
    /*
     * debug code which prints out the execution command-line. Enable if
     * neccessary. for(int i=0;i<args.length;i++) { System.err.print(args[i]
     * + " "); } System.err.println();
     */

    // Creates process with the defined language setting of LC_ALL=C
    // That way the textual output of certain commands is predictable.
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.directory(workingDir);
    Map<String, String> env = pb.environment();
    env.put("LC_ALL", "C");

    Process p = null;

    try {

        p = pb.start();

        if (userInput != null) {
            PrintWriter writer = new PrintWriter(
                    new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
            writer.println(userInput);
            writer.flush();
            writer.close();
        }
        int exitValue = p.waitFor();
        if (exitValue != 0) {
            print(p);
            throw new MojoExecutionException(
                    String.format("(Subprocess exit value = %s) %s", exitValue, failureMsg));
        }
    } catch (IOException ioe) {
        throw new MojoExecutionException(ioExceptionMsg + " :" + ioe.getMessage(), ioe);
    } catch (InterruptedException ie) {
        // Cannot happen.
        throw new MojoExecutionException("InterruptedException", ie);
    }
    return p.getInputStream();
}

From source file:io.hops.hopsworks.api.zeppelin.util.ZeppelinResource.java

private void forceKillProccess(String pid) {
    String[] command = { "kill", "-9", pid };
    ProcessBuilder pb = new ProcessBuilder(command);
    if (pid == null) {
        return;/*  w w w .  j a  v  a  2s  . co m*/
    }
    try {
        Process p = pb.start();
        p.waitFor();
        p.exitValue();
    } catch (IOException | InterruptedException ex) {
        logger.log(Level.WARNING, "Problem killing Zeppelin Interpreter: {0}", ex.toString());
    }
}

From source file:com.easytrack.component.system.LicenseCheck.java

public List getLinuxMACAddress() {
    ArrayList address = new ArrayList();
    try {/*from   w w w . j a va 2 s . co m*/
        ProcessBuilder pb = new ProcessBuilder(new String[] { "/sbin/ifconfig", "-a" });
        Process p = pb.start();
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            System.out.println(line);
            if (line.indexOf(" HWaddr") != -1) {
                int index = line.indexOf("HWaddr");
                String mac = line.substring(index + 7);
                address.add(mac);
            }
        }
        br.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return address;
}

From source file:com.mesosphere.dcos.cassandra.executor.tasks.RestoreSnapshot.java

@Override
public void run() {
    try {//from www.j  a  va2s . c  o  m
        // Send TASK_RUNNING
        sendStatus(driver, Protos.TaskState.TASK_RUNNING, "Started restoring snapshot");

        if (Objects.equals(context.getRestoreType(), new String("new"))) {
            final String keyspaceDirectory = context.getLocalLocation() + File.separator + context.getName()
                    + File.separator + context.getNodeId();

            final String ssTableLoaderBinary = CassandraPaths.create(version).bin().resolve("sstableloader")
                    .toString();
            final String cassandraYaml = CassandraPaths.create(version).cassandraConfig().toString();

            final File keyspacesDirectory = new File(keyspaceDirectory);
            LOGGER.info("Keyspace Directory {} exists: {}", keyspaceDirectory, keyspacesDirectory.exists());

            final File[] keyspaces = keyspacesDirectory.listFiles();

            String libProcessAddress = System.getenv("LIBPROCESS_IP");
            libProcessAddress = StringUtils.isBlank(libProcessAddress)
                    ? InetAddress.getLocalHost().getHostAddress()
                    : libProcessAddress;

            for (File keyspace : keyspaces) {
                final File[] columnFamilies = keyspace.listFiles();

                final String keyspaceName = keyspace.getName();
                if (keyspaceName.equals(StorageUtil.SCHEMA_FILE))
                    continue;
                LOGGER.info("Going to bulk load keyspace: {}", keyspaceName);

                for (File columnFamily : columnFamilies) {
                    final String columnFamilyName = columnFamily.getName();
                    if (columnFamilyName.equals(StorageUtil.SCHEMA_FILE))
                        continue;
                    LOGGER.info("Bulk loading... keyspace: {} column family: {}", keyspaceName,
                            columnFamilyName);

                    final String columnFamilyPath = columnFamily.getAbsolutePath();
                    final List<String> command = Arrays.asList(ssTableLoaderBinary, "-d", libProcessAddress,
                            "-u", context.getUsername(), "-pw", context.getPassword(), "-f", cassandraYaml,
                            columnFamilyPath);
                    LOGGER.info("Executing command: {}", command);

                    final ProcessBuilder processBuilder = new ProcessBuilder(command);
                    processBuilder.redirectErrorStream(true);
                    Process process = processBuilder.start();

                    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        LOGGER.info(line);
                    }

                    int exitCode = process.waitFor();
                    LOGGER.info("Command exit code: {}", exitCode);

                    // Send TASK_ERROR
                    if (exitCode != 0) {
                        final String errMessage = String.format("Error restoring snapshot. Exit code: %s",
                                (exitCode + ""));
                        LOGGER.error(errMessage);
                        sendStatus(driver, Protos.TaskState.TASK_ERROR, errMessage);
                    }

                    LOGGER.info("Done bulk loading! keyspace: {} column family: {}", keyspaceName,
                            columnFamilyName);
                }
                LOGGER.info("Successfully bulk loaded keyspace: {}", keyspaceName);
            }
            // cleanup downloaded snapshot directory recursively.
            Path rootPath = Paths.get(context.getLocalLocation() + File.separator + context.getName());
            if (rootPath.toFile().exists()) {
                Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder())
                        .map(Path::toFile).forEach(File::delete);
            }
        } else {
            // run nodetool refresh rather than SSTableLoader, as on performance test
            // I/O stream was pretty slow between mesos container processes
            final String localLocation = context.getLocalLocation();
            final List<String> keyspaces = cassandra.getNonSystemKeySpaces();
            for (String keyspace : keyspaces) {
                final String keySpaceDirPath = localLocation + "/" + keyspace;
                File keySpaceDir = new File(keySpaceDirPath);
                File[] cfNames = keySpaceDir
                        .listFiles((current, name) -> new File(current, name).isDirectory());
                for (File cfName : cfNames) {
                    String columnFamily = cfName.getName().substring(0, cfName.getName().indexOf("-"));
                    cassandra.getProbe().loadNewSSTables(keyspace, columnFamily);
                    LOGGER.info("Completed nodetool refresh for keyspace {} & columnfamily {}", keyspace,
                            columnFamily);
                }
            }
        }

        final String message = "Finished restoring snapshot";
        LOGGER.info(message);
        sendStatus(driver, Protos.TaskState.TASK_FINISHED, message);
    } catch (Throwable t) {
        // Send TASK_FAILED
        final String errorMessage = "Failed restoring snapshot. Reason: " + t;
        LOGGER.error(errorMessage, t);
        sendStatus(driver, Protos.TaskState.TASK_FAILED, errorMessage);
    }
}

From source file:edu.cornell.med.icb.clustering.MCLClusterer.java

/**
 * Groups instances into clusters. Returns the indices of the instances that belong to a cluster
 * as an int array in the list result.//from  w w w .ja  v  a  2s .c  om
 *
 * @param calculator The {@link SimilarityDistanceCalculator}
 * that should be used when clustering
 * @param qualityThreshold The QT clustering algorithm quality threshold (d)
 * @return The list of clusters.
 */
public List<int[]> cluster(final SimilarityDistanceCalculator calculator, final double qualityThreshold) {
    if (mclCommand == null) {
        throw new IllegalStateException("mcl command not set!");
    }

    // reset cluster results
    clusterCount = 0;
    for (int i = 0; i < instanceCount; i++) {
        clusters[i].clear();
    }

    BufferedReader br = null;
    try {
        final File mclInputFile = File.createTempFile("mcl-input", ".txt");
        writeMCLInputFile(mclInputFile, calculator, qualityThreshold);

        final File mclOutputFile = File.createTempFile("mcl-output", ".txt");
        final String[] command = { mclCommand, mclInputFile.getAbsolutePath(), "--abc", "-o",
                mclOutputFile.getAbsolutePath() };

        LOGGER.info("Executing: " + ArrayUtils.toString(command));

        final ProcessBuilder builder = new ProcessBuilder(command);
        builder.redirectErrorStream(true);
        final Process process = builder.start();
        final InputStream is = process.getInputStream();
        final InputStreamReader isr = new InputStreamReader(is);
        br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null) {
            LOGGER.info(line);
        }
        process.waitFor();

        LOGGER.info("Program terminated!");

        readMCLOutputFile(mclOutputFile);
    } catch (IOException e) {
        LOGGER.error("Counldn't create MCL file", e);
        throw new ClusteringException("Counldn't create MCL file", e);
    } catch (InterruptedException e) {
        LOGGER.error("Interrupted!", e);
        Thread.currentThread().interrupt();
    } finally {
        IOUtils.closeQuietly(br);
    }

    return getClusters();
}

From source file:net.solarnetwork.node.control.ping.HttpRequesterJob.java

private void handleOSCommand(String command) {
    if (command == null) {
        return;/*w  ww .  ja va  2 s . c om*/
    }
    ProcessBuilder pb = new ProcessBuilder(command.split("\\s+"));
    try {
        Process pr = pb.start();
        logInputStream(pr.getInputStream(), false);
        logInputStream(pr.getErrorStream(), true);
        pr.waitFor();
        if (pr.exitValue() == 0) {
            log.debug("Command [{}] executed", command);
            handleCommandSleep();
        } else {
            log.error("Error executing [{}], exit status: {}", command, pr.exitValue());
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.mashupmedia.encode.ProcessManager.java

public void startProcess(ProcessQueueItem processQueueItem) throws IOException {

    try {/*from w ww. j av a 2s.c  o  m*/
        logger.info("Starting process...");
        List<String> commands = processQueueItem.getCommands();

        ProcessBuilder processBuilder = new ProcessBuilder(commands);
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();

        // The started on date should have already been set
        Date startedOn = processQueueItem.getProcessStartedOn();
        if (startedOn == null) {
            processQueueItem.setProcessStartedOn(new Date());
        }

        processQueueItem.setProcess(process);

        InputStream inputStream = process.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line;

        while ((line = bufferedReader.readLine()) != null) {
            logger.info(line);
        }
        IOUtils.closeQuietly(inputStream);

        try {
            int waitForValue = process.waitFor();
            logger.info("Process waitFor value = " + waitForValue);
        } catch (InterruptedException e) {
            logger.error("Error waiting for waitFor.", e);
        }

        int exitValue = process.exitValue();
        logger.info("Process exit value = " + exitValue);

    } finally {
        processQueueItems.remove(processQueueItem);
        encodeMediaItemTaskManager.processQueue();
    }

}