Example usage for java.lang Process getInputStream

List of usage examples for java.lang Process getInputStream

Introduction

In this page you can find the example usage for java.lang Process getInputStream.

Prototype

public abstract InputStream getInputStream();

Source Link

Document

Returns the input stream connected to the normal output of the process.

Usage

From source file:io.hops.hopsworks.common.security.PKIUtils.java

public static void revokeCert(Settings settings, String certFile, boolean intermediate)
        throws IOException, InterruptedException {
    logger.info("Revoking certificate...");
    List<String> cmds = new ArrayList<>();
    cmds.add("openssl");
    cmds.add("ca");
    cmds.add("-batch");
    cmds.add("-config");
    if (intermediate) {
        cmds.add(settings.getIntermediateCaDir() + "/openssl-intermediate.cnf");
    } else {/*from   w  w w . ja v a  2 s.  co m*/
        cmds.add(settings.getCaDir() + "/openssl-ca.cnf");
    }
    cmds.add("-passin");
    cmds.add("pass:" + settings.getHopsworksMasterPasswordSsl());
    cmds.add("-revoke");
    cmds.add(certFile);

    StringBuilder sb = new StringBuilder("/usr/bin/");
    for (String s : cmds) {
        sb.append(s).append(" ");
    }
    logger.info(sb.toString());

    Process process = new ProcessBuilder(cmds).directory(new File("/usr/bin/")).redirectErrorStream(true)
            .start();
    BufferedReader br = new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charset.forName("UTF8")));
    String line;
    while ((line = br.readLine()) != null) {
        logger.info(line);
    }
    process.waitFor();
    int exitValue = process.exitValue();
    if (exitValue != 0) {
        throw new RuntimeException("Failed to revoke certificate. Exit value: " + exitValue);
    }
    logger.info("Revoked certificate.");
    //update the crl
    createCRL(settings, intermediate);
}

From source file:io.hops.hopsworks.common.security.PKIUtils.java

public static String verifyCertificate(Settings settings, String cert, boolean intermediate)
        throws IOException, InterruptedException {
    File certFile = File.createTempFile(System.getProperty("java.io.tmpdir"), ".pem");
    FileUtils.writeStringToFile(certFile, cert);
    String certDir = intermediate ? settings.getIntermediateCaDir() : settings.getCaDir();
    String crlFile = intermediate ? certDir + "/crl/intermediate.crl.pem" : certDir + "/crl/ca.crl.pem";
    String pubCert = intermediate ? "/intermediate/certs/intermediate.cert.pem " : "/certs/ca.cert.pem ";
    //update the crl
    createCRL(settings, intermediate);//from  www. j  av a 2s  .c o m
    logger.info("Checking certificate...");
    List<String> cmds = new ArrayList<>();
    cmds.add("openssl");
    cmds.add("verify");
    cmds.add("-crl_check");
    cmds.add("-CAfile");
    cmds.add("<(cat " + certDir + pubCert + crlFile + ")");
    cmds.add(certFile.getAbsolutePath());
    StringBuilder sb = new StringBuilder("/usr/bin/");
    for (String s : cmds) {
        sb.append(s).append(" ");
    }
    logger.info(sb.toString());

    Process process = new ProcessBuilder(cmds).directory(new File("/usr/bin/")).redirectErrorStream(true)
            .start();
    BufferedReader br = new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charset.forName("UTF8")));
    String line;
    StringBuilder lines = new StringBuilder("");
    while ((line = br.readLine()) != null) {
        logger.info(line);
        lines.append(line);
    }
    process.waitFor();
    int exitValue = process.exitValue();
    if (exitValue != 0) {
        throw new RuntimeException("Failed cert check. Exit value: " + exitValue);
    }
    logger.info("Done cert check.");
    return lines.toString();
}

From source file:io.hops.hopsworks.common.security.PKIUtils.java

public static String createCRL(Settings settings, boolean intermediate)
        throws IOException, InterruptedException {
    logger.info("Creating crl...");
    String generatedCrlFile;//from w w w  .ja v a  2s  .  c  o  m
    List<String> cmds = new ArrayList<>();
    cmds.add("openssl");
    cmds.add("ca");
    cmds.add("-batch");
    cmds.add("-config");
    if (intermediate) {
        cmds.add(settings.getIntermediateCaDir() + "/openssl-intermediate.cnf");
        generatedCrlFile = settings.getIntermediateCaDir() + "/crl/intermediate.crl.pem";
    } else {
        cmds.add(settings.getCaDir() + "/openssl-ca.cnf");
        generatedCrlFile = settings.getCaDir() + "/crl/ca.crl.pem";
    }
    cmds.add("-passin");
    cmds.add("pass:" + settings.getHopsworksMasterPasswordSsl());
    cmds.add("-gencrl");
    cmds.add("-out");
    cmds.add(generatedCrlFile);

    StringBuilder sb = new StringBuilder("/usr/bin/");
    for (String s : cmds) {
        sb.append(s).append(" ");
    }
    logger.info(sb.toString());

    Process process = new ProcessBuilder(cmds).directory(new File("/usr/bin/")).redirectErrorStream(true)
            .start();
    BufferedReader br = new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charset.forName("UTF8")));
    String line;
    while ((line = br.readLine()) != null) {
        logger.info(line);
    }
    process.waitFor();
    int exitValue = process.exitValue();
    if (exitValue != 0) {
        throw new RuntimeException("Failed to create crl. Exit value: " + exitValue);
    }
    logger.info("Created crl.");
    return FileUtils.readFileToString(new File(generatedCrlFile));
}

From source file:com.sinpo.xnfc.nfc.Util.java

public static String execRootCmd(String cmd) {
    String result = "";
    DataOutputStream dos = null;//from w  w  w  .ja v a 2 s. com
    DataInputStream dis = null;

    try {
        Process p = Runtime.getRuntime().exec("su");
        dos = new DataOutputStream(p.getOutputStream());
        dis = new DataInputStream(p.getInputStream());

        dos.writeBytes(cmd + "\n");
        dos.flush();
        dos.writeBytes("exit\n");
        dos.flush();
        String line = null;
        while ((line = dis.readLine()) != null) {
            result += line + "\r\n";
        }
        p.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (dis != null) {
            try {
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}

From source file:edu.cwru.jpdg.Javac.java

/**
 * Compiles the java./*from   w w  w.  j  a  va  2s  .  c  o  m*/
 */
public static List<String> javac(String basepath, String name, String s) {
    Path dir = Paths.get(cwd).resolve(basepath);
    if (Files.notExists(dir)) {
        create_dir(dir);
    }
    Path java = dir.resolve(name + ".java");
    Path build = dir.resolve("build");
    if (!Files.notExists(build)) {
        try {
            FileUtils.deleteDirectory(build.toFile());
        } catch (IOException e) {
            throw new RuntimeException("Couldn't rm -r build dir");
        }
    }
    create_dir(build);

    byte[] bytes = s.getBytes();
    try {
        Files.write(java, bytes);
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage());
    }

    try {
        Process p = Runtime.getRuntime()
                .exec(new String[] { "javac", "-d", build.toString(), java.toString() });
        String line;
        BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));
        List<String> stdout_lines = new ArrayList<String>();
        line = stdout.readLine();
        while (line != null) {
            stdout_lines.add(line);
            line = stdout.readLine();
        }
        BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        List<String> stderr_lines = new ArrayList<String>();
        line = stderr.readLine();
        while (line != null) {
            stderr_lines.add(line);
            line = stderr.readLine();
        }
        if (p.waitFor() != 0) {
            System.err.println(StringUtils.join(stdout_lines, "\n"));
            System.err.println("-------------------------------------");
            System.err.println(StringUtils.join(stderr_lines, "\n"));
            throw new RuntimeException("javac failed");
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e.getMessage());
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage());
    }

    return abs_paths(find_classes(build.toString()));
}

From source file:com.offbynull.portmapper.common.ProcessUtils.java

/**
 * Run a process and dump the stdout stream to a string.
 * @param timeout maximum amount of time the process can take to run
 * @param command command//w  w w  .j a v a  2 s.  c om
 * @param args arguments
 * @return stdout from the process dumped to a string
 * @throws IOException if the process encounters an error
 * @throws NullPointerException if any arguments are {@code null} or contains {@code null}
 * @throws IllegalArgumentException any numeric argument is negative
 */
public static String runProcessAndDumpOutput(long timeout, String command, String... args) throws IOException {
    Validate.notNull(command);
    Validate.noNullElements(args);
    Validate.inclusiveBetween(0L, Long.MAX_VALUE, timeout);

    String[] pbCmd = new String[args.length + 1];
    pbCmd[0] = command;
    System.arraycopy(args, 0, pbCmd, 1, args.length);

    ProcessBuilder builder = new ProcessBuilder(pbCmd);

    final AtomicBoolean failedFlag = new AtomicBoolean();

    Timer timer = new Timer("Process timeout timer", true);
    Process proc = null;
    try {
        proc = builder.start();

        final Process finalProc = proc;
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                failedFlag.set(true);
                finalProc.destroy();
            }
        }, timeout);

        String ret = IOUtils.toString(proc.getInputStream());
        if (failedFlag.get()) {
            throw new IOException("Process failed");
        }

        return ret;
    } finally {
        if (proc != null) {
            proc.destroy();
        }
        timer.cancel();
        timer.purge();
    }
}

From source file:io.appium.java_client.service.local.AppiumServiceBuilder.java

private static void validateNodeJSVersion() {
    Runtime rt = Runtime.getRuntime();
    String result = null;//  w  w w .  ja  v  a2 s.  c o m
    Process p = null;
    try {
        p = rt.exec(NODE_COMMAND_PREFIX + " node -v");
        p.waitFor();
        result = getProcessOutput(p.getInputStream());
    } catch (Exception e) {
        throw new InvalidNodeJSInstance("Node.js is not installed", e);
    } finally {
        if (p != null)
            p.destroy();
    }

    String versionNum = result.replace("v", "");
    String[] tokens = versionNum.split("\\.");
    if (Integer.parseInt(tokens[0]) < REQUIRED_MAJOR_NODE_JS
            || Integer.parseInt(tokens[1]) < REQUIRED_MINOR_NODE_JS)
        throw new InvalidNodeJSInstance("Current node.js version " + versionNum + "is lower than "
                + "required (" + REQUIRED_MAJOR_NODE_JS + "." + REQUIRED_MINOR_NODE_JS + " or greater)");
}

From source file:jeplus.INSELWinTools.java

/**
 * Call INSEL executable file to run the simulation
 * @param config INSEL Configuration// w  w  w . j  av  a2 s. co  m
 * @param WorkDir The working directory where the input files are stored and the output files to be generated
 * @param useReadVars Whether or not to use readvars after simulation
 * @return the result code represents the state of execution steps. >=0 means successful
 */
public static int runINSEL(INSELConfig config, String WorkDir, String modelfile) {

    int ExitValue = -99;

    try {
        // Trace simulation time
        Date start = new Date();

        // Run EnergyPlus executable
        String CmdLine = config.getResolvedInselEXEC() + " " + modelfile;
        Process EPProc = Runtime.getRuntime().exec(CmdLine, null, new File(WorkDir));

        BufferedReader ins = new BufferedReader(new InputStreamReader(EPProc.getInputStream()));
        // Use console output as the report file
        BufferedWriter outs = new BufferedWriter(new FileWriter(WorkDir + config.ScreenFile, false));
        outs.newLine();
        outs.write("Calling insel.exe - " + (new SimpleDateFormat()).format(start));
        outs.newLine();
        outs.write("Command line: " + WorkDir + ">" + CmdLine);
        outs.newLine();

        int res = ins.read();
        while (res != -1) {
            outs.write(res);
            res = ins.read();
        }
        ins.close();
        outs.newLine();
        outs.write("Simulation time: " + Long.toString((new Date().getTime() - start.getTime()) / 1000)
                + " seconds");
        outs.flush();
        outs.close();

        EPProc.waitFor();
        ExitValue = EPProc.exitValue();
    } catch (IOException | InterruptedException e) {
        logger.error("Exception during INSEL execution.", e);
    }

    // Return Radiance exit value
    return ExitValue;
}

From source file:eu.interedition.collatex.tools.CollationServer.java

private static String detectDotPath() {
    for (String detectionCommand : new String[] { "which dot", "where dot.exe" }) {
        try {/*ww w. ja  va2 s.  c o m*/

            final Process process = Runtime.getRuntime().exec(detectionCommand);
            try (BufferedReader processReader = new BufferedReader(
                    new InputStreamReader(process.getInputStream(), Charset.defaultCharset()))) {
                final CompletableFuture<Optional<String>> path = CompletableFuture
                        .supplyAsync(() -> processReader.lines().map(String::trim)
                                .filter(l -> l.toLowerCase().contains("dot")).findFirst());
                process.waitFor();
                final String dotPath = path.get().get();
                LOG.info(() -> "Detected GraphViz' dot at '" + dotPath + "'");
                return dotPath;
            }
        } catch (Throwable t) {
            LOG.log(Level.FINE, detectionCommand, t);
        }
    }
    return null;
}

From source file:com.pclinuxos.rpm.util.FileUtils.java

/**
 * The method extracts a srpm into the default directory used by the program (/home/<user>/RCEB/srpms/tmp)
 * //from  w w  w .  j  a  v a 2  s.com
 * @param srpm the srpm to extract
 * @return 0 if the extraction was successfully, -1 if a IOException occurred, -2 if a InterruptException
 *  occurred. Values > 0 for return codes of the rpm2cpio command.
 */
public static int extractSrpm(String srpm) {

    int returnCode = 0;

    try {

        Process extractProcess = Runtime.getRuntime()
                .exec("rpm2cpio " + FileConstants.SRCSRPMS.getAbsolutePath() + "/" + srpm);
        // 64kb buffer
        byte[] buffer = new byte[0xFFFF];
        InputStream inread = extractProcess.getInputStream();

        FileOutputStream out = new FileOutputStream(new File(FileConstants.F4SRPMEX + "archive.cpio"));

        while (inread.read(buffer) != -1) {

            out.write(buffer);
        }

        returnCode = extractProcess.waitFor();

        if (returnCode == 0) {

            CpioArchiveInputStream cpioIn = new CpioArchiveInputStream(
                    new FileInputStream(FileConstants.F4SRPMEX + "archive.cpio"));
            CpioArchiveEntry cpEntry;

            while ((cpEntry = cpioIn.getNextCPIOEntry()) != null) {

                FileOutputStream fOut = new FileOutputStream(FileConstants.F4SRPMEX + cpEntry.getName());
                // Do not make this buffer bigger it breaks the cpio decompression
                byte[] buffer2 = new byte[1];
                ArrayList<Byte> buf = new ArrayList<Byte>();

                while (cpioIn.read(buffer2) != -1) {

                    buf.add(buffer2[0]);
                }

                byte[] file = new byte[buf.size()];

                for (int i = 0; i < buf.size(); i++) {

                    file[i] = buf.get(i);
                }

                fOut.write(file);

                fOut.flush();
                fOut.close();
            }

            cpioIn.close();
        }
    } catch (IOException e) {

        returnCode = -1;
    } catch (InterruptedException e) {

        returnCode = -2;
    }

    new File(FileConstants.F4SRPMEX + "archive.cpio").delete();

    return returnCode;
}