Example usage for java.lang Runtime exec

List of usage examples for java.lang Runtime exec

Introduction

In this page you can find the example usage for java.lang Runtime exec.

Prototype

public Process exec(String cmdarray[]) throws IOException 

Source Link

Document

Executes the specified command and arguments in a separate process.

Usage

From source file:org.kepler.ssh.LocalExec.java

public int executeCmd(String command, OutputStream streamOut, OutputStream streamErr, String thirdPartyTarget)
        throws ExecException {
    _commandArr[_commandCount] = command;

    Runtime rt = Runtime.getRuntime();
    Process proc;//w  w  w .  ja  v a2s  . c  o m

    // get the pwd/passphrase to the third party (and perform authentication
    // if not yet done)
    String pwd = SshSession.getPwdToThirdParty(thirdPartyTarget);

    try {
        proc = rt.exec(_commandArr);
    } catch (Exception ex) {
        //ex.printStackTrace();
        throw new ExecException("Cannot execute cmd ** : " + _commandArr[_commandCount] + ex);
    }

    // System.out.println("%%% Process started");

    // the streams from the process: stdout and stderr
    BufferedReader out_in = new BufferedReader(new InputStreamReader(proc.getInputStream())); // stdout
    BufferedReader err_in = new BufferedReader(new InputStreamReader(proc.getErrorStream())); // stderr

    // the streams towards the caller: stdout and stderr
    BufferedWriter out_out = new BufferedWriter(new OutputStreamWriter(streamOut));
    BufferedWriter err_out = new BufferedWriter(new OutputStreamWriter(streamErr));

    BufferedWriter proc_in = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())); // stdin

    String line; // Temp for each line of output.
    int exitVal = -32766;
    boolean readOut = true;
    boolean readErr = true;
    boolean finished = false;
    boolean checkForPwd = (pwd != null);
    char c[] = new char[256];
    int charsRead;

    // variables for the timeout checking
    long start = System.currentTimeMillis();
    long current = 0;
    long maxtime = timeout * 1000L;

    while (!finished) { // will stop when the process terminates or after
        // timeout
        // check the status of the process
        try {
            exitVal = proc.exitValue();
            finished = true; // process terminated so exit this loop after
                             // reading the buffers
        } catch (IllegalThreadStateException ex) {
            // process not yet terminated so we go further
        }

        // read stdout
        if (readOut) {
            try {
                while (out_in.ready()) {
                    charsRead = out_in.read(c, 0, 256);
                    out_out.write(c, 0, charsRead);

                    // System.out.println("%%% "+ new String(c, 0,
                    // charsRead));
                    /*
                     * try { proc_in.write("Anyadat\n", 0, 8); // send the
                     * password proc_in.flush(); } catch (Exception ex) {
                     * System.out.println("### "+ex);
                     * 
                     * }
                     */
                    if (checkForPwd && containsPasswordRequest(c, 0, charsRead)) {

                        // System.out.println("%%% Found password request");

                        out_out.flush(); // so you may see the request on
                                         // stdout already
                        proc_in.write(pwd + "\n", 0, pwd.length() + 1); // send
                        // the
                        // password
                        proc_in.flush();
                        log.info("Sent password to third party.");
                        checkForPwd = false; // even if it's wrong, do not
                                             // do it again
                    }
                    if (timeoutRestartOnStdout)
                        start = System.currentTimeMillis(); // restart
                    // timeout timer
                }
            } catch (IOException ioe) {
                log.error("<IOException> when reading the stdout: " + ioe + "</IOException>");
                readOut = false;
            }
        }

        // read stderr
        if (readErr) {
            try {
                while (err_in.ready()) {
                    charsRead = err_in.read(c, 0, 256);
                    err_out.write(c, 0, charsRead);
                    System.out.println("### " + new String(c, 0, charsRead));
                    if (checkForPwd && containsPasswordRequest(c, 0, charsRead)) {

                        System.out.println("### Found password request");

                        out_out.flush(); // so you may see the request on
                                         // stdout already
                        proc_in.write(pwd + "\n", 0, pwd.length() + 1); // send
                        // the
                        // password
                        proc_in.flush();
                        log.info("Sent password to third party.");
                        checkForPwd = false; // even if it's wrong, do not
                                             // do it again
                    }
                    if (timeoutRestartOnStderr)
                        start = System.currentTimeMillis(); // restart
                    // timeout timer
                }
            } catch (IOException ioe) {
                log.error("<IOException> when reading the stderr: " + ioe + "</IOException>");
                readErr = false;
            }
        }

        // sleep a bit to not overload the system
        if (!finished)
            try {
                java.lang.Thread.sleep(100);
            } catch (InterruptedException ex) {
            }

        // check timeout
        current = System.currentTimeMillis();
        if (timeout > 0 && maxtime < current - start) {
            log.error("Timeout: " + timeout + "s elapsed for command " + command);
            proc.destroy();
            throw new ExecTimeoutException(command);
            // exitVal = timeoutErrorCode;
            // finished = true;
        }

    }

    try {
        // flush to caller
        out_out.flush();
        err_out.flush();
        // close streams from/to child process
        out_in.close();
        err_in.close();
        proc_in.close();
    } catch (IOException ex) {
        log.error("Could not flush output streams: " + ex);
    }

    // System.out.println("ExitValue: " + exitVal);
    return exitVal;

}

From source file:ch.kostceco.tools.kostval.validation.modulesiard.impl.ValidationHcontentModuleImpl.java

@Override
public boolean validate(File valDatei, File directoryOfLogfile) throws ValidationHcontentException {
    // Ausgabe SIARD-Modul Ersichtlich das KOST-Val arbeitet
    System.out.print("H   ");
    System.out.print("\r");
    int onWork = 41;

    boolean valid = true;
    try {//  w  w w.j a v a 2  s. c  o  m
        /* Extract the metadata.xml from the temporary work folder and build a jdom document */
        String pathToWorkDir = getConfigurationService().getPathToWorkDir();
        pathToWorkDir = pathToWorkDir + File.separator + "SIARD";
        File metadataXml = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("header")
                .append(File.separator).append("metadata.xml").toString());
        InputStream fin = new FileInputStream(metadataXml);
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(fin);
        fin.close();

        /* read the document and for each schema and table entry verify existence in temporary
         * extracted structure */
        Namespace ns = Namespace.getNamespace("http://www.bar.admin.ch/xmlns/siard/1.0/metadata.xsd");
        // select schema elements and loop
        List<Element> schemas = document.getRootElement().getChild("schemas", ns).getChildren("schema", ns);
        for (Element schema : schemas) {
            Element schemaFolder = schema.getChild("folder", ns);
            File schemaPath = new File(new StringBuilder(pathToWorkDir).append(File.separator).append("content")
                    .append(File.separator).append(schemaFolder.getText()).toString());
            if (schemaPath.isDirectory()) {
                Element[] tables = schema.getChild("tables", ns).getChildren("table", ns)
                        .toArray(new Element[0]);
                for (Element table : tables) {
                    Element tableFolder = table.getChild("folder", ns);
                    File tablePath = new File(new StringBuilder(schemaPath.getAbsolutePath())
                            .append(File.separator).append(tableFolder.getText()).toString());
                    if (tablePath.isDirectory()) {
                        File tableXml = new File(new StringBuilder(tablePath.getAbsolutePath())
                                .append(File.separator).append(tableFolder.getText() + ".xml").toString());
                        File tableXsd = new File(new StringBuilder(tablePath.getAbsolutePath())
                                .append(File.separator).append(tableFolder.getText() + ".xsd").toString());
                        // TODO: hier erfolgt die Validerung
                        if (verifyRowCount(tableXml, tableXsd)) {

                            // valid = validate1( tableXml, tableXsd ) && valid;

                            // xmllint via cmd
                            // resources\xmllint\xmllint --noout --stream --schema tableXsd tableXml
                            try {
                                // Pfad zum Programm xmllint existiert die Dateien?
                                String pathToxmllintExe = "resources" + File.separator + "xmllint"
                                        + File.separator + "xmllint.exe";
                                String pathToxmllintDll1 = "resources" + File.separator + "xmllint"
                                        + File.separator + "iconv.dll";
                                String pathToxmllintDll2 = "resources" + File.separator + "xmllint"
                                        + File.separator + "libxml2.dll";
                                String pathToxmllintDll3 = "resources" + File.separator + "xmllint"
                                        + File.separator + "zlib1.dll";

                                File fpathToxmllintExe = new File(pathToxmllintExe);
                                File fpathToxmllintDll1 = new File(pathToxmllintDll1);
                                File fpathToxmllintDll2 = new File(pathToxmllintDll2);
                                File fpathToxmllintDll3 = new File(pathToxmllintDll3);
                                if (!fpathToxmllintExe.exists()) {
                                    getMessageService().logError(getTextResourceService()
                                            .getText(MESSAGE_XML_MODUL_H_SIARD)
                                            + getTextResourceService().getText(ERROR_XML_XMLLINT1_MISSING));
                                    valid = false;
                                } else if (!fpathToxmllintDll1.exists()) {
                                    getMessageService().logError(getTextResourceService()
                                            .getText(MESSAGE_XML_MODUL_H_SIARD)
                                            + getTextResourceService().getText(ERROR_XML_XMLLINT2_MISSING));
                                    valid = false;
                                } else if (!fpathToxmllintDll2.exists()) {
                                    getMessageService().logError(getTextResourceService()
                                            .getText(MESSAGE_XML_MODUL_H_SIARD)
                                            + getTextResourceService().getText(ERROR_XML_XMLLINT3_MISSING));
                                    valid = false;
                                } else if (!fpathToxmllintDll3.exists()) {
                                    getMessageService().logError(getTextResourceService()
                                            .getText(MESSAGE_XML_MODUL_H_SIARD)
                                            + getTextResourceService().getText(ERROR_XML_XMLLINT4_MISSING));
                                    valid = false;
                                } else {

                                    StringBuffer command = new StringBuffer("resources" + File.separator
                                            + "xmllint" + File.separator + "xmllint ");
                                    command.append("--noout --stream ");
                                    command.append(" --schema ");
                                    command.append(" ");
                                    command.append("\"");
                                    command.append(tableXsd.getAbsolutePath());
                                    command.append("\"");
                                    command.append(" ");
                                    command.append("\"");
                                    command.append(tableXml.getAbsolutePath());
                                    command.append("\"");

                                    Process proc = null;
                                    Runtime rt = null;

                                    try {
                                        File outTableXml = new File(pathToWorkDir + File.separator + "SIARD_H_"
                                                + tableXml.getName() + ".txt");

                                        Util.switchOffConsoleToTxt(outTableXml);

                                        rt = Runtime.getRuntime();
                                        proc = rt.exec(command.toString().split(" "));
                                        // .split(" ") ist notwendig wenn in einem Pfad ein Doppelleerschlag vorhanden
                                        // ist!

                                        // Fehleroutput holen

                                        StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(),
                                                "ERROR-" + tableXml.getName());

                                        // Output holen
                                        StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(),
                                                "OUTPUT-" + tableXml.getName());

                                        // Threads starten
                                        errorGobbler.start();
                                        outputGobbler.start();

                                        // Warte, bis wget fertig ist 0 = Alles io
                                        int exitStatus = proc.waitFor();

                                        // 200ms warten bis die Konsole umgeschaltet wird, damit wirklich alles im
                                        // file landet
                                        Thread.sleep(200);
                                        Util.switchOnConsole();

                                        if (0 != exitStatus) {
                                            // message.xml.h.invalid.xml = <Message>{0} ist invalid zu
                                            // {1}</Message></Error>
                                            getMessageService().logError(
                                                    getTextResourceService().getText(MESSAGE_XML_MODUL_H_SIARD)
                                                            + getTextResourceService().getText(
                                                                    MESSAGE_XML_H_INVALID_XML,
                                                                    tableXml.getName(), tableXsd.getName()));
                                            valid = false;

                                            // Fehlermeldung aus outTableXml auslesen

                                            BufferedReader br = new BufferedReader(new FileReader(outTableXml));
                                            try {
                                                String line = br.readLine();
                                                String linePrev = null;
                                                /* Fehlermeldungen holen, ausser die letzte, die besagt, dass es invalide
                                                 * ist (wurde bereits oben in D, F,E ausgegeben */
                                                while (line != null) {
                                                    if (linePrev != null) {
                                                        getMessageService().logError(getTextResourceService()
                                                                .getText(MESSAGE_XML_MODUL_H_SIARD)
                                                                + getTextResourceService().getText(
                                                                        MESSAGE_XML_H_INVALID_ERROR, linePrev));
                                                    }
                                                    linePrev = line;
                                                    line = br.readLine();
                                                }
                                            } finally {
                                                br.close();

                                                /* Konsole zuerst einmal noch umleiten und die Streams beenden, damit die
                                                 * dateien gelscht werden knnen */
                                                Util.switchOffConsoleToTxtClose(outTableXml);
                                                System.out.println(" . ");
                                                Util.switchOnConsole();
                                                Util.deleteFile(outTableXml);

                                            }
                                        } else {
                                            /* Konsole zuerst einmal noch umleiten und die Streams beenden, damit die
                                             * dateien gelscht werden knnen */
                                            Util.switchOffConsoleToTxtClose(outTableXml);
                                            System.out.println(" . ");
                                            Util.switchOnConsole();
                                            Util.deleteFile(outTableXml);

                                        }
                                        /* Konsole zuerst einmal noch umleiten und die Streams beenden, damit die
                                         * dateien gelscht werden knnen */
                                        Util.switchOffConsoleToTxtClose(outTableXml);
                                        System.out.println(" . ");
                                        Util.switchOnConsole();
                                        Util.deleteFile(outTableXml);

                                    } catch (Exception e) {
                                        getMessageService().logError(
                                                getTextResourceService().getText(MESSAGE_XML_MODUL_H_SIARD)
                                                        + getTextResourceService().getText(ERROR_XML_UNKNOWN,
                                                                e.getMessage()));
                                        return false;
                                    } finally {
                                        if (proc != null) {
                                            closeQuietly(proc.getOutputStream());
                                            closeQuietly(proc.getInputStream());
                                            closeQuietly(proc.getErrorStream());
                                        }
                                    }
                                }
                            } finally {
                            }
                        }
                    }
                    if (onWork == 41) {
                        onWork = 2;
                        System.out.print("H-   ");
                        System.out.print("\r");
                    } else if (onWork == 11) {
                        onWork = 12;
                        System.out.print("H\\   ");
                        System.out.print("\r");
                    } else if (onWork == 21) {
                        onWork = 22;
                        System.out.print("H|   ");
                        System.out.print("\r");
                    } else if (onWork == 31) {
                        onWork = 32;
                        System.out.print("H/   ");
                        System.out.print("\r");
                    } else {
                        onWork = onWork + 1;
                    }
                }
            }
            if (onWork == 41) {
                onWork = 2;
                System.out.print("H-   ");
                System.out.print("\r");
            } else if (onWork == 11) {
                onWork = 12;
                System.out.print("H\\   ");
                System.out.print("\r");
            } else if (onWork == 21) {
                onWork = 22;
                System.out.print("H|   ");
                System.out.print("\r");
            } else if (onWork == 31) {
                onWork = 32;
                System.out.print("H/   ");
                System.out.print("\r");
            } else {
                onWork = onWork + 1;
            }
        }
    } catch (java.io.IOException ioe) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_H_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, ioe.getMessage() + " (IOException)"));
    } catch (JDOMException e) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_H_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage() + " (JDOMException)"));
    } catch (SAXException e) {
        valid = false;
        getMessageService().logError(getTextResourceService().getText(MESSAGE_XML_MODUL_H_SIARD)
                + getTextResourceService().getText(ERROR_XML_UNKNOWN, e.getMessage() + " (SAXException)"));
    }

    return valid;
}

From source file:san.FileSystemImpl.java

/**
* moveFile() - move file /*from   w w  w.j a va2  s .co m*/
* @param filePath - filePath 
* @param path - path
* @param fileName - fileName
* @param destPath - destination filePath
* @param destFileName - destinationFile
* @throws - error when the File object is null
*/
public void moveFile(String filePath, String path, String fileName, String destPath, String destFileName)
        throws SanException {

    logger.info("filePath = " + filePath + " path = " + path + " fileName = " + fileName + " destPath = "
            + destPath + " destFileName = " + destFileName);

    StringBuffer srcdir = new StringBuffer(path);
    srcdir.append(filePath);

    logger.info("srcdir= " + srcdir.toString());

    StringBuffer newdir = new StringBuffer(path);
    newdir.append(destPath);
    newdir.append(File.separator);
    newdir.append(destFileName);

    logger.info("newdir= " + newdir.toString());

    try {
        Runtime runtime = Runtime.getRuntime();

        // It is important to break up the command into a String[] array
        // I couldn't get it working without resorting to arg array
        //  Process proc = runtime.exec(new String[] {"/bin/mv", srcdir.toString() + fileName, newdir.toString()});
        Process proc = runtime
                .exec(new String[] { SanConstants.sanMove, srcdir.toString() + fileName, newdir.toString() });

        // Very important to check errors returned by the process as
        // the java program will not print out the error that is output by
        // the child process unless you do this
        InputStream stdin = proc.getErrorStream();
        InputStreamReader isr = new InputStreamReader(stdin);
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        while ((line = br.readLine()) != null)
            throw new SanException("error " + line);
    } catch (Exception e) {
        throw new SanException("error " + e.getMessage());
    }
}

From source file:san.FileSystemImpl.java

/**
* copyDirectory() - copy the entire directory to another directory using unix command (cp -r)
* @param filePath - filePath /* www  .j  av  a  2 s . c  om*/
* @param path - path
* @param fileName - fileName or directory name
* @param destPath - destination filePath
* @param destFileName - destinationFile
* @throws - error when the File object is null
*/
public void copyDirectory(String filePath, String path, String fileName, String destPath, String destFileName)
        throws SanException {

    logger.info("filePath = " + filePath + " path = " + path + " fileName = " + fileName + " destPath = "
            + destPath + " destFileName = " + destFileName);

    StringBuffer srcdir = new StringBuffer(path);
    srcdir.append(filePath);

    logger.info("srcdir= " + srcdir.toString());

    StringBuffer newdir = new StringBuffer(path);
    newdir.append(destPath);
    if (!destPath.endsWith(File.separator)) {
        newdir.append(File.separator);
    }
    newdir.append(destFileName);

    logger.info("newdir= " + newdir.toString());

    try {
        Runtime runtime = Runtime.getRuntime();

        // It is important to break up the command into a String[] array
        // I couldn't get it working without resorting to arg array
        //  Process proc = runtime.exec(new String[] {"/bin/mv", srcdir.toString() + fileName, newdir.toString()});
        Process proc = runtime.exec(new String[] { SanConstants.sanCopy, SanConstants.sanCopyOption,
                srcdir.toString() + fileName, newdir.toString() });

        // Very important to check errors returned by the process as
        // the java program will not print out the error that is output by
        // the child process unless you do this
        InputStream stdin = proc.getErrorStream();
        InputStreamReader isr = new InputStreamReader(stdin);
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        while ((line = br.readLine()) != null)
            throw new SanException("error " + line);
    } catch (Exception e) {
        throw new SanException("error " + e.getMessage());
    }
}

From source file:com._17od.upm.gui.AccountDialog.java

/**
 * Method that get(as input) the selected Account URL and open this URL via
 * the default browser of our platform.//from www. j  av  a2  s.  c om
 * 
 * @param url
 */
private void LaunchSelectedURL(String url) {

    if (Desktop.isDesktopSupported()) {
        Desktop desktop = Desktop.getDesktop();

        try {
            desktop.browse(new URI(url));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    } else { // Linux and Mac specific code in order to launch url
        Runtime runtime = Runtime.getRuntime();

        try {
            runtime.exec("xdg-open " + url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:net.liuxuan.device.VACVBS.JIF_DrawChart_vacvbs.java

private void jButton_tidyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_tidyActionPerformed
    Runtime rn = Runtime.getRuntime();
    Process p = null;//  w  ww  .j  a v a  2  s.co  m
    //        File f= new File("others/exe/VBS-data-export.exe");
    //        System.out.println(f.getAbsolutePath());
    try {
        p = rn.exec("\"others/exe/VBS-data-export.exe\"");
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Error exec!");
    }
}

From source file:san.FileSystemImpl.java

/**
* diskUsageOfDirectory() - get the disk usage of this directory
* @param dirName - dirName/* w  ww  .jav a 2  s  .c o  m*/
* @param path - path
* @param filePath - path of the directory (if there is any from db)
* @throws - error when the File object is null
*/
public String diskUsageOfDirectory(String dirName, String path, String filePath) throws SanException {

    logger.info("dirName = " + dirName + " path = " + path + " filePath = " + filePath);

    StringBuffer srcdir = new StringBuffer(path);
    srcdir.append(filePath);

    logger.info("srcdir= " + srcdir.toString());

    try {
        Runtime runtime = Runtime.getRuntime();

        // It is important to break up the command into a String[] array
        // I couldn't get it working without resorting to arg array
        //  Process proc = runtime.exec(new String[] {"/bin/mv", srcdir.toString() + fileName, newdir.toString()});
        Process proc = runtime.exec(new String[] { SanConstants.sanDiskUsage, SanConstants.sanDiskUsageOption1,
                SanConstants.sanDiskUsageOption2, SanConstants.sanDiskUsageOption3,
                srcdir.toString() + dirName });

        // Very important to check errors returned by the process as
        // the java program will not print out the error that is output by
        // the child process unless you do this

        InputStream stdin = null;
        int exitVal = proc.waitFor();
        if (exitVal == 0)
            stdin = proc.getInputStream();
        else
            stdin = proc.getErrorStream();

        InputStreamReader isr = new InputStreamReader(stdin);
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        while ((line = br.readLine()) != null) {
            logger.info("line = " + line);
            int index = line.indexOf("total");
            if (index != -1) {
                logger.info("index = " + index);
                String usedSize = line.substring(0, index);
                logger.info("usedSize = " + usedSize);
                if (usedSize == null) {
                    logger.info("usedSize is null");
                    return null;
                } else {
                    usedSize = usedSize.trim();
                    logger.info("usedSize " + usedSize);
                    return usedSize;
                    //return "24000M";
                }
            }
        }
    } catch (Exception e) {
        throw new SanException("error " + e.getMessage());
    }
    return null;
}

From source file:nu.nethome.home.impl.HomeServer.java

public void handleUpgrade() {
    if (doUpgrade) {
        try {/*from  w w w .  j av a2 s  . c  o  m*/
            logger.info("Starting upgrade sequence");
            Runtime r = Runtime.getRuntime();
            // Run the upgrade command. If this is a Windows bat-file, you have to have one bat file which
            // does a "start" of the second real upgrade bat file.
            r.exec(upgradeCommand);
            try {
                // For some reason we have to wait a while, otherwise it seems this program exits before
                // the execution of the upgrade command is really started.
                Thread.sleep(UPGRADE_HOLDOFF_TIME);
            } catch (InterruptedException i) {
                // Do nothing
            }
        } catch (IOException e) {
            logger.warning("Could not auto upgrade:" + e.getMessage());
        }
    }
}

From source file:com.ikanow.infinit.e.processing.custom.launcher.CustomHadoopTaskLauncher.java

public String runHadoopJob_commandLine(CustomMapReduceJobPojo job, String jar) {
    String jobid = null;//w  w  w.ja v  a  2s  .c o  m
    try {
        job.tempConfigXMLLocation = createConfigXML_commandLine(job.jobtitle, job.inputCollection,
                job._id.toString(), job.tempConfigXMLLocation, job.mapper, job.reducer, job.combiner,
                InfiniteHadoopUtils.getQueryOrProcessing(job.query, InfiniteHadoopUtils.QuerySpec.QUERY),
                job.communityIds, job.isCustomTable, job.getOutputDatabase(), job.outputKey, job.outputValue,
                job.outputCollectionTemp, job.arguments, job.incrementalMode, job.submitterID, job.selfMerge,
                job.outputCollection, job.appendResults);
        Runtime rt = Runtime.getRuntime();
        String[] commands = new String[] { "hadoop", "--config", props_custom.getHadoopConfigPath() + "/hadoop",
                "jar", jar, "-conf", job.tempConfigXMLLocation };
        String command = "";
        for (String s : commands)
            command += s + " ";
        Process pr = rt.exec(command);

        //Once we start running the command attach to stderr to
        //receive the output to parse out the jobid
        InputStream in = pr.getErrorStream();
        InputStreamReader is = new InputStreamReader(in);
        BufferedReader br = new BufferedReader(is);
        StringBuilder output = new StringBuilder();
        String line = null;

        long startTime = new Date().getTime();
        boolean bGotJobId = false;
        //while we haven't found the id, there are still lines to read, and it hasn't been more than 60 seconds
        while (!bGotJobId && (line = br.readLine()) != null
                && (new Date().getTime() - startTime) < InfiniteHadoopUtils.SECONDS_60) {
            output.append(line);
            int getJobIdIndex = -1;
            String searchstring = "INFO mapred.JobClient: Running job: ";
            if ((getJobIdIndex = line.indexOf(searchstring)) >= 0) {
                // Get JobId and trim() it (obviously trivial)
                jobid = line.substring(getJobIdIndex + searchstring.length()).trim();
                bGotJobId = true;
            }
        }

        //60 seconds passed and we never found the id
        if (!bGotJobId) {
            _logger.info("job_start_timeout_error_title=" + job.jobtitle + " job_start_timeout_error_id="
                    + job._id.toString() + " job_start_timeout_error_message=" + output.toString());
            //if we never found the id mark it as errored out
            return "Error:\n" + output.toString();
        }
    } catch (Exception ex) {
        //had an error running command
        //probably log error to the job so we stop trying to run it
        _logger.info("job_start_timeout_error_title=" + job.jobtitle + " job_start_timeout_error_id="
                + job._id.toString() + " job_start_timeout_error_message="
                + InfiniteHadoopUtils.createExceptionMessage(ex));
        jobid = "Error:\n" + ex.getMessage(); // (means this gets displayed)         
    }
    return jobid;
}

From source file:san.FileSystemImpl.java

/**
* fileContentType() - read the content type of the file
* @param fileName - fileName including the entire path
* @returns String - content type as a string
* @throws - error when the File object is null
*///  ww  w.  j av  a  2s  . c  om
public String getFileContentType(String fileName) throws SanException {

    logger.info(" getFileContentType() fileName = " + fileName);

    try {
        Runtime runtime = Runtime.getRuntime();

        // It is important to break up the command into a String[] array
        // I couldn't get it working without resorting to arg array
        //  Process proc = runtime.exec(new String[] {"/bin/mv", srcdir.toString() + fileName, newdir.toString()});
        //Process proc = runtime.exec(new String[] {"/usr/bin/file", "/tmp/redbasin_facilities.doc"});
        Process proc = runtime.exec(new String[] { SanConstants.sanFileCmd, fileName });

        // Very important to check errors returned by the process as
        // the java program will not print out the error that is output by
        // the child process unless you do this

        InputStream stdin = null;
        int exitVal = proc.waitFor();
        if (exitVal == 0)
            stdin = proc.getInputStream();
        else
            stdin = proc.getErrorStream();

        InputStreamReader isr = new InputStreamReader(stdin);
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        while ((line = br.readLine()) != null) {
            logger.info("line = " + line);
            int index = line.lastIndexOf(":");
            if (index != -1 && index < line.length()) {
                String contentType = line.substring(index + 1, line.length());
                logger.info("contentType = " + contentType);
            }
        }
    } catch (Exception e) {
        throw new SanException("error " + e.getMessage());
    }
    return null;
}