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.apache.pdfbox.pdmodel.font.encoding.GlyphList.java

private void loadList(InputStream input) throws IOException {
    BufferedReader in = new BufferedReader(new InputStreamReader(input, "ISO-8859-1"));
    try {//from w  w  w.ja  v a  2 s  . c o  m
        while (in.ready()) {
            String line = in.readLine();
            if (line != null && !line.startsWith("#")) {
                String[] parts = line.split(";");
                if (parts.length < 2) {
                    throw new IOException("Invalid glyph list entry: " + line);
                }

                String name = parts[0];
                String[] unicodeList = parts[1].split(" ");

                if (nameToUnicode.containsKey(name)) {
                    LOG.warn("duplicate value for " + name + " -> " + parts[1] + " " + nameToUnicode.get(name));
                }

                int[] codePoints = new int[unicodeList.length];
                int index = 0;
                for (String hex : unicodeList) {
                    codePoints[index++] = Integer.parseInt(hex, 16);
                }
                String string = new String(codePoints, 0, codePoints.length);

                // forward mapping
                nameToUnicode.put(name, string);

                // reverse mapping
                if (!unicodeToName.containsKey(string)) {
                    unicodeToName.put(string, name);
                }
            }
        }
    } finally {
        in.close();
    }
}

From source file:org.folg.places.tools.AnalyzePlaces.java

private void doMain() throws SAXParseException, IOException {

    Normalizer normalizer = null;
    if (useTokenizer) {
        normalizer = Normalizer.getInstance();
    }/*from  w ww . j  ava 2  s .co m*/

    PrintWriter reversedWordsWriter = analysisPlacesOut != null
            ? new PrintWriter(new File(analysisPlacesOut, "reversedWords.txt"))
            : new PrintWriter(System.out);

    BufferedReader bufferedReader = new BufferedReader(new FileReader(placesIn));

    int lineCount = 0;
    while (bufferedReader.ready()) {
        String nextLine = bufferedReader.readLine();
        nextLine = nextLine.trim().toLowerCase();
        if (nextLine.length() == 0)
            continue;

        lineCount++;
        if (lineCount % 5000 == 0)
            System.out.println("indexing line " + lineCount);

        placesCountCC.add(nextLine);
        totalPlacesCount++;

        String[] placeList = nextLine.split(SPLIT_REGEX);

        for (String place : placeList) {
            place = place.trim();

            if (place.length() == 0)
                continue;

            if (NumberUtils.isNumber(place)) {
                numbersCountCC.add(place);
                totalNumbersCount++;
            } else {
                wordsCountCC.add(place);
                totalWordsCount++;
            }
        }

        int lastCommaIndx = nextLine.lastIndexOf(",");
        String lastWord = nextLine.substring(lastCommaIndx + 1).trim();
        if (lastWord.length() > 0) {
            endingsOfPlacesCC.add(lastWord);
            endingsOfPlacesTotalCount++;
        }

        if (lineCount % REVERSE_EVERY_N == 0) {
            StringBuilder reversedWord = new StringBuilder(nextLine);
            reversedWordsWriter.println(reversedWord.reverse());
        }

        if ((useTokenizer) && (lineCount % TOKENIZE_EVERY_N == 0)) {
            List<List<String>> levels = normalizer.tokenize(nextLine);
            for (List<String> levelWords : levels) {
                tokenizerPlacesCountCC.addAll(levelWords);
                totalTokenizerPlacesCount += levelWords.size();
            }
        }
    }

    System.out.println("total number of lines in files " + lineCount);

    System.out.println("Indexed a total of " + totalPlacesCount + " places.");
    System.out.println("Found a total of " + getPlacesCountCC().size() + " unique places.");
    getPlacesCountCC().writeSorted(false, 1,
            analysisPlacesOut != null ? new PrintWriter(new File(analysisPlacesOut, "placesCount.txt"))
                    : new PrintWriter(System.out));

    System.out.println("Indexed a total of " + totalWordsCount + " words.");
    System.out.println("Found a total of " + getWordsCountCC().size() + " unique words.");
    getWordsCountCC().writeSorted(false, 1,
            analysisPlacesOut != null ? new PrintWriter(new File(analysisPlacesOut, "wordsCount.txt"))
                    : new PrintWriter(System.out));

    System.out.println("Indexed a total of " + totalNumbersCount + " numbers.");
    System.out.println("Found a total of " + getNumbersCountCC().size() + " unique numbers.");
    getNumbersCountCC().writeSorted(false, 1,
            analysisPlacesOut != null ? new PrintWriter(new File(analysisPlacesOut, "numbersCount.txt"))
                    : new PrintWriter(System.out));

    System.out.println("Indexed a total of " + endingsOfPlacesTotalCount + " endings.");
    System.out.println("Found a total of " + getEndingsOfPlacesCC().size() + " unique endings.");
    getEndingsOfPlacesCC().writeSorted(false, 1,
            analysisPlacesOut != null ? new PrintWriter(new File(analysisPlacesOut, "endingsCount.txt"))
                    : new PrintWriter(System.out));

    if (useTokenizer) {
        System.out.println("Indexed a total of " + totalTokenizerPlacesCount + " normalized words.");
        System.out.println("Found a total of " + getTokenizerPlacesCountCC().size() + " normalized words.");
        getTokenizerPlacesCountCC().writeSorted(false, 1,
                analysisPlacesOut != null
                        ? new PrintWriter(new File(analysisPlacesOut, "normalizedWordsCount.txt"))
                        : new PrintWriter(System.out));
    }

}

From source file:de.erdesignerng.test.sql.AbstractReverseEngineeringTestImpl.java

protected void loadSQL(Connection aConnection, String aResource) throws IOException, SQLException {
    BufferedReader theReader = new BufferedReader(
            new InputStreamReader(getClass().getResourceAsStream(aResource)));
    Statement theStatement = aConnection.createStatement();
    while (theReader.ready()) {
        String theLine = theReader.readLine();
        if (StringUtils.isNotEmpty(theLine)) {
            theLine = theLine.trim();/* w ww. j a v  a  2  s  .  co  m*/
        }
        if (StringUtils.isNotEmpty(theLine)) {
            System.out.println(theLine);
            theStatement.execute(theLine);
        }
    }
    theStatement.close();

    theReader.close();
}

From source file:org.springframework.social.betaseries.api.impl.BetaSerieErrorHandler.java

/**
 * Read fully./*  ww w .ja  v  a2s  .  c om*/
 * 
 * @param in
 *            the in
 * @return the string
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private String readFully(InputStream in) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder sb = new StringBuilder();
    while (reader.ready()) {
        sb.append(reader.readLine());
    }
    return sb.toString();
}

From source file:org.wso2.carbon.registry.core.utils.MediaTypesUtils.java

/**
 * Method to obtain the resource media types.
 *
 * @param configSystemRegistry a configuration system registry instance.
 *
 * @return a String of resource media types, in the format extension:type,extension:type,...
 * @throws RegistryException if the operation failed.
 *//*  ww w .  j  a  v a 2s  . com*/
public static String getResourceMediaTypeMappings(Registry configSystemRegistry) throws RegistryException {

    RegistryContext registryContext = configSystemRegistry.getRegistryContext();

    if (getResourceMediaTypeMappings(registryContext) != null) {
        return getResourceMediaTypeMappings(registryContext);
    }

    Resource resource;
    String mediaTypeString = null;

    String resourcePath = MIME_TYPE_COLLECTION + RegistryConstants.PATH_SEPARATOR + RESOURCE_MIME_TYPE_INDEX;

    if (!configSystemRegistry.resourceExists(resourcePath)) {
        resource = configSystemRegistry.newCollection();
    } else {
        resource = configSystemRegistry.get(resourcePath);
        Properties properties = resource.getProperties();
        if (properties.size() > 0) {
            Set<Object> keySet = properties.keySet();
            for (Object key : keySet) {
                if (key instanceof String) {
                    String ext = (String) key;
                    if (RegistryUtils.isHiddenProperty(ext)) {
                        continue;
                    }
                    String value = resource.getProperty(ext);
                    String mediaTypeMapping = ext + ":" + value;
                    if (mediaTypeString == null) {
                        mediaTypeString = mediaTypeMapping;
                    } else {
                        mediaTypeString = mediaTypeString + "," + mediaTypeMapping;
                    }
                }
            }
        }
        registryContext.setResourceMediaTypes(mediaTypeString);
        return mediaTypeString;
    }

    BufferedReader reader;
    try {
        File mimeFile = getMediaTypesFile();
        reader = new BufferedReader(new InputStreamReader(new FileInputStream(mimeFile)));
    } catch (Exception e) {
        String msg = "Failed to read the the media type definitions file. Only a limited "
                + "set of media type definitions will be populated. ";
        log.error(msg, e);
        mediaTypeString = "txt:text/plain,jpg:image/jpeg,gif:image/gif";
        registryContext.setResourceMediaTypes(mediaTypeString);
        return mediaTypeString;
    }

    try {
        while (reader.ready()) {
            String mediaTypeData = reader.readLine().trim();
            if (mediaTypeData.startsWith("#")) {
                // ignore the comments
                continue;
            }

            if (mediaTypeData.length() == 0) {
                // ignore the blank lines
                continue;
            }

            // mime.type file delimits media types:extensions by tabs. if there is no
            // extension associated with a media type, there are no tabs in the line. so we
            // don't need such lines.
            if (mediaTypeData.indexOf('\t') > 0) {

                String[] parts = mediaTypeData.split("\t+");
                if (parts.length == 2 && parts[0].length() > 0 && parts[1].length() > 0) {

                    // there can multiple extensions associated with a single media type. in
                    // that case, extensions are delimited by a space.
                    String[] extensions = parts[1].trim().split(" ");
                    for (String extension : extensions) {
                        if (extension.length() > 0) {
                            String mediaTypeMapping = extension + ":" + parts[0];
                            resource.setProperty(extension, parts[0]);
                            if (mediaTypeString == null) {
                                mediaTypeString = mediaTypeMapping;
                            } else {
                                mediaTypeString = mediaTypeString + "," + mediaTypeMapping;
                            }
                        }
                    }
                }
            }
        }
        resource.setDescription("This collection contains the media Types available for "
                + "resources on the Registry. Add, Edit or Delete properties to Manage Media " + "Types.");
        Resource collection = configSystemRegistry.newCollection();
        collection.setDescription("This collection lists the media types available on the "
                + "Registry Server. Before changing an existing media type, please make sure "
                + "to alter existing resources/collections and related configuration details.");
        configSystemRegistry.put(MIME_TYPE_COLLECTION, collection);
        configSystemRegistry.put(resourcePath, resource);

    } catch (IOException e) {
        String msg = "Could not read the media type mappings file from the location: ";
        throw new RegistryException(msg, e);

    } finally {
        try {
            reader.close();
        } catch (IOException ignore) {
        }
    }
    registryContext.setResourceMediaTypes(mediaTypeString);
    return mediaTypeString;
}

From source file:org.apache.streams.instagram.test.data.InstagramMediaFeedDataConverterIT.java

@Test
public void InstagramMediaFeedDataConverterITCase() throws Exception {
    InputStream is = InstagramMediaFeedDataConverterIT.class.getResourceAsStream("/testMediaFeedObjects.txt");
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    PrintStream outStream = new PrintStream(new BufferedOutputStream(
            new FileOutputStream("target/test-classes/InstagramMediaFeedDataConverterITCase.txt")));

    try {//  www .  j a  v a 2  s  . co m
        while (br.ready()) {
            String line = br.readLine();
            if (!StringUtils.isEmpty(line)) {
                LOGGER.info("raw: {}", line);

                MediaFeedData mediaFeedData = gson.fromJson(line, MediaFeedData.class);

                ActivityConverter<MediaFeedData> converter = new InstagramMediaFeedDataConverter();

                Activity activity = converter.toActivityList(mediaFeedData).get(0);

                LOGGER.info("activity: {}", activity.toString());

                assertThat(activity, is(not(nullValue())));

                assertThat(activity.getId(), is(not(nullValue())));
                assertThat(activity.getActor(), is(not(nullValue())));
                assertThat(activity.getActor().getId(), is(not(nullValue())));
                assertThat(activity.getVerb(), is(not(nullValue())));
                assertThat(activity.getProvider(), is(not(nullValue())));

                outStream.println(mapper.writeValueAsString(activity));

            }

        }
        outStream.flush();

    } catch (Exception ex) {
        LOGGER.error("Exception: ", ex);
        outStream.flush();
        Assert.fail();
    }
}

From source file:me.crime.loader.DataBaseLoader.java

public void loadURCTable() throws SQLException, ClassNotFoundException {
    URCCatagoriesDAO dao = URCCatagoriesDAO.class
            .cast(DaoBeanFactory.create().getDaoBean(URCCatagoriesDAO.class));

    // Read in the URC Codes.
    InputStream s = ClassLoader.getSystemResourceAsStream("me/crime/loader/CrimeData.txt");
    if (s == null) {
        log_.error("unable to find me/crime/loader/CrimeData.txt");
    } else {//  w  ww. j a v a  2s.  c  o  m

        try {
            BufferedReader bf = new BufferedReader(new InputStreamReader(s));

            while (bf.ready()) {
                String word = bf.readLine().trim().toUpperCase();
                if (!word.startsWith("#")) {
                    if (word.length() > 0) {
                        String[] info = word.split(",");
                        URCCatagories urc = dao.findURCbyCatagory(info[0]);
                        if (urc == null) {

                            urc = new URCCatagories();

                            int rank = Integer.parseInt(info[1].trim());

                            if (rank == 1) {
                                urc.setCatagorie(info[0].trim());
                                urc.setCrimeGroup(info[3].trim());
                                dao.save(urc);
                            }
                        }
                    }
                }

            }
            bf.close();

        } catch (IOException e) {
            log_.error(e.getLocalizedMessage(), e);
        }

    }

}

From source file:org.wso2.am.integration.ui.tests.APIMANAGER3272ExternalLogoutPageTestCase.java

private boolean editStoreConfig(String externalLogoutPage) {
    String serverRoot = System.getProperty(ServerConstants.CARBON_HOME);
    String deploymentPath = serverRoot + getStoreSiteConfPath();
    File file = new File(deploymentPath);
    StringBuilder content = new StringBuilder();
    try {//w  w w. ja v a 2 s.c o  m
        if (file.exists()) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(file), "UTF-8"));
            try {
                while (reader.ready()) {
                    content.append(reader.readLine() + "\r\n");
                }
            } finally {
                reader.close();
            }

            int ssoConfigIndex = content.indexOf("ssoConfiguration");

            if (ssoConfigIndex > -1) {
                String ssoConfigElement = content.substring(ssoConfigIndex);
                log.debug("SSO Configuration before editing : " + ssoConfigElement);
                int originalLength = ssoConfigElement.length();
                ssoConfigElement = ssoConfigElement
                        .replaceFirst("\"enabled\" : \"false\"", "\"enabled\" : \"true\"")
                        .replaceAll("\"keyStorePassword\" : \"[a-zA-Z0-9]*\"", "\"keyStorePassword\" : \"\"");
                ssoConfigElement.concat("\"externalLogoutPage\" : " + externalLogoutPage);
                content.replace(ssoConfigIndex, originalLength, ssoConfigElement);
                String jsonConfig = content.toString();
                log.debug("SSO Configuration after editing : " + jsonConfig);

                OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
                try {
                    writer.write(jsonConfig);
                } finally {
                    writer.close();
                }
                return true;
            }
        }

    } catch (IOException ex) {
        log.error("Exception occurred while file reading or writing " + ex);
    }

    return false;
}

From source file:org.opencms.workplace.tools.sites.CmsSitesWebserverThread.java

/**
 * Executes the webserver script.<p>
 *
 * @throws IOException if something goes wrong
 * @throws InterruptedException if something goes wrong
 *//*from   www  . j av a2s . c  o  m*/
private void executeScript() throws IOException, InterruptedException {

    File script = new File(m_scriptPath);
    List<String> params = new LinkedList<String>();
    params.add(script.getAbsolutePath());
    params.addAll(m_writtenFiles);
    ProcessBuilder pb = new ProcessBuilder(params.toArray(new String[params.size()]));
    pb.directory(new File(script.getParent()));
    Process pr = pb.start();
    pr.waitFor();
    BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    while (buf.ready()) {
        String line = buf.readLine();
        if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(line)) {
            getReport().println(Messages.get().container(Messages.RPT_OUTPUT_WEBSERVER_1, buf.readLine()),
                    I_CmsReport.FORMAT_OK);
        }
    }
}

From source file:org.kalypso.kalypsomodel1d2d.sim.SwanResultProcessor.java

private void processSWANTabFile(final FileObject swanResOutTabFile, final FileObject swanResShiftFile) {
    final GM_Position lShiftPosition = SWANDataConverterHelper.readCoordinateShiftValues(swanResShiftFile);
    if (lShiftPosition == null)
        return;/*w w  w. j  a  v  a 2  s .  c  o m*/

    try {
        // FIXME: why?! should never happen...!
        if (swanResOutTabFile.isContentOpen())
            swanResOutTabFile.close();

        final FileObject swanResOutTabFileBackUp = swanResOutTabFile.getParent()
                .resolveFile(swanResOutTabFile.getName().getBaseName() + ".bck"); //$NON-NLS-1$
        swanResOutTabFile.moveTo(swanResOutTabFileBackUp);

        final OutputStream lOutStream = swanResOutTabFile.getContent().getOutputStream();
        final Formatter lFormatter = new Formatter(lOutStream, Charset.defaultCharset().name(), Locale.US);

        final BufferedReader lInDataStream = new BufferedReader(
                new InputStreamReader(swanResOutTabFileBackUp.getContent().getInputStream()));

        while (lInDataStream.ready()) {
            final String lStrTmpLine = lInDataStream.readLine().trim();
            if (lStrTmpLine.startsWith("%")) //$NON-NLS-1$
            {
                lFormatter.format("%s\n", lStrTmpLine); //$NON-NLS-1$
                continue;
            }

            final StringTokenizer lStrTokenizer = new StringTokenizer(lStrTmpLine, " "); //$NON-NLS-1$
            int lIntTokenCounter = 0;
            String lStrNewLine = ""; //$NON-NLS-1$
            while (lStrTokenizer.hasMoreTokens()) {
                final String lStrToken = lStrTokenizer.nextToken();
                if (lIntTokenCounter == 1) {
                    lStrNewLine += String.format(Locale.US, "%.5f\t", //$NON-NLS-1$
                            NumberUtils.parseQuietDouble(lStrToken) + lShiftPosition.getX());
                } else if (lIntTokenCounter == 2) {
                    lStrNewLine += String.format(Locale.US, "%.5f\t", //$NON-NLS-1$
                            NumberUtils.parseQuietDouble(lStrToken) + lShiftPosition.getY());
                } else {
                    lStrNewLine += lStrToken + "\t"; //$NON-NLS-1$
                }
                lIntTokenCounter++;
            }
            lFormatter.format("%s\n", lStrNewLine); //$NON-NLS-1$
        }

        // FIXME: not closed in a save way!
        lFormatter.close();
        lInDataStream.close();
        lOutStream.close();
    } catch (final Exception e) {
        // FIXME: this is no way to handle an error !
    }
}