Example usage for java.lang Process getOutputStream

List of usage examples for java.lang Process getOutputStream

Introduction

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

Prototype

public abstract OutputStream getOutputStream();

Source Link

Document

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

Usage

From source file:com.sentaroh.android.SMBExplorer.SMBExplorerMain.java

private boolean initSuCmdProcess() {
    boolean su_available = false;
    if (mGp.settingsUseRootPrivilege) {
        Process p = null;
        try {//from   ww  w .ja  v a 2s . co m
            p = Runtime.getRuntime().exec("su");
            p.getOutputStream().write(new String("id" + "\n").getBytes());
            p.getOutputStream().flush();
            byte[] buffer = new byte[1024];
            String ret = "";
            int bc = 0;
            bc = p.getInputStream().read(buffer);
            if (bc > 0)
                ret = new String(buffer, 0, bc, "UTF-8");
            if (ret.length() > 0)
                su_available = true;
            //            Log.v("","ret="+ret);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        if (su_available) {
            mGp.mSuCmdProcess = p;
            sendDebugLogMsg(1, "I", "root ptivilege granted");
        } else {
            sendDebugLogMsg(1, "I", "root ptivilege not granted");
        }
    }
    return su_available;
}

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 {//from ww w.  ja  v a2 s  .  c  om
        /* 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:com.panet.imeta.job.entries.shell.JobEntryShell.java

private void executeShell(Result result, List<RowMetaAndData> cmdRows, String[] args) {
    LogWriter log = LogWriter.getInstance();
    FileObject fileObject = null;
    String realScript = null;/*www .jav a  2 s. c  o m*/
    FileObject tempFile = null;

    try {
        // What's the exact command?
        String base[] = null;
        List<String> cmds = new ArrayList<String>();

        if (log.isBasic())
            log.logBasic(toString(), Messages.getString("JobShell.RunningOn", Const.getOS()));

        if (insertScript) {
            realScript = environmentSubstitute(script);
        } else {
            String realFilename = environmentSubstitute(getFilename());
            fileObject = KettleVFS.getFileObject(realFilename);
        }

        if (Const.getOS().equals("Windows 95")) {
            base = new String[] { "command.com", "/C" };
        } else if (Const.getOS().startsWith("Windows")) {
            base = new String[] { "cmd.exe", "/C" };
        } else {
            if (!insertScript) {
                // Just set the command to the script we need to execute...
                //
                base = new String[] { KettleVFS.getFilename(fileObject) };
            } else {
                // Create a unique new temporary filename in the working directory, put the script in there
                // Set the permissions to execute and then run it...
                //
                try {
                    tempFile = KettleVFS.createTempFile("kettle", "shell", workDirectory);
                    tempFile.createFile();
                    OutputStream outputStream = tempFile.getContent().getOutputStream();
                    outputStream.write(realScript.getBytes());
                    outputStream.close();
                    String tempFilename = KettleVFS.getFilename(tempFile);
                    // Now we have to make this file executable...
                    // On Unix-like systems this is done using the command "/bin/chmod +x filename"
                    //
                    ProcessBuilder procBuilder = new ProcessBuilder("chmod", "+x", tempFilename);
                    Process proc = procBuilder.start();
                    // Eat/log stderr/stdout all messages in a different thread...
                    StreamLogger errorLogger = new StreamLogger(proc.getErrorStream(),
                            toString() + " (stderr)");
                    StreamLogger outputLogger = new StreamLogger(proc.getInputStream(),
                            toString() + " (stdout)");
                    new Thread(errorLogger).start();
                    new Thread(outputLogger).start();
                    proc.waitFor();

                    // Now set this filename as the base command...
                    //
                    base = new String[] { tempFilename };
                } catch (Exception e) {
                    throw new Exception("Unable to create temporary file to execute script", e);
                }
            }
        }

        // Construct the arguments...
        if (argFromPrevious && cmdRows != null) {
            // Add the base command...
            for (int i = 0; i < base.length; i++)
                cmds.add(base[i]);

            if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) {
                // for windows all arguments including the command itself
                // need to be
                // included in 1 argument to cmd/command.

                StringBuffer cmdline = new StringBuffer(300);

                cmdline.append('"');
                if (insertScript)
                    cmdline.append(realScript);
                else
                    cmdline.append(optionallyQuoteField(KettleVFS.getFilename(fileObject), "\""));
                // Add the arguments from previous results...
                for (int i = 0; i < cmdRows.size(); i++) // Normally just
                // one row, but
                // once in a
                // while to
                // remain
                // compatible we
                // have
                // multiple.
                {
                    RowMetaAndData r = (RowMetaAndData) cmdRows.get(i);
                    for (int j = 0; j < r.size(); j++) {
                        cmdline.append(' ');
                        cmdline.append(optionallyQuoteField(r.getString(j, null), "\""));
                    }
                }
                cmdline.append('"');
                cmds.add(cmdline.toString());
            } else {
                // Add the arguments from previous results...
                for (int i = 0; i < cmdRows.size(); i++) // Normally just
                // one row, but
                // once in a
                // while to
                // remain
                // compatible we
                // have
                // multiple.
                {
                    RowMetaAndData r = (RowMetaAndData) cmdRows.get(i);
                    for (int j = 0; j < r.size(); j++) {
                        cmds.add(optionallyQuoteField(r.getString(j, null), "\""));
                    }
                }
            }
        } else if (args != null) {
            // Add the base command...
            for (int i = 0; i < base.length; i++)
                cmds.add(base[i]);

            if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) {
                // for windows all arguments including the command itself
                // need to be
                // included in 1 argument to cmd/command.

                StringBuffer cmdline = new StringBuffer(300);

                cmdline.append('"');
                if (insertScript)
                    cmdline.append(realScript);
                else
                    cmdline.append(optionallyQuoteField(KettleVFS.getFilename(fileObject), "\""));

                for (int i = 0; i < args.length; i++) {
                    cmdline.append(' ');
                    cmdline.append(optionallyQuoteField(args[i], "\""));
                }
                cmdline.append('"');
                cmds.add(cmdline.toString());
            } else {
                for (int i = 0; i < args.length; i++) {
                    cmds.add(args[i]);
                }
            }
        }

        StringBuffer command = new StringBuffer();

        Iterator<String> it = cmds.iterator();
        boolean first = true;
        while (it.hasNext()) {
            if (!first)
                command.append(' ');
            else
                first = false;
            command.append((String) it.next());
        }
        if (log.isBasic())
            log.logBasic(toString(), Messages.getString("JobShell.ExecCommand", command.toString()));

        // Build the environment variable list...
        ProcessBuilder procBuilder = new ProcessBuilder(cmds);
        Map<String, String> env = procBuilder.environment();
        String[] variables = listVariables();
        for (int i = 0; i < variables.length; i++) {
            env.put(variables[i], getVariable(variables[i]));
        }

        if (getWorkDirectory() != null && !Const.isEmpty(Const.rtrim(getWorkDirectory()))) {
            String vfsFilename = environmentSubstitute(getWorkDirectory());
            File file = new File(KettleVFS.getFilename(KettleVFS.getFileObject(vfsFilename)));
            procBuilder.directory(file);
        }
        Process proc = procBuilder.start();

        // any error message?
        StreamLogger errorLogger = new StreamLogger(proc.getErrorStream(), toString() + " (stderr)");

        // any output?
        StreamLogger outputLogger = new StreamLogger(proc.getInputStream(), toString() + " (stdout)");

        // kick them off
        new Thread(errorLogger).start();
        new Thread(outputLogger).start();

        proc.waitFor();
        if (log.isDetailed())
            log.logDetailed(toString(), Messages.getString("JobShell.CommandFinished", command.toString()));

        // What's the exit status?
        result.setExitStatus(proc.exitValue());
        if (result.getExitStatus() != 0) {
            if (log.isDetailed())
                log.logDetailed(toString(), Messages.getString("JobShell.ExitStatus",
                        environmentSubstitute(getFilename()), "" + result.getExitStatus()));

            result.setNrErrors(1);
        }

        // close the streams
        // otherwise you get "Too many open files, java.io.IOException" after a lot of iterations
        proc.getErrorStream().close();
        proc.getOutputStream().close();

    } catch (IOException ioe) {
        log.logError(toString(), Messages.getString("JobShell.ErrorRunningShell",
                environmentSubstitute(getFilename()), ioe.toString()));
        result.setNrErrors(1);
    } catch (InterruptedException ie) {
        log.logError(toString(), Messages.getString("JobShell.Shellinterupted",
                environmentSubstitute(getFilename()), ie.toString()));
        result.setNrErrors(1);
    } catch (Exception e) {
        log.logError(toString(), Messages.getString("JobShell.UnexpectedError",
                environmentSubstitute(getFilename()), e.toString()));
        result.setNrErrors(1);
    } finally {
        // If we created a temporary file, remove it...
        //
        if (tempFile != null) {
            try {
                tempFile.delete();
            } catch (Exception e) {
                Messages.getString("JobShell.UnexpectedError", tempFile.toString(), e.toString());
            }
        }
    }

    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }
}

From source file:org.simmi.GeneSetHead.java

License:asdf

public void doBlast(final String fasta, final String evaluestr, final boolean ids, final RunnableResult rr,
        boolean x) {
    /*File blastn;/*from  w w w  .j  ava  2s .c om*/
    File blastp;
    File makeblastdb;
    File blastx = new File( "c:\\\\Program files\\NCBI\\blast-2.2.29+\\bin\\blastx.exe" );
    if( !blastx.exists() ) {
       blastx = new File( "/opt/ncbi-blast-2.2.29+/bin/blastx" );
       if( !blastx.exists() ) {
    blastx = new File( "/usr/local/ncbi/blast/bin/blastx" );
    blastn = new File( "/usr/local/ncbi/blast/bin/blastn" );
    blastp = new File( "/usr/local/ncbi/blast/bin/blastp" );
            
    makeblastdb = new File( "/usr/local/ncbi/blast/bin/makeblastdb" );
       } else {
    blastn = new File( "/opt/ncbi-blast-2.2.29+/bin/blastn" );
    blastp = new File( "/opt/ncbi-blast-2.2.29+/bin/blastp" );
            
    makeblastdb = new File( "/opt/ncbi-blast-2.2.29+/bin/makeblastdb" );
       }
    } else {
       blastn = new File( "c:\\\\Program files\\NCBI\\blast-2.2.29+\\bin\\blastn.exe" );
       blastp = new File( "c:\\\\Program files\\NCBI\\blast-2.2.29+\\bin\\blastp.exe" );
               
       makeblastdb = new File( "c:\\\\Program files\\NCBI\\blast-2.2.29+\\bin\\makeblastdb.exe" );
    }*/

    String OS = System.getProperty("os.name").toLowerCase();
    int procs = Runtime.getRuntime().availableProcessors();
    String[] mcmds = { OS.indexOf("mac") >= 0 ? "/usr/local/bin/makeblastdb" : "makeblastdb", "-dbtype", "prot",
            "-title", "tmp", "-out", "tmp" };
    List<String> lcmd = new ArrayList<String>(Arrays.asList(mcmds));

    final ProcessBuilder mpb = new ProcessBuilder(lcmd);
    mpb.redirectErrorStream(true);
    try {
        final Process mp = mpb.start();

        new Thread() {
            public void run() {
                try {
                    OutputStream pos = mp.getOutputStream();
                    Writer ow = new OutputStreamWriter(pos);
                    for (Gene g : geneset.genelist) {
                        if (g.getTag() == null || g.getTag().length() == 0) {
                            GeneGroup gg = g.getGeneGroup();

                            if (gg != null) {
                                String name;
                                if (ids)
                                    name = g.id;
                                else {
                                    String addstr = "";
                                    Cog cog = gg.getCog(geneset.cogmap);
                                    String cazy = gg.getCommonCazy(geneset.cazymap);
                                    if (cog != null)
                                        addstr += "_" + cog.id;
                                    if (cazy != null) {
                                        if (addstr.length() > 0)
                                            addstr += cazy;
                                        addstr += "_" + cazy;
                                    }
                                    if (addstr.length() > 0)
                                        addstr += "_";

                                    name = g.name + addstr + "[" + g.id + "]";
                                    //pos.write( (">" + g.name + addstr + "[" + g.id + "]\n").getBytes() );
                                }
                                Sequence sb = g.tegeval.getProteinSequence();
                                sb.setName(name);
                                sb.writeSequence(ow);
                                /*for( int i = 0; i < sb.length(); i+=70 ) {
                                   pos.write( sb.substring(i, Math.min( sb.length(), i+70) ).getBytes() );
                                }
                                pos.write( '\n' );*/
                            }
                        }
                    }
                    ow.close();
                    pos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread() {
            public void run() {
                try {
                    InputStream pin = mp.getInputStream();
                    InputStreamReader rdr = new InputStreamReader(pin);
                    //FileReader fr = new FileReader( new File("c:/dot.blastout") );
                    BufferedReader br = new BufferedReader(rdr);
                    String line = br.readLine();
                    while (line != null) {
                        System.out.println(line);
                        line = br.readLine();
                    }
                    pin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.run();

        //File blastFile = x ? blastx : blastp; //dbType.equals("prot") ? type.equals("prot") ? blastp : blastx : blastn;

        String[] cmds = { OS.indexOf("mac") >= 0 ? "/usr/local/bin/blastp" : "blastp", "-query", "-", "-db",
                "tmp", "-evalue", evaluestr, "-num_threads", Integer.toString(procs) };
        lcmd = new ArrayList<String>(Arrays.asList(cmds));
        //String[] exts = extrapar.trim().split("[\t ]+");

        ProcessBuilder pb = new ProcessBuilder(lcmd);
        pb.redirectErrorStream(true);
        final Process p = pb.start();

        final Thread t = new Thread() {
            public void run() {
                try {
                    OutputStream pos = p.getOutputStream();
                    pos.write(fasta.getBytes());
                    pos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        t.start();

        final Thread t2 = new Thread() {
            public void run() {
                try {
                    System.err.println("WHY NOT");
                    InputStreamReader rdr = new InputStreamReader(p.getInputStream());
                    //FileReader fr = new FileReader( new File("c:/dot.blastout") );

                    String res = "";
                    BufferedReader br = new BufferedReader(rdr);
                    String line = br.readLine();
                    while (line != null) {
                        //System.err.println( line );
                        if (line.startsWith("> ")) {
                            int i = line.indexOf(' ', 2);
                            if (i == -1)
                                i = line.length();
                            String id = line.substring(2, i);

                            Gene g = geneset.genemap.get(id);
                            if (g != null) {
                                if (!isGeneview()) {
                                    /*i = geneset.allgenegroups.indexOf( g.getGeneGroup() );
                                    if( i != -1 && i < table.getRowCount() ) {
                                       int r = table.convertRowIndexToView( i );
                                       table.addRowSelectionInterval(r, r);
                                    }*/
                                    table.getSelectionModel().select(g.getGeneGroup());
                                } else {
                                    /*i = geneset.genelist.indexOf( g );
                                    if( i != -1 && i < table.getRowCount() ) {
                                       int r = table.convertRowIndexToView( i );
                                       table.addRowSelectionInterval(r, r);
                                    }*/
                                    gtable.getSelectionModel().select(g);
                                }
                            }

                            String stuff = line + "\n";
                            line = br.readLine();
                            while (line != null && !line.startsWith("Query=") && !line.startsWith("> ")) {
                                stuff += line + "\n";
                                line = br.readLine();
                            }
                            if (rr != null) {
                                rr.run(stuff);
                                //res += line+"\n";
                            }
                        } else
                            line = br.readLine();
                    }
                    br.close();
                    //System.err.println("wn done");
                    p.destroy();

                    if (rr != null)
                        rr.run("close");

                    /*if( rr != null ) {
                       rr.run( res );
                    }*/
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        t2.start();
        //fr.close();
    } catch (IOException e2) {
        e2.printStackTrace();
    }
}

From source file:org.simmi.GeneSetHead.java

License:asdf

public void doBlastn(final String fasta, final String evaluestr, final boolean ids, final RunnableResult rr,
        boolean show) {
    /*File blastn;// w w  w  .  j a  va2s.  c o  m
    File blastp;
    File makeblastdb;
    File blastx = new File( "c:\\\\Program files\\NCBI\\blast-2.2.29+\\bin\\blastx.exe" );
    if( !blastx.exists() ) {
       blastx = new File( "/opt/ncbi-blast-2.2.29+/bin/blastx" );
       if( !blastx.exists() ) {
    blastx = new File( "/usr/local/ncbi/blast/bin/blastx" );
    blastn = new File( "/usr/local/ncbi/blast/bin/blastn" );
    blastp = new File( "/usr/local/ncbi/blast/bin/blastp" );
            
    makeblastdb = new File( "/usr/local/ncbi/blast/bin/makeblastdb" );
       } else {
    blastn = new File( "/opt/ncbi-blast-2.2.29+/bin/blastn" );
    blastp = new File( "/opt/ncbi-blast-2.2.29+/bin/blastp" );
            
    makeblastdb = new File( "/opt/ncbi-blast-2.2.29+/bin/makeblastdb" );
       }
    } else {
       blastn = new File( "c:\\\\Program files\\NCBI\\blast-2.2.29+\\bin\\blastn.exe" );
       blastp = new File( "c:\\\\Program files\\NCBI\\blast-2.2.29+\\bin\\blastp.exe" );
               
       makeblastdb = new File( "c:\\\\Program files\\NCBI\\blast-2.2.29+\\bin\\makeblastdb.exe" );
    }*/

    int procs = Runtime.getRuntime().availableProcessors();
    String[] mcmds = { "makeblastdb", "-dbtype", "nucl", "-title", "tmp", "-out", "tmp" };
    List<String> lcmd = new ArrayList<String>(Arrays.asList(mcmds));

    final ProcessBuilder mpb = new ProcessBuilder(lcmd);
    mpb.redirectErrorStream(true);
    try {
        final Process mp = mpb.start();

        new Thread() {
            public void run() {
                try {
                    OutputStream pos = mp.getOutputStream();
                    for (String cname : geneset.contigmap.keySet()) {
                        Sequence c = geneset.contigmap.get(cname);
                        if (ids)
                            pos.write((">" + c.id + "\n").getBytes());
                        else {
                            pos.write((">" + c.getName() + "\n").getBytes());
                        }
                        StringBuilder sb = c.getStringBuilder();
                        for (int i = 0; i < sb.length(); i += 70) {
                            pos.write(sb.substring(i, Math.min(sb.length(), i + 70)).getBytes());
                        }
                        pos.write('\n');
                    }
                    pos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread() {
            public void run() {
                try {
                    InputStream pin = mp.getInputStream();
                    InputStreamReader rdr = new InputStreamReader(pin);
                    //FileReader fr = new FileReader( new File("c:/dot.blastout") );
                    BufferedReader br = new BufferedReader(rdr);
                    String line = br.readLine();
                    while (line != null) {
                        System.out.println(line);
                        line = br.readLine();
                    }
                    pin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.run();

        //File blastFile = blastn; //dbType.equals("prot") ? type.equals("prot") ? blastp : blastx : blastn;

        String[] cmds1 = { "blastn", "-dust", "no", "-perc_identity", "99", "-word_size", "21", "-query", "-",
                "-db", "tmp", "-evalue", evaluestr, "-num_threads", Integer.toString(procs) };
        String[] cmds2 = { "blastn", "-query", "-", "-db", "tmp", "-evalue", evaluestr, "-num_threads",
                Integer.toString(procs) };
        String[] cmds = show ? cmds2 : cmds1;

        lcmd = new ArrayList<String>(Arrays.asList(cmds));
        //String[] exts = extrapar.trim().split("[\t ]+");

        ProcessBuilder pb = new ProcessBuilder(lcmd);
        pb.redirectErrorStream(true);
        final Process p = pb.start();

        final Thread t = new Thread() {
            public void run() {
                try {
                    OutputStream pos = p.getOutputStream();
                    pos.write(fasta.getBytes());
                    pos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        t.start();

        Map<String, Set<String>> tph = new HashMap<String, Set<String>>();
        Map<String, Map<String, String>> tvp = new HashMap<String, Map<String, String>>();
        Map<String, Map<String, String>> tmr = new HashMap<String, Map<String, String>>();

        Map<String, Integer> specindex = new LinkedHashMap<String, Integer>();
        Map<String, Integer> phindex = new LinkedHashMap<String, Integer>();

        /*final Thread t2 = new Thread() {
           public void run() {*/
        try {
            System.err.println("WHY NOT");
            InputStreamReader rdr = new InputStreamReader(p.getInputStream());
            //FileReader fr = new FileReader( new File("c:/dot.blastout") );

            String qspec = null;
            String query = null;
            String ctype = null;
            Annotation at = new Annotation();
            int o = 0;
            StringBuilder res = new StringBuilder();
            BufferedReader br = new BufferedReader(rdr);
            String line = br.readLine();
            res.append(line + "\n");
            while (line != null) {
                if (line.startsWith("Query= ")) {
                    query = line.substring(7, line.length());
                    int e = query.indexOf("CRISPR") - 1;
                    if (e > 0) {
                        qspec = query.substring(0, e);
                        qspec = Sequence.getSpec(qspec);
                        String rest = query.substring(e + 8);
                        int ri = rest.lastIndexOf('-');
                        if (ri != -1)
                            ctype = rest.substring(ri + 1);
                    } else {
                        System.err.println();
                    }

                    line = br.readLine();
                    res.append(line + "\n");
                    while (!line.startsWith("Length")) {
                        line = br.readLine();
                        res.append(line + "\n");
                    }
                    o = Integer.parseInt(line.substring(7));
                } else if (line.startsWith("> ")) {
                    String contname = line.substring(1).trim();
                    //line = br.readLine();
                    //res.append( line+"\n" );
                    //int o = Integer.parseInt( line.substring(7) );

                    Sequence cont = geneset.contigmap.get(contname);

                    if (cont != null) {
                        int start = -1;
                        int stop = 0;
                        line = br.readLine();
                        res.append(line + "\n");
                        String lastmatch = null;
                        while (line != null && !line.startsWith(">")
                                && !line.startsWith("Query=") /*&& !line.contains("Expect =")*/ ) {
                            if (line.startsWith("Sbjct")) {
                                String[] split = line.split("[\t ]+");
                                int k = Integer.parseInt(split[1]);
                                int m = Integer.parseInt(split[3]);
                                lastmatch = split[2];

                                if (start == -1)
                                    start = k;
                                stop = m;
                            }
                            line = br.readLine();
                            res.append(line + "\n");
                        }

                        if (start > stop) {
                            int tmp = start;
                            start = stop;
                            stop = tmp;
                        }

                        at.start = start;
                        at.stop = stop;

                        //if( stop - start < o*2 ) {
                        List<Annotation> lann = cont.getAnnotations();
                        if (lann != null) {
                            int k = Collections.binarySearch(lann, at);

                            //System.err.println( "kkk  " + k + "   " + lann.size() );

                            if (k < 0)
                                k = -(k + 1) - 1;

                            Annotation ann = lann.get(Math.max(0, k));

                            boolean yes = true;
                            if (ann.type != null && ann.type.contains("ummer")) {
                                yes = false;
                            }

                            int u = k - 1;
                            Annotation nann = null;
                            if (u >= 0 && u < lann.size())
                                nann = lann.get(u);

                            u = k + 1;
                            Annotation rann = null;
                            if (u >= 0 && u < lann.size())
                                rann = lann.get(u);

                            if (nann != null && nann.type != null && nann.type.contains("ummer")) {
                                yes = false;
                            }

                            if (rann != null && rann.type != null && rann.type.contains("ummer")) {
                                yes = false;
                            }

                            if (!yes) {
                                //System.err.println();
                            }

                            Gene g = ann.getGene();
                            String desig = ann.designation;

                            if (yes && g != null) { //ann.stop > at.start && ann.start < at.stop ) {
                                GeneGroup gg = g.getGeneGroup();
                                if (desig != null && desig.contains("phage")) {
                                    if (!phindex.containsKey(desig))
                                        phindex.put(desig, phindex.size());

                                    Map<String, String> tvps;
                                    String specname = qspec;//Sequence.nameFix(qspec, true);
                                    if (!specindex.containsKey(specname))
                                        specindex.put(specname, specindex.size());

                                    if (tvp.containsKey(specname)) {
                                        tvps = tvp.get(specname);
                                    } else {
                                        tvps = new HashMap<String, String>();
                                        tvp.put(specname, tvps);
                                    }
                                    tvps.put(desig, ctype);

                                    String contspec = cont.getSpec();
                                    System.err.println(query + " asdf " + contspec + " " + lastmatch + "  "
                                            + at.start + " " + at.stop + "  " + ann.start + " " + ann.stop
                                            + " rann " + (rann != null ? rann.start + "  " + rann.stop : "")
                                            + " nann " + (nann != null ? nann.start + "  " + nann.stop : ""));
                                    if (qspec.equals(contspec)) {
                                        if (tmr.containsKey(specname)) {
                                            tvps = tmr.get(specname);
                                        } else {
                                            tvps = new HashMap<String, String>();
                                            tmr.put(specname, tvps);
                                        }
                                        tvps.put(desig, ctype);
                                    }

                                    /*if( specname.contains("brockianus_MAT_338") ) {
                                       System.err.println();
                                    }*/
                                }

                                Platform.runLater(() -> {
                                    if (!isGeneview()) {
                                        /*int ggindex = geneset.allgenegroups.indexOf( gg );
                                        int i = table.convertRowIndexToView( ggindex );
                                        if( i != -1 ) table.addRowSelectionInterval(i, i);*/

                                        table.getSelectionModel().select(gg);
                                    } else {
                                        /*int gindex = geneset.genelist.indexOf( g );
                                        int i = table.convertRowIndexToView( gindex );
                                        table.addRowSelectionInterval(i, i);*/

                                        gtable.getSelectionModel().select(g);
                                    }
                                });
                            }

                            /*for( Annotation ann : lann ) {
                               if( ann.stop > start && ann.start < stop ) {
                            Gene g = ann.getGene();
                            if( g != null ) {
                               if( table.getModel() == groupModel ) {
                                  GeneGroup gg = g.getGeneGroup();
                                          
                                  int ggindex = allgenegroups.indexOf( gg );
                                  int i = table.convertRowIndexToView( ggindex );
                                  table.addRowSelectionInterval(i, i);
                               } else if( table.getModel() == defaultModel ) {
                                  int gindex = geneset.genelist.indexOf( g );
                                  int i = table.convertRowIndexToView( gindex );
                                  table.addRowSelectionInterval(i, i);
                               }
                            }
                               }
                            }*/
                        }
                        //}
                        continue;
                    }
                }

                /*int i = line.indexOf(' ', 2);
                if( i == -1 ) i = line.length();
                String id = line.substring(2, i);
                        
                Gene g = genemap.get( id );
                if( g != null ) {
                   if( table.getModel() == groupModel ) {
                      i = allgenegroups.indexOf( g.getGeneGroup() );
                      if( i != -1 && i < table.getRowCount() ) {
                         int r = table.convertRowIndexToView( i );
                         table.addRowSelectionInterval(r, r);
                      }
                   } else {
                      i = geneset.genelist.indexOf( g );
                      if( i != -1 && i < table.getRowCount() ) {
                         int r = table.convertRowIndexToView( i );
                         table.addRowSelectionInterval(r, r);
                      }
                   }
                }
                        
                String stuff = line+"\n";
                line = br.readLine();
                while( line != null && !line.startsWith("Query=") && !line.startsWith("> ") ) {
                   stuff += line+"\n";
                   line = br.readLine();
                }
                if( rr != null ) {
                   rr.run( stuff );
                   //res += line+"\n";
                }
                } //else*/
                line = br.readLine();
                res.append(line + "\n");
            }
            br.close();
            p.destroy();

            for (String specname : geneset.speccontigMap.keySet()) {
                List<Sequence> lseq = geneset.speccontigMap.get(specname);
                for (Sequence seq : lseq) {
                    List<Annotation> lann = seq.getAnnotations();
                    if (lann != null) {
                        for (Annotation a : lann) {
                            String desig = a.designation;
                            if (desig != null && desig.contains("phage") && phindex.containsKey(desig)) {
                                if (!specindex.containsKey(specname))
                                    specindex.put(specname, specindex.size());

                                Set<String> tvps;
                                if (tph.containsKey(specname)) {
                                    tvps = tph.get(specname);
                                } else {
                                    tvps = new HashSet<String>();
                                    tph.put(specname, tvps);
                                }
                                tvps.add(desig);
                            }
                        }
                    }
                }
            }

            int k = 0;
            int u = 0;
            Workbook wb = new XSSFWorkbook();
            Sheet sh = wb.createSheet("Phage");
            Row rw = sh.createRow(u++);
            //res = new StringBuilder();
            for (String ph : phindex.keySet()) {
                res.append("\t" + ph);
                rw.createCell(++k).setCellValue(ph);
            }
            res.append("\n");
            for (String rspec : specindex.keySet()) {
                String spec = Sequence.nameFix(rspec, true);
                rw = sh.createRow(u++);
                k = 0;
                rw.createCell(k++).setCellValue(spec);

                Map<String, String> set = tvp.get(rspec);
                res.append(spec);
                if (set != null) {
                    for (String ph : phindex.keySet()) {
                        if (set.containsKey(ph)) {
                            String type = set.get(ph);
                            if (type == null || type.length() == 0)
                                type = "yes";
                            res.append("\t" + type);
                            rw.createCell(k).setCellValue(type);
                        } else {
                            res.append("\t");
                        }

                        k++;
                    }
                }
                res.append("\n");
            }

            for (String ph : phindex.keySet()) {
                res.append("\t" + ph);
            }
            res.append("\n");

            u++;
            for (String rspec : specindex.keySet()) {
                String spec = Sequence.nameFix(rspec, true);

                rw = sh.createRow(u++);
                k = 0;
                rw.createCell(k++).setCellValue(spec);

                Map<String, String> set = tmr.get(rspec);
                res.append(spec);
                if (set != null) {
                    for (String ph : phindex.keySet()) {
                        if (set.containsKey(ph)) {
                            String type = set.get(ph);
                            if (type == null || type.length() == 0)
                                type = "yes";
                            res.append("\t" + type);
                            rw.createCell(k).setCellValue(type);
                        } else
                            res.append("\t");

                        k++;
                    }
                }
                res.append("\n");
            }

            u++;
            for (String rspec : specindex.keySet()) {
                String spec = Sequence.nameFix(rspec, true);

                rw = sh.createRow(u++);
                k = 0;
                rw.createCell(k++).setCellValue(spec);

                Set<String> set = tph.get(rspec);
                Map<String, String> setvp = tvp.get(rspec);
                res.append(spec);
                if (set != null) {
                    for (String ph : phindex.keySet()) {
                        if (set.contains(ph)) {
                            if (setvp != null && setvp.containsKey(ph)) {
                                res.append("\tyes wspacer");
                                rw.createCell(k).setCellValue("yes wspacer");
                            } else {
                                res.append("\tyes");
                                rw.createCell(k).setCellValue("yes");
                            }
                        } else
                            res.append("\t");

                        k++;
                    }
                }
                res.append("\n");
            }

            File file = new File("/Users/sigmar/phage.xlsx");
            FileOutputStream fos = new FileOutputStream(file);
            wb.write(fos);
            fos.close();

            Desktop.getDesktop().open(file);

            //if( !show ) {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setSize(800, 600);

            JTextArea ta = new JTextArea();
            ta.setFont(new Font("monospaced", Font.PLAIN, 12));
            ta.append(res.toString());
            JScrollPane sp = new JScrollPane(ta);
            frame.add(sp);

            frame.setVisible(true);

            FileWriter fw = new FileWriter("/Users/sigmar/file.txt");
            fw.write(res.toString());
            fw.close();

            if (rr != null)
                rr.run("close");
            //}

            /*if( rr != null ) {
             rr.run( res );
            }*/
        } catch (IOException e) {
            e.printStackTrace();
        }
        /*   }
        };
        t2.start();*/
        //fr.close();
    } catch (IOException e2) {
        e2.printStackTrace();
    }
}

From source file:com.clark.func.Functions.java

/**
 * Performs the os command./*from   ww  w .  j a v a 2s  . c o  m*/
 * 
 * @param cmdAttribs
 *            the command line parameters
 * @param max
 *            The maximum limit for the lines returned
 * @param timeout
 *            The timout amount in milliseconds or no timeout if the value
 *            is zero or less
 * @return the parsed data
 * @throws IOException
 *             if an error occurs
 */
static List<String> performCommand(String[] cmdAttribs, int max, long timeout) throws IOException {
    // this method does what it can to avoid the 'Too many open files' error
    // based on trial and error and these links:
    // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4784692
    // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4801027
    // http://forum.java.sun.com/thread.jspa?threadID=533029&messageID=2572018
    // however, its still not perfect as the JDK support is so poor
    // (see commond-exec or ant for a better multi-threaded multi-os
    // solution)

    List<String> lines = new ArrayList<String>(20);
    Process proc = null;
    InputStream in = null;
    OutputStream out = null;
    InputStream err = null;
    BufferedReader inr = null;
    try {

        Thread monitor = ThreadMonitor.start(timeout);

        proc = openProcess(cmdAttribs);
        in = proc.getInputStream();
        out = proc.getOutputStream();
        err = proc.getErrorStream();
        inr = new BufferedReader(new InputStreamReader(in));
        String line = inr.readLine();
        while (line != null && lines.size() < max) {
            line = line.toLowerCase(Locale.ENGLISH).trim();
            lines.add(line);
            line = inr.readLine();
        }

        proc.waitFor();

        ThreadMonitor.stop(monitor);

        if (proc.exitValue() != 0) {
            // os command problem, throw exception
            throw new IOException("Command line returned OS error code '" + proc.exitValue() + "' for command "
                    + Arrays.asList(cmdAttribs));
        }
        if (lines.size() == 0) {
            // unknown problem, throw exception
            throw new IOException(
                    "Command line did not return any info " + "for command " + Arrays.asList(cmdAttribs));
        }
        return lines;

    } catch (InterruptedException ex) {
        throw new IOExceptionWithCause("Command line threw an InterruptedException " + "for command "
                + Arrays.asList(cmdAttribs) + " timeout=" + timeout, ex);
    } finally {
        closeQuietly(in);
        closeQuietly(out);
        closeQuietly(err);
        closeQuietly(inr);
        if (proc != null) {
            proc.destroy();
        }
    }
}