Example usage for java.io BufferedReader ready

List of usage examples for java.io BufferedReader ready

Introduction

In this page you can find the example usage for java.io BufferedReader ready.

Prototype

public boolean ready() throws IOException 

Source Link

Document

Tells whether this stream is ready to be read.

Usage

From source file:edu.uci.ics.jung.io.CustomPajekNetReader.java

/**
 * Populates the graph <code>g</code> with the graph represented by the
 * Pajek-format data supplied by <code>reader</code>. Stores edge weights,
 * if any, according to <code>nev</code> (if non-null).
 *
 * <p>/*w  w w . j a v  a2s .co  m*/
 * Any existing vertices/edges of <code>g</code>, if any, are unaffected.
 *
 * <p>
 * The edge data are filtered according to <code>g</code>'s constraints, if
 * any; thus, if <code>g</code> only accepts directed edges, any undirected
 * edges in the input are ignored.
 *
 * @throws IOException
 */
public G load(Reader reader, G g) throws IOException {
    BufferedReader br = new BufferedReader(reader);

    // ignore everything until we see '*Colors'
    String curLine = skip(br, cc_pred);

    StringTokenizer st = new StringTokenizer(curLine);
    st.nextToken(); // skip past "*colors";
    String[] colorMetadata = st.nextToken().split(",");
    ((MyGraph) g).getLayoutParameters().setBackgroundColor(Integer.parseInt(colorMetadata[0]));
    ((MyGraph) g).getLayoutParameters().setEdgeColor(Integer.parseInt(colorMetadata[1]));

    // ignore everything until we see '*Vertices'
    curLine = skip(br, v_pred);

    if (curLine == null) // no vertices in the graph; return empty graph
    {
        return g;
    }

    // create appropriate number of vertices
    st = new StringTokenizer(curLine);
    st.nextToken(); // skip past "*vertices";

    String[] vertexMetadata = st.nextToken().split(",");

    int num_vertices = Integer.parseInt(vertexMetadata[0]);
    boolean areVertexIconsAllowed = Boolean.parseBoolean(vertexMetadata[1]);

    ((MyGraph) g).getLayoutParameters().setAllowNodeIcons(areVertexIconsAllowed);

    List<V> id = null;
    if (vertex_factory != null) {
        for (int i = 1; i <= num_vertices; i++) {
            g.addVertex(vertex_factory.create());
        }
        id = new ArrayList<V>(g.getVertices());
    }

    // read vertices until we see any Pajek format tag ('*...')
    curLine = null;
    while (br.ready()) {
        curLine = br.readLine();
        if (curLine == null || t_pred.evaluate(curLine)) {
            break;
        }
        if (curLine == "") // skip blank lines
        {
            continue;
        }

        try {
            readVertex(curLine, id, num_vertices, g);
        } catch (IllegalArgumentException iae) {
            br.close();
            reader.close();
            throw iae;
        }
    }

    // skip over the intermediate stuff (if any) 
    // and read the next arcs/edges section that we find
    curLine = readArcsOrEdges(curLine, br, g, id, edge_factory);

    // ditto
    readArcsOrEdges(curLine, br, g, id, edge_factory);

    br.close();
    reader.close();

    return g;
}

From source file:ffx.potential.parsers.INTFilter.java

/**
 * {@inheritDoc}//from w  w w.  j a v  a2s .c  o  m
 *
 * Parse the INT File.
 *
 * @since 1.0
 */
@Override
public boolean readFile() {
    File intFile = activeMolecularAssembly.getFile();
    if (forceField == null) {
        logger.warning("No force field is associated with " + intFile.toString());
        return false;
    }
    // Open a data stream to the Internal Coordinate file
    try {
        FileReader fr = new FileReader(intFile);
        BufferedReader br = new BufferedReader(fr);
        String data = br.readLine().trim();
        // Read blank lines at the top of the file
        while (data != null && data.length() == 0) {
            data = br.readLine().trim();
        }
        if (data == null) {
            logger.warning("Empty file: " + intFile.toString());
            return false;
        }
        int numberOfAtoms;
        String tokens[] = data.trim().split(" +");
        try {
            numberOfAtoms = Integer.parseInt(tokens[0]);
            if (numberOfAtoms < 1) {
                logger.warning("Invalid number of atoms: " + numberOfAtoms);
                return false;
            }
        } catch (Exception e) {
            logger.severe("Error parsing the number of atoms.\n" + e);
            return false;
        }
        if (tokens.length >= 2) {
            tokens = data.trim().split(" +", 2);
            activeMolecularAssembly.setName(tokens[1]);
        }
        logger.info("  Opening " + intFile.getName() + " with " + numberOfAtoms + " atoms");
        double d[] = { 0.0d, 0.0d, 0.0d };
        int zi[][] = new int[numberOfAtoms][4];
        double zv[][] = new double[numberOfAtoms][3];
        Vector<int[]> zadd = new Vector<int[]>();
        Vector<int[]> zdel = new Vector<int[]>();
        atomList = new ArrayList<Atom>();
        for (int i = 0; i < numberOfAtoms; i++) {
            // Atom Data
            if (!br.ready()) {
                return false;
            }
            data = br.readLine();
            if (data == null) {
                logger.severe("  Check atom " + (i + 1) + " in " + activeMolecularAssembly.getFile().getName());
                return false;
            }
            tokens = data.trim().split(" +");
            if (tokens == null || tokens.length < 3) {
                logger.severe("  Check atom " + (i + 1) + " in " + activeMolecularAssembly.getFile().getName());
                return false;
            }
            // Atom number, name, type
            String name = tokens[1];
            int type = Integer.parseInt(tokens[2]);
            AtomType atomType = forceField.getAtomType(String.valueOf(type));
            if (atomType == null) {
                logger.severe("  Check atom " + (i + 1) + " in " + activeMolecularAssembly.getFile().getName());
                return false;
            }
            Atom atom = new Atom(i + 1, name, atomType, d);
            atomList.add(atom);
            // Bond partner and bond value
            if (tokens.length >= 5) {
                zi[i][0] = Integer.parseInt(tokens[3]);
                zv[i][0] = Double.parseDouble(tokens[4]);
            } else {
                zi[i][0] = 0;
                zv[i][0] = 0.0d;
            }
            // Angle partner and angle value
            if (tokens.length >= 7) {
                zi[i][1] = Integer.parseInt(tokens[5]);
                zv[i][1] = Double.parseDouble(tokens[6]);
            } else {
                zi[i][1] = 0;
                zv[i][1] = 0.0d;
            }
            // Torsion partner and dihedral value
            if (tokens.length >= 10) {
                zi[i][2] = Integer.parseInt(tokens[7]);
                zv[i][2] = Double.parseDouble(tokens[8]);
                zi[i][3] = Integer.parseInt(tokens[9]);
            } else {
                zi[i][2] = 0;
                zv[i][2] = 0.0d;
                zi[i][3] = 0;
            }
        }
        if (br.ready()) {
            data = br.readLine();
            // Check for a first blank line
            if (data.trim().equalsIgnoreCase("")) {
                // Parse bond pairs to add until EOF or a blank line is
                // reached
                boolean blank = false;
                while (br.ready() && !blank) {
                    data = br.readLine();
                    if (data.trim().equalsIgnoreCase("")) {
                        blank = true;
                    } else {
                        tokens = data.trim().split(" +");
                        if (tokens.length != 2) {
                            logger.severe("  Check Additional Bond Pair: " + (zadd.size() + 1) + " in "
                                    + activeMolecularAssembly.getFile().getName());
                            return false;
                        }
                        int pair[] = new int[2];
                        pair[0] = Integer.parseInt(tokens[0]);
                        pair[1] = Integer.parseInt(tokens[1]);
                        zadd.add(pair);
                    }
                }
                // Parse bond pairs to be removed until EOF
                while (br.ready()) {
                    data = br.readLine();
                    tokens = data.trim().split(" +");
                    if (tokens.length != 2) {
                        logger.severe("  Check Bond Pair to Remove: " + (zadd.size() + 1) + " in "
                                + activeMolecularAssembly.getFile().getName());
                        return false;
                    }
                    int pair[] = new int[2];
                    pair[0] = Integer.parseInt(tokens[0]);
                    pair[1] = Integer.parseInt(tokens[1]);
                    zdel.add(pair);
                }
            }
        }
        br.close();
        fr.close();
        if (atomList.size() == numberOfAtoms) {
            // Add bonds specified in the Z-matrix
            bondList = new ArrayList<Bond>();
            for (int i = 1; i < numberOfAtoms; i++) {
                int partner = zi[i][0];
                boolean del = false;
                for (int j = 0; j < zdel.size(); j++) {
                    int pair[] = zdel.get(j);
                    if (pair[0] == i + 1 && pair[1] == partner) {
                        del = true;
                    }
                    if (pair[1] == i + 1 && pair[0] == partner) {
                        del = true;
                    }
                }
                if (!del) {
                    Atom atom1 = atomList.get(i);
                    Atom atom2 = atomList.get(partner - 1);
                    bondList.add(new Bond(atom1, atom2));
                }
            }
            // Add additional bonds
            for (int i = 0; i < zadd.size(); i++) {
                int pair[] = zadd.get(i);
                Atom atom1 = atomList.get(pair[0] - 1);
                Atom atom2 = atomList.get(pair[1] - 1);
                bondList.add(new Bond(atom1, atom2));
            }
            // Determine coordinates from Z-matrix values
            for (int i = 0; i < numberOfAtoms; i++) {
                Atom atom = atomList.get(i);
                Atom ia = null;
                Atom ib = null;
                Atom ic = null;
                int[] atoms = zi[i];
                if (atoms[0] > 0) {
                    ia = atomList.get(atoms[0] - 1);
                }
                if (atoms[1] > 0) {
                    ib = atomList.get(atoms[1] - 1);
                }
                if (atoms[2] > 0) {
                    ic = atomList.get(atoms[2] - 1);
                }
                double bond = zv[i][0];
                double angle1 = zv[i][1];
                double angle2 = zv[i][2];
                int chiral = atoms[3];
                intxyz(atom, ia, bond, ib, angle1, ic, angle2, chiral);
            }
            return true;
        }
        logger.warning(
                "Reported number of Atoms: " + numberOfAtoms + "\nNumber of Atoms Found: " + atomList.size());
    } catch (IOException e) {
        logger.severe(e.toString());
    }
    return false;
}

From source file:ffx.potential.parsers.XYZFilter.java

/**
 * {@inheritDoc}//from  w  w w.j  a  va 2 s  .  com
 *
 * Parse the XYZ File
 */
@Override
public boolean readFile() {
    File xyzFile = activeMolecularAssembly.getFile();

    if (forceField == null) {
        logger.warning(" No force field is associated with " + xyzFile.toString());
        return false;
    }
    try {
        FileReader fr = new FileReader(xyzFile);
        BufferedReader br = new BufferedReader(fr);
        String data = br.readLine();
        // Read blank lines at the top of the file
        while (data != null && data.trim().equals("")) {
            data = br.readLine();
        }
        if (data == null) {
            return false;
        }
        String tokens[] = data.trim().split(" +", 2);
        int numberOfAtoms = Integer.parseInt(tokens[0]);
        if (numberOfAtoms < 1) {
            return false;
        }
        if (tokens.length == 2) {
            getActiveMolecularSystem().setName(tokens[1]);
        }
        logger.info("\n Opening " + xyzFile.getName() + " with " + numberOfAtoms + " atoms\n");
        // The header line is reasonable - prepare to parse atom lines.
        Hashtable<Integer, Integer> labelHash = new Hashtable<Integer, Integer>();
        int label[] = new int[numberOfAtoms];
        int bonds[][] = new int[numberOfAtoms][8];
        double d[][] = new double[numberOfAtoms][3];
        boolean renumber = false;
        atomList = new ArrayList<Atom>();
        // Loop over the expected number of atoms.
        for (int i = 0; i < numberOfAtoms; i++) {
            if (!br.ready()) {
                return false;
            }
            data = br.readLine();
            if (data == null) {
                logger.warning("Check atom " + (i + 1) + " in " + activeMolecularAssembly.getFile().getName());
                return false;
            }
            tokens = data.trim().split(" +");
            if (tokens == null || tokens.length < 6) {
                logger.warning("Check atom " + (i + 1) + " in " + activeMolecularAssembly.getFile().getName());
                return false;
            }
            // Valid number of tokens, so try to parse this line.
            label[i] = Integer.parseInt(tokens[0]);
            // Check for valid atom numbering, or flag for re-numbering.
            if (label[i] != i + 1) {
                renumber = true;
            }
            String atomName = tokens[1];
            d[i][0] = Double.parseDouble(tokens[2]);
            d[i][1] = Double.parseDouble(tokens[3]);
            d[i][2] = Double.parseDouble(tokens[4]);
            int type = Integer.parseInt(tokens[5]);
            AtomType atomType = forceField.getAtomType(Integer.toString(type));
            if (atomType == null) {
                StringBuilder message = new StringBuilder("Check atom type ");
                message.append(type).append(" for Atom ").append(i + 1);
                message.append(" in ").append(activeMolecularAssembly.getFile().getName());
                logger.warning(message.toString());
                return false;
            }
            Atom a = new Atom(i + 1, atomName, atomType, d[i]);
            atomList.add(a);
            // Bond Data
            int numberOfBonds = tokens.length - 6;
            for (int b = 0; b < 8; b++) {
                if (b < numberOfBonds) {
                    int bond = Integer.parseInt(tokens[6 + b]);
                    bonds[i][b] = bond;
                } else {
                    bonds[i][b] = 0;
                }
            }
        }
        // Check if this is an archive.
        if (br.ready()) {
            // Read past blank lines between archive files
            data = br.readLine().trim();
            while (data != null && data.equals("")) {
                data = br.readLine().trim();
            }
            if (data != null) {
                tokens = data.split(" +", 2);
                if (tokens != null && tokens.length > 0) {
                    try {
                        int archiveNumberOfAtoms = Integer.parseInt(tokens[0]);
                        if (archiveNumberOfAtoms == numberOfAtoms) {
                            setType(FileType.ARC);
                        }
                    } catch (Exception e) {
                        tokens = null;
                    }
                }
            }
        }
        br.close();
        fr.close();
        // Try to renumber
        if (renumber) {
            for (int i = 0; i < numberOfAtoms; i++) {
                if (labelHash.containsKey(label[i])) {
                    logger.warning("Two atoms have the same index: " + label[i]);
                    return false;
                }
                labelHash.put(label[i], i + 1);
            }
            for (int i = 0; i < numberOfAtoms; i++) {
                int j = -1;
                while (j < 3 && bonds[i][++j] > 0) {
                    bonds[i][j] = labelHash.get(bonds[i][j]);
                }
            }
        }
        bondList = new ArrayList<Bond>();
        int c[] = new int[2];
        for (int i = 1; i <= numberOfAtoms; i++) {
            int a1 = i;
            int j = -1;
            while (j < 7 && bonds[i - 1][++j] > 0) {
                int a2 = bonds[i - 1][j];
                if (a1 < a2) {
                    if (a1 > numberOfAtoms || a1 < 1 || a2 > numberOfAtoms || a2 < 1) {
                        logger.warning("Check the Bond Bewteen " + a1 + " and " + a2 + " in "
                                + activeMolecularAssembly.getFile().getName());
                        return false;
                    }
                    // Check for bidirectional connection
                    boolean bidirectional = false;
                    int k = -1;
                    while (k < 7 && bonds[a2 - 1][++k] > 0) {
                        int a3 = bonds[a2 - 1][k];
                        if (a3 == a1) {
                            bidirectional = true;
                            break;
                        }
                    }
                    if (!bidirectional) {
                        logger.warning("Check the Bond Bewteen " + a1 + " and " + a2 + " in "
                                + activeMolecularAssembly.getFile().getName());
                        return false;
                    }
                    Atom atom1 = atomList.get(a1 - 1);
                    Atom atom2 = atomList.get(a2 - 1);
                    if (atom1 == null || atom2 == null) {
                        logger.warning("Check the Bond Bewteen " + a1 + " and " + a2 + " in "
                                + activeMolecularAssembly.getFile().getName());
                        return false;
                    }
                    Bond bond = new Bond(atom1, atom2);
                    c[0] = atom1.getAtomType().atomClass;
                    c[1] = atom2.getAtomType().atomClass;
                    String key = BondType.sortKey(c);
                    BondType bondType = forceField.getBondType(key);
                    if (bondType == null) {
                        logger.severe("No BondType for key: " + key);
                    } else {
                        bond.setBondType(bondType);
                    }
                    bondList.add(bond);
                }
            }
        }
        /*
         if (getType() == FileType.ARC) {
         return readtrajectory();
         } */
        return true;
    } catch (IOException e) {
        logger.severe(e.toString());
    }
    return false;
}

From source file:org.ejbca.util.CertTools.java

/**
 * Reads a certificate in PEM-format from an InputStream. The stream may contain other things,
 * the first certificate in the stream is read.
 *
 * @param certstream the input stream containing the certificate in PEM-format
 * @return Ordered Collection of Certificate, first certificate first, or empty Collection
 * @exception IOException if the stream cannot be read.
 * @exception CertificateException if the stream does not contain a correct certificate.
 *///w  ww . ja  va 2s.  com
public static Collection<Certificate> getCertsFromPEM(InputStream certstream)
        throws IOException, CertificateException {
    if (log.isTraceEnabled()) {
        log.trace(">getCertfromPEM");
    }
    ArrayList<Certificate> ret = new ArrayList<Certificate>();
    String beginKeyTrust = "-----BEGIN TRUSTED CERTIFICATE-----";
    String endKeyTrust = "-----END TRUSTED CERTIFICATE-----";
    BufferedReader bufRdr = null;
    ByteArrayOutputStream ostr = null;
    PrintStream opstr = null;
    try {
        bufRdr = new BufferedReader(new InputStreamReader(certstream));
        while (bufRdr.ready()) {
            ostr = new ByteArrayOutputStream();
            opstr = new PrintStream(ostr);
            String temp;
            while ((temp = bufRdr.readLine()) != null
                    && !(temp.equals(CertTools.BEGIN_CERTIFICATE) || temp.equals(beginKeyTrust))) {
                continue;
            }
            if (temp == null) {
                if (ret.isEmpty()) {
                    // There was no certificate in the file
                    throw new IOException("Error in " + certstream.toString() + ", missing "
                            + CertTools.BEGIN_CERTIFICATE + " boundary");
                } else {
                    // There were certificates, but some blank lines or something in the end
                    // anyhow, the file has ended so we can break here.
                    break;
                }
            }
            while ((temp = bufRdr.readLine()) != null
                    && !(temp.equals(CertTools.END_CERTIFICATE) || temp.equals(endKeyTrust))) {
                opstr.print(temp);
            }
            if (temp == null) {
                throw new IOException("Error in " + certstream.toString() + ", missing "
                        + CertTools.END_CERTIFICATE + " boundary");
            }
            opstr.close();

            byte[] certbuf = Base64.decode(ostr.toByteArray());
            ostr.close();
            // Phweeew, were done, now decode the cert from file back to Certificate object
            Certificate cert = getCertfromByteArray(certbuf);
            ret.add(cert);
        }
    } finally {
        if (bufRdr != null) {
            bufRdr.close();
        }
        if (opstr != null) {
            opstr.close();
        }
        if (ostr != null) {
            ostr.close();
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("<getcertfromPEM:" + ret.size());
    }
    return ret;
}

From source file:configuration.Util.java

public Vector<String> read(String filename) {
    Vector<String> tmp = new Vector<String>();
    try {// ww  w . jav  a 2s .c o m
        BufferedReader br = new BufferedReader(new FileReader(new File(filename)));
        while (br.ready()) {
            tmp.add(br.readLine());
        }
    } catch (Exception e) {
        System.out.println("Copy Failed!");
        System.out.println(e);
        return tmp;
    }
    return tmp;
}

From source file:org.eclipsetrader.yahoo.internal.core.connector.StreamingConnector.java

@Override
public void run() {
    BufferedReader in = null;
    char[] buffer = new char[512];

    try {/*from w  w  w .  ja va  2s . com*/
        HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        Util.setupProxy(client, Util.streamingFeedHost);

        HttpMethod method = null;

        while (!isStopping()) {
            // Check if the connection was not yet initialized or there are changed in the subscriptions.
            if (in == null || isSubscriptionsChanged()) {
                try {
                    if (method != null) {
                        method.releaseConnection();
                    }
                    if (in != null) {
                        in.close();
                    }
                } catch (Exception e) {
                    // We can't do anything at this time, ignore
                }

                String[] symbols;
                synchronized (symbolSubscriptions) {
                    Set<String> s = new HashSet<String>(symbolSubscriptions.keySet());
                    s.add("MSFT");
                    symbols = s.toArray(new String[s.size()]);
                    setSubscriptionsChanged(false);
                    if (symbols.length == 0) {
                        break;
                    }
                }
                method = Util.getStreamingFeedMethod(symbols);

                client.executeMethod(method);

                in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));

                line = new StringBuilder();
                script = new StringBuilder();
                inTag = false;
                inScript = false;

                fetchLatestSnapshot(client, symbols, false);
            }

            if (in.ready()) {
                int length = in.read(buffer);
                if (length == -1) {
                    in.close();
                    in = null;
                    continue;
                }
                processIncomingChars(buffer, length);
            } else {
                // Check stale data
                List<String> updateList = new ArrayList<String>();
                synchronized (symbolSubscriptions) {
                    long currentTime = System.currentTimeMillis();
                    for (FeedSubscription subscription : symbolSubscriptions.values()) {
                        long elapsedTime = currentTime - subscription.getIdentifierType().getLastUpdate();
                        if (elapsedTime >= 60000) {
                            updateList.add(subscription.getIdentifierType().getSymbol());
                            subscription.getIdentifierType().setLastUpdate(currentTime / 60000 * 60000);
                        }
                    }
                }
                if (updateList.size() != 0) {
                    fetchLatestSnapshot(client, updateList.toArray(new String[updateList.size()]), true);
                }
            }

            Thread.sleep(100);
        }
    } catch (Exception e) {
        Status status = new Status(IStatus.ERROR, YahooActivator.PLUGIN_ID, 0, "Error reading data", e);
        YahooActivator.log(status);
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e) {
            // We can't do anything at this time, ignore
        }
    }
}

From source file:configuration.Util.java

/**
 * Return the content of the Ressource with the specified name
 * @param name//w w w. ja  v a 2s. c  o m
 * @return
 */
public String getRessource(String name) {
    String str = "";
    try {
        BufferedReader br = new BufferedReader(
                new InputStreamReader(this.getClass().getResourceAsStream(name)));
        while (br.ready()) {
            str += br.readLine() + "\n";
        }
    } catch (Exception e) {
        System.out.println("Get Ressource " + name + " Failed!");
        System.out.println(e);
    }
    return str;
}

From source file:jmri.enginedriver.threaded_application.java

private void set_default_function_labels() {
    function_labels_default = new LinkedHashMap<Integer, String>();
    try {//from   w w w  .j a  v  a 2 s . co m
        File sdcard_path = Environment.getExternalStorageDirectory();
        File settings_file = new File(sdcard_path + "/engine_driver/function_settings.txt");
        if (settings_file.exists()) { //if file found, use it for settings arrays
            BufferedReader settings_reader = new BufferedReader(new FileReader(settings_file));
            //read settings into local arrays
            while (settings_reader.ready()) {
                String line = settings_reader.readLine();
                String temp[] = line.split(":");
                function_labels_default.put(Integer.parseInt(temp[1]), temp[0]); //put funcs and labels into global default
            }
            settings_reader.close();
        } else { //hard-code some buttons and default the rest
            function_labels_default.put(0, "Light");
            function_labels_default.put(1, "Bell");
            function_labels_default.put(2, "Horn");
            for (int k = 3; k <= 28; k++) {
                function_labels_default.put(k, Integer.toString(k)); //String.format("%d",k));
            }
        }
    } catch (IOException except) {
        Log.e("settings_activity", "Could not read file " + except.getMessage());
    }
}

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 .  j  a  v a  2 s . co  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:com.pironet.tda.TDA.java

private String parseWelcomeURL(InputStream is) {
    BufferedReader br = null;
    String resultString = null;/*from  w w  w .ja v a 2s  .c om*/

    StringBuilder result = new StringBuilder();

    try {
        br = new BufferedReader(new InputStreamReader(is));
        while (br.ready()) {
            result.append(br.readLine());
            result.append('\n');
        }
        resultString = result.toString();
        resultString = resultString.replaceFirst("./important.png",
                TDA.class.getResource("/doc/important.png").toString());
        resultString = resultString.replaceFirst("./logo.png",
                TDA.class.getResource("/doc/logo.png").toString());
        resultString = resultString.replaceFirst("./fileopen.png",
                TDA.class.getResource("/doc/fileopen.png").toString());
        resultString = resultString.replaceFirst("./settings.png",
                TDA.class.getResource("/doc/settings.png").toString());
        resultString = resultString.replaceFirst("./help.png",
                TDA.class.getResource("/doc/help.png").toString());
        resultString = resultString.replaceFirst("<!-- ##tipofday## -->", TipOfDay.getTipOfDay());
        resultString = resultString.replaceFirst("<!-- ##recentlogfiles## -->",
                getAsTable("openlogfile://", PrefManager.get().getRecentFiles()));
        resultString = resultString.replaceFirst("<!-- ##recentsessions## -->",
                getAsTable("opensession://", PrefManager.get().getRecentSessions()));
    } catch (IllegalArgumentException | IOException ex) {
        // hack to prevent crashing of the app because off unparsed replacer.
        ex.printStackTrace();
    } finally {
        try {
            if (br != null) {
                br.close();
                is.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    // remove unparsed replacers.
    resultString = resultString.replaceFirst("<!-- ##tipofday## -->", "");
    resultString = resultString.replaceFirst("<!-- ##recentlogfiles## -->", "");
    resultString = resultString.replaceFirst("<!-- ##recentsessions## -->", "");
    return (resultString);
}