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:org.geoserver.catalog.SLDHandler.java

/**
 * Helper method for finding which style handler/version to use from the actual content.
 *//*from  w  ww  . ja  va  2 s.  com*/
Object[] getVersionAndReader(Object input) throws IOException {
    //need to determine version of sld from actual content
    BufferedReader reader = null;

    if (input instanceof InputStream) {
        reader = RequestUtils.getBufferedXMLReader((InputStream) input, XML_LOOKAHEAD);
    } else {
        reader = RequestUtils.getBufferedXMLReader(toReader(input), XML_LOOKAHEAD);
    }

    if (!reader.ready()) {
        return null;
    }

    String version;
    try {
        //create stream parser
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(false);

        //parse root element
        XmlPullParser parser = factory.newPullParser();
        parser.setInput(reader);
        parser.nextTag();

        version = null;
        for (int i = 0; i < parser.getAttributeCount(); i++) {
            if ("version".equals(parser.getAttributeName(i))) {
                version = parser.getAttributeValue(i);
            }
        }

        parser.setInput(null);
    } catch (XmlPullParserException e) {
        throw (IOException) new IOException("Error parsing content").initCause(e);
    }

    //reset input stream
    reader.reset();

    if (version == null) {
        LOGGER.warning("Could not determine SLD version from content. Assuming 1.0.0");
        version = "1.0.0";
    }

    return new Object[] { new Version(version), reader };
}

From source file:org.owasp.dependencycheck.analyzer.RubyBundleAuditAnalyzer.java

/**
 * Determines if the analyzer can analyze the given file type.
 *
 * @param dependency the dependency to determine if it can analyze
 * @param engine the dependency-check engine
 * @throws AnalysisException thrown if there is an analysis exception.
 *///from  ww w.  ja  v a 2  s  .  c om
@Override
protected void analyzeFileType(Dependency dependency, Engine engine) throws AnalysisException {
    if (needToDisableGemspecAnalyzer) {
        boolean failed = true;
        final String className = RubyGemspecAnalyzer.class.getName();
        for (FileTypeAnalyzer analyzer : engine.getFileTypeAnalyzers()) {
            if (analyzer instanceof RubyBundlerAnalyzer) {
                ((RubyBundlerAnalyzer) analyzer).setEnabled(false);
                LOGGER.info("Disabled " + RubyBundlerAnalyzer.class.getName()
                        + " to avoid noisy duplicate results.");
            } else if (analyzer instanceof RubyGemspecAnalyzer) {
                ((RubyGemspecAnalyzer) analyzer).setEnabled(false);
                LOGGER.info("Disabled " + className + " to avoid noisy duplicate results.");
                failed = false;
            }
        }
        if (failed) {
            LOGGER.warn("Did not find " + className + '.');
        }
        needToDisableGemspecAnalyzer = false;
    }
    final File parentFile = dependency.getActualFile().getParentFile();
    final Process process = launchBundleAudit(parentFile);
    try {
        process.waitFor();
    } catch (InterruptedException ie) {
        throw new AnalysisException("bundle-audit process interrupted", ie);
    }
    BufferedReader rdr = null;
    BufferedReader errReader = null;
    try {
        errReader = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
        while (errReader.ready()) {
            final String error = errReader.readLine();
            LOGGER.warn(error);
        }
        rdr = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
        processBundlerAuditOutput(dependency, engine, rdr);
    } catch (IOException ioe) {
        LOGGER.warn("bundle-audit failure", ioe);
    } finally {
        if (errReader != null) {
            try {
                errReader.close();
            } catch (IOException ioe) {
                LOGGER.warn("bundle-audit close failure", ioe);
            }
        }
        if (null != rdr) {
            try {
                rdr.close();
            } catch (IOException ioe) {
                LOGGER.warn("bundle-audit close failure", ioe);
            }
        }
    }

}

From source file:org.owasp.dependencycheck.analyzer.RubyBundleAuditAnalyzer.java

/**
 * Initialize the analyzer. In this case, extract GrokAssembly.exe to a
 * temporary location.//from   w  w w  . j  a  v a  2 s . c  o  m
 *
 * @throws Exception if anything goes wrong
 */
@Override
public void initializeFileTypeAnalyzer() throws Exception {
    try {
        cvedb = new CveDB();
        cvedb.open();
    } catch (DatabaseException ex) {
        LOGGER.warn("Exception opening the database");
        LOGGER.debug("error", ex);
        setEnabled(false);
        throw ex;
    }
    // Now, need to see if bundle-audit actually runs from this location.
    Process process = null;
    try {
        process = launchBundleAudit(Settings.getTempDirectory());
    } catch (AnalysisException ae) {
        LOGGER.warn("Exception from bundle-audit process: {}. Disabling {}", ae.getCause(), ANALYZER_NAME);
        setEnabled(false);
        cvedb.close();
        cvedb = null;
        throw ae;
    }

    final int exitValue = process.waitFor();
    if (0 == exitValue) {
        LOGGER.warn("Unexpected exit code from bundle-audit process. Disabling {}: {}", ANALYZER_NAME,
                exitValue);
        setEnabled(false);
        throw new AnalysisException("Unexpected exit code from bundle-audit process.");
    } else {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
            if (!reader.ready()) {
                LOGGER.warn("Bundle-audit error stream unexpectedly not ready. Disabling " + ANALYZER_NAME);
                setEnabled(false);
                throw new AnalysisException("Bundle-audit error stream unexpectedly not ready.");
            } else {
                final String line = reader.readLine();
                if (line == null || !line.contains("Errno::ENOENT")) {
                    LOGGER.warn("Unexpected bundle-audit output. Disabling {}: {}", ANALYZER_NAME, line);
                    setEnabled(false);
                    throw new AnalysisException("Unexpected bundle-audit output.");
                }
            }
        } finally {
            if (null != reader) {
                reader.close();
            }
        }
    }

    if (isEnabled()) {
        LOGGER.info(ANALYZER_NAME + " is enabled. It is necessary to manually run \"bundle-audit update\" "
                + "occasionally to keep its database up to date.");
    }
}

From source file:ci6226.eval_index_writer.java

public eval_index_writer(Analyzer _analyzer, String _iReviewLocation, String _dir) throws IOException {
    String file = _iReviewLocation;
    JSONParser parser = new JSONParser();
    BufferedReader in = new BufferedReader(new FileReader(file));
    Date start = new Date();
    String indexPath = "./" + _dir;
    System.out.println("Indexing to directory '" + indexPath + "'...");
    Analyzer analyzer = _analyzer;/*from   w ww .  j a  v  a 2  s .c  o  m*/
    IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_47, analyzer);
    Directory dir = FSDirectory.open(new File(indexPath));
    iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
    IndexWriter writer = new IndexWriter(dir, iwc);
    //  int line=0;
    while (in.ready()) {
        String s = in.readLine();
        Object obj = JSONValue.parse(s);
        JSONObject person = (JSONObject) obj;
        String text = (String) person.get("text");
        String user_id = (String) person.get("user_id");
        String business_id = (String) person.get("business_id");
        String review_id = (String) person.get("review_id");
        JSONObject votes = (JSONObject) person.get("votes");
        long funny = (Long) votes.get("funny");
        long cool = (Long) votes.get("cool");
        long useful = (Long) votes.get("useful");
        Document doc = new Document();
        Field review_idf = new StringField("review_id", review_id, Field.Store.YES);
        doc.add(review_idf);
        //    Field business_idf = new StringField("business_id", business_id, Field.Store.YES);
        //     doc.add(business_idf);

        //http://qindongliang1922.iteye.com/blog/2030639
        FieldType ft = new FieldType();
        ft.setIndexed(true);//
        ft.setStored(true);//
        ft.setStoreTermVectors(true);
        ft.setTokenized(true);
        ft.setStoreTermVectorPositions(true);//
        ft.setStoreTermVectorOffsets(true);//

        Field textf = new Field("text", text, ft);

        doc.add(textf);
        //    Field user_idf = new StringField("user_id", user_id, Field.Store.YES);
        //     doc.add(user_idf);
        //      doc.add(new LongField("cool", cool, Field.Store.YES));
        //      doc.add(new LongField("funny", funny, Field.Store.YES));
        //       doc.add(new LongField("useful", useful, Field.Store.YES));

        writer.addDocument(doc);

        //  System.out.println(line++);
    }

    writer.close();
    Date end = new Date();
    System.out.println(end.getTime() - start.getTime() + " total milliseconds");
}

From source file:com.thejustdo.servlet.CargaMasivaServlet.java

/**
 * Given a stream containing the file to process, it builds all the info
 * related to the beneficiaries for dream boxes
 *
 * @param fi Contains the info related to the file to be processed. <br />
 * <strong>File structure</strong> <ul> <li>0: Identification number.</li>
 * <li>1: Identification type.</li> <li>2: Age.</li> <li>3: Given
 * box.</li> <li>4: Last name.</li> <li>5: Second last name.</li> </ul>
 * @return The list of beneficiaries.//from w  ww .  ja va 2s . c o  m
 */
private List<Beneficiary> processFile(FileItem fi) throws IOException {
    List<Beneficiary> answer = new ArrayList<Beneficiary>();

    // 1. Getting the input stream with the file.
    InputStream stream = fi.getInputStream();
    InputStreamReader isr = new InputStreamReader(stream, "ISO-8859-1");
    BufferedReader reader = new BufferedReader(isr);

    // 2. Parsing line by line.
    String line;
    String parts[];
    Beneficiary b;
    while (reader.ready()) {
        line = reader.readLine();
        // Building the beneficiaries.
        if ((line == null) || ("".equalsIgnoreCase(line.trim()))) {
            continue;
        }

        // 2.1 Spliting parts.
        log.info(String.format("Found line: %s", line));
        parts = line.split(",");
        // 2.2 Building the new elemento of response.
        b = new Beneficiary();
        //b.setIdNumber(Long.parseLong(parts[0]));
        //b.setDocumentType(parts[1]);
        //b.setAge(Integer.parseInt(parts[2]));
        b.setGivenNames(parts[0]);
        b.setLastName(parts[1]);
        //b.setSecondLastName(parts[2]);

        // 2.3 Adding the element to the answer.
        answer.add(b);
    }

    // n. Clossing the stream.
    stream.close();

    return answer;
}

From source file:de.gesundkrank.wikipedia.hadoop.parser.Parser.java

private boolean readContributor(String line, BufferedReader in) throws IOException {
    if (!foundContributor && matchContributor(line)) {
        foundContributor = true;/*from w  w  w. j a  v  a  2  s .  c  o m*/

        WikiRevisionContributor contributor = new WikiRevisionContributor();

        boolean foundUsername = false;
        boolean foundContributorId = false;

        while (in.ready()) {
            line = in.readLine();

            if (!foundUsername) {
                String username = matchUsername(line);
                if (username != null) {
                    contributor.setUsername(username);
                    foundUsername = true;
                    continue;
                }
            }

            if (!foundContributorId) {
                long id = matchId(line);
                if (id != -1) {
                    contributor.setId(id);
                    foundContributorId = true;
                    continue;
                }
            }

            if (matchContributorEnd(line)) {
                break;
            }
        }
        revision.setContributor(contributor);
        return true;
    }
    return false;
}

From source file:org.opennms.systemreport.AbstractSystemReportPlugin.java

protected String slurpCommand(final String[] command) {
    Process p = null;/*from  w w w  .  ja v a 2s .  c om*/
    InputStream is = null;
    InputStreamReader isr = null;
    BufferedReader br = null;

    StringBuffer sb = new StringBuffer();
    try {
        p = Runtime.getRuntime().exec(command);
        is = p.getInputStream();
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);
        while (br.ready()) {
            final String line = br.readLine();
            if (line == null)
                break;
            sb.append(line);
            if (br.ready())
                sb.append("\n");
        }
    } catch (final Throwable e) {
        LOG.debug("Failure attempting to run command '{}'", Arrays.asList(command), e);
    } finally {
        IOUtils.closeQuietly(br);
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(is);
    }

    return sb.toString();
}

From source file:de.indiplex.javapt.JavAPT.java

public void updateSources(boolean downloadSs) throws URISyntaxException, IOException, SQLException {
    Statement stat = db.getStat();
    stat.executeUpdate("DELETE FROM packages;");
    debs = new ArrayList<DEB>();
    int last = 0;
    for (String u : sourcesURLs) {
        String pre = new URL(u).getHost();
        File out = new File(dTemp, pre + ".source");
        if (downloadSs) {
            URLConnection con = new URL(u.toString() + "Packages.bz2").openConnection();
            File tmpOut = new File(dTemp, pre + ".source.bz2");

            System.out.println("Downloading " + con.getURL() + "...");

            download(con, tmpOut);/*  www. j  a v a2 s. co  m*/

            System.out.println("Decompressing...");
            CountingFileInputStream fis = new CountingFileInputStream(tmpOut);
            BZip2CompressorInputStream in = new BZip2CompressorInputStream(fis);
            Finish = tmpOut.length();

            Util.checkFiles(out);
            OutputStream fout = new FileOutputStream(out);
            int i = in.read();
            while (i != -1) {
                State = fis.getCount();
                fout.write(i);
                i = in.read();
            }
            fout.close();

            in.close();
        }

        BufferedReader br = new BufferedReader(new FileReader(out));
        DEB deb = null;
        ArrayList<String> lines = new ArrayList<String>();
        while (br.ready()) {
            String line = br.readLine();
            lines.add(line);
        }
        Finish = lines.size();
        State = 0;
        System.out.println("Parsing...");
        for (String line : lines) {
            State++;
            if (line.startsWith("Package")) {
                if (deb != null) {
                    debs.add(deb);
                }
                deb = new DEB(p(line));
            }
            if (line.startsWith("Depends")) {
                if (deb == null) {
                    continue;
                }
                deb.depends = p(line).trim();
                deb.depends = deb.depends.replaceAll("\\({1}[^\\(]*\\)", "");
            }
            if (line.startsWith("Provides")) {
                if (deb == null) {
                    continue;
                }
                deb.provides = p(line);
            }
            if (line.startsWith("Filename")) {
                if (deb == null) {
                    continue;
                }
                deb.filename = u + p(line);
                if (u.equals("http://apt.saurik.com/dists/ios/675.00/main/binary-iphoneos-arm/")) {
                    deb.filename = "http://apt.saurik.com/" + p(line);
                }
                if (u.contains("apt.thebigboss")) {
                    deb.filename = deb.filename.replace("dists/stable/main/binary-iphoneos-arm/", "");
                }
                deb.filename = deb.filename.replace("http://", "");
                deb.filename = deb.filename.replace("//", "/");
                deb.filename = "http://" + deb.filename;
            }
        }
        System.out.println("Updated " + u + "! " + (debs.size() - last) + " packages found");
        last = debs.size();
    }
    PreparedStatement pstat = db
            .getPreparedStatement("INSERT INTO packages (name, depends, provides, filename) VALUES (?,?,?,?);");
    for (DEB deb : debs) {
        pstat.setString(1, deb.packagename);
        pstat.setString(2, deb.depends);
        pstat.setString(3, deb.provides);
        pstat.setString(4, deb.filename);
        pstat.addBatch();
    }
    db.closePS();
    if (isGUI()) {
        mf.fillPackages(debs);
    }
    hashDEB();
}

From source file:org.talend.dataprofiler.core.migration.impl.MergeMetadataTask.java

/**
 * DOC Use replace method to migrate from 400 to 410.
 * // w  w w.  j  a  v a2  s  .c om
 * @param result
 * @param migFolder
 * @param acceptFileExtentionNames
 * @param replaceStringMap
 * @return
 */
private boolean migrateFolder(File migFolder, final String[] acceptFileExtentionNames,
        Map<String, String> replaceStringMap) {

    ArrayList<File> fileList = new ArrayList<File>();
    getAllFilesFromFolder(migFolder, fileList, new FilenameFilter() {

        public boolean accept(File dir, String name) {
            for (String extName : acceptFileExtentionNames) {
                if (name.endsWith(extName)) {
                    return true;
                }
            }
            return false;
        }
    });
    log.info("-------------- Migrating " + fileList.size() + " files"); //$NON-NLS-1$ //$NON-NLS-2$

    int counter = 0;
    int errorCounter = 0;
    Throwable error = null;

    for (File sample : fileList) {
        log.info("-------------- Migrating (" + counter++ + ") : " + sample.getAbsolutePath()); //$NON-NLS-1$ //$NON-NLS-2$
        try {
            BufferedReader fileReader = new BufferedReader(new FileReader(sample));
            BufferedWriter fileWriter = new BufferedWriter(
                    new FileWriter(new File(sample.getAbsolutePath() + MIGRATION_FILE_EXT)));

            while (fileReader.ready()) {
                String line = fileReader.readLine();
                for (String key : replaceStringMap.keySet()) {
                    line = line.replaceAll(key, replaceStringMap.get(key));
                }
                fileWriter.append(line);
                fileWriter.newLine();
            }

            fileWriter.flush();
            fileWriter.close();
            fileWriter = null;
            fileReader.close();
            fileReader = null;
            // We must show called garbage collection,if set fileReader and fileWriter,then don't clear memory,will
            // warn a
            // message is file is in using.
            System.gc();
        } catch (Exception e) {
            error = e;
            errorCounter++;
            log.error("!!!!!!!!!!!  Error transforming (" + sample.getAbsolutePath() + ")\n" + e.getMessage(), //$NON-NLS-1$//$NON-NLS-2$
                    e);
        }
        log.info("-------------- Migration done of " + counter + " files" //$NON-NLS-1$ //$NON-NLS-2$
                + (errorCounter != 0 ? (",  there are " + errorCounter + " files in error.") : ".")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    }

    if (error != null) {
        return false;
    } else {
        // remove original files and rename new ones to old ones
        for (File sample : fileList) {
            boolean isDeleted = sample.delete();
            log.info(sample.getAbsolutePath() + (isDeleted ? " is deleted." : " failed to delete.")); //$NON-NLS-1$ //$NON-NLS-2$
            boolean isrenamed = new File(sample.getAbsolutePath() + MIGRATION_FILE_EXT).renameTo(sample);
            log.info(sample.getAbsolutePath() + MIGRATION_FILE_EXT
                    + (isrenamed ? " is renamed." : " failed to rename.")); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }

    return true;
}

From source file:com.symbian.driver.plugins.reboot.Activator.java

/**
 * @param switchState//from   w  w  w  .  java 2s .  c o m
 * @throws IOException
 */
private synchronized void switchOp(String switchState) throws IOException {
    LOGGER.log(Level.INFO, "Activator::switchOp");

    // Alternative being "TelnetSwitch"
    if (method.compareToIgnoreCase("PortTalk") == 0)// ATX power
    {
        String state = switchState == "2" ? "OFF" : "ON";
        File hardwareSwitchFile = JarUtils.extractResource(Activator.class, "/resource/HardwareSwitch.exe");
        if (hardwareSwitchFile.isFile()) {
            Process p = Runtime.getRuntime()
                    .exec("cmd.exe /c " + hardwareSwitchFile.getAbsolutePath() + " " + state);
            BufferedReader iBufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String lOutput = null;
            StringBuffer iOutputBuffer = new StringBuffer();
            while ((lOutput = iBufferedReader.readLine()) != null) {
                lOutput += System.getProperty("line.separator");
                iOutputBuffer.append(lOutput);
                // Parse for errors and redirect to appropriate buffer.
            }
            LOGGER.info(iOutputBuffer.toString());
        } else {
            LOGGER.warning(hardwareSwitchFile.getAbsolutePath() + " was not found");
        }
    } else {

        String responseLine = "";
        String[] states = { "User Name :", "Password  :", "Control Console", "Device Manager",
                "Outlet Management", "Outlet Control/Configuration", "Outlet " + outletNo, "Control Outlet",
                "Immediate Off", "Press <ENTER> to continue..." };

        String[] answers = { userName, password, "1", "2", "1", outletNo, "1", switchState, "YES", "\n" };

        Socket sock = new Socket(hostAddr, 23);
        PrintWriter dataToTelnetServer = new PrintWriter(sock.getOutputStream(), true);
        BufferedReader dataFromTelnetServer = new BufferedReader(new InputStreamReader(sock.getInputStream()));
        // start the state machine...
        int state = 0;
        long lastStateChng = System.currentTimeMillis();
        while (state < states.length) {
            while (dataFromTelnetServer.ready()) {
                char nextChar = (char) dataFromTelnetServer.read();
                responseLine += nextChar;
            }
            LOGGER.log(Level.FINE, responseLine);
            if (responseLine.contains(states[state])) // sort of on
            {

                LOGGER.log(Level.FINE, "answers[" + state + "]:" + answers[state]);
                dataToTelnetServer.println(answers[state]);
                state++;
                lastStateChng = System.currentTimeMillis();
                continue;
            }
            if ((System.currentTimeMillis() - lastStateChng) > 10000) {
                // too much time since last change of state...
                // we have lost the connection...
                LOGGER.log(Level.SEVERE, "Lost telnet connection");
                break;
            }
        }
        responseLine = "";
        dataToTelnetServer.flush();
        dataToTelnetServer.close();
        dataFromTelnetServer.close();
        sock.close();
    }
}