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:de.unijena.bioinf.ChemistryBase.chem.utils.IsotopicDistributionJSONFile.java

public IsotopicDistribution read(Reader json) throws IOException {
    final IsotopicDistribution dist = new IsotopicDistribution(PeriodicTable.getInstance());
    final BufferedReader reader = new BufferedReader(json);
    final StringBuilder buffer = new StringBuilder();
    while (reader.ready()) {
        buffer.append(reader.readLine()).append("\n");
    }/*from   w ww . ja  v a 2s. c o  m*/
    JSONObject obj;
    try {
        obj = new JSONObject(buffer.toString());
        for (Iterator<?> keys = obj.keys(); keys.hasNext();) {
            final String key = keys.next().toString();
            final Isotopes prev = PeriodicTable.getInstance().getDistribution().getIsotopesFor(key);
            //final JSONObject element = (JSONObject)obj.get(key);
            //final JSONArray jmasses = (JSONArray)obj.get("masses");
            final JSONArray jabundances = (JSONArray) obj.get(key);
            final String elementSymbol = key;
            final double[] abundances = new double[jabundances.length()];
            final double[] masses = new double[jabundances.length()];
            for (int i = 0; i < prev.getNumberOfIsotopes(); ++i) { // TODO: fix!!!
                abundances[i] = jabundances.getDouble(i);
                masses[i] = prev.getMass(i);
            }
            dist.addIsotope(key, masses, abundances);
        }
    } catch (JSONException e) {
        throw new IOException("Can't parse json file. Invalid JSON syntax");
    }
    return dist;
}

From source file:zack.yovel.clear.controller.foreground.HelpFragment.java

private String getHelpHtmlString() throws IOException {
    InputStream inputStream = getActivity().getResources().openRawResource(R.raw.help);
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    String helpHtmlString = "";
    while (reader.ready()) {
        helpHtmlString += reader.readLine();
    }/*from  w  ww  . j  a  v  a 2  s.com*/
    return helpHtmlString;
}

From source file:org.apache.streams.gplus.processors.GooglePlusTypeConverterIT.java

@Test(dependsOnGroups = { "testGPlusUserDataProvider" })
public void testProcessPerson() throws IOException, ActivitySerializerException {

    File file = new File("target/test-classes/GPlusUserDataProviderIT.stdout.txt");
    InputStream is = new FileInputStream(file);
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    while (br.ready()) {
        String line = br.readLine();
        if (!StringUtils.isEmpty(line)) {
            LOGGER.info("raw: {}", line);
            Activity activity = new Activity();

            Person person = objectMapper.readValue(line, Person.class);
            StreamsDatum streamsDatum = new StreamsDatum(person);

            assertNotNull(streamsDatum.getDocument());

            List<StreamsDatum> retList = googlePlusTypeConverter.process(streamsDatum);
            GooglePlusActivityUtil.updateActivity(person, activity);

            assertEquals(retList.size(), 1);
            assert (retList.get(0).getDocument() instanceof Activity);
            assertEquals(activity, retList.get(0).getDocument());
        }/*from ww w  .  ja  va  2  s. com*/
    }
}

From source file:org.apache.streams.gplus.processors.GooglePlusTypeConverterIT.java

@Test(dependsOnGroups = { "testGPlusUserActivityProvider" })
public void testProcessActivity() throws IOException, ActivitySerializerException {

    File file = new File("target/test-classes/GPlusUserActivityProviderIT.stdout.txt");
    InputStream is = new FileInputStream(file);
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    while (br.ready()) {
        String line = br.readLine();
        if (!StringUtils.isEmpty(line)) {
            LOGGER.info("raw: {}", line);
            Activity activity = new Activity();

            com.google.api.services.plus.model.Activity gPlusActivity = objectMapper.readValue(line,
                    com.google.api.services.plus.model.Activity.class);
            StreamsDatum streamsDatum = new StreamsDatum(gPlusActivity);

            assertNotNull(streamsDatum.getDocument());

            List<StreamsDatum> retList = googlePlusTypeConverter.process(streamsDatum);
            GooglePlusActivityUtil.updateActivity(gPlusActivity, activity);

            assertEquals(retList.size(), 1);
            assertTrue(retList.get(0).getDocument() instanceof Activity);
            assertEquals(activity, retList.get(0).getDocument());
        }/*from  w w  w.j  a v a 2  s  . c  o m*/
    }
}

From source file:com.google.testing.testify.risk.frontend.server.api.impl.UploadApiImpl.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    BufferedReader reader = req.getReader();
    StringBuilder input = new StringBuilder();
    while (reader.ready()) {
        input.append(req.getReader().readLine());
    }/*from w ww. ja  v  a2 s . c  om*/
    LOG.info("Input received: " + input.toString());
    JSONArray json;
    try {
        json = new JSONArray(input.toString());
    } catch (JSONException e) {
        LOG.warning("Couldn't parse JSON: " + e.toString());
        error(resp, "Malformed JSON could not be parsed: " + e.toString());
        return;
    }
    LOG.info("JSON received: " + json.toString());
    JSONObject o;
    TaskOptions task;
    String email = userService.getEmail();
    for (int i = 0; i < json.length(); i++) {
        try {
            o = json.getJSONObject(i);
            task = TaskOptions.Builder.withUrl(UploadDataTask.URL).method(Method.POST)
                    .param("json", o.toString()).param("user", email);
            ServletUtils.queueWithRetries(UploadDataTask.QUEUE, task, "Processing data item upload");
        } catch (JSONException e) {
            LOG.warning("Couldn't parse item " + i + " in JSON array: " + e.toString());
            resp.getOutputStream().print("<p>Couldn't parse item " + i + "</p>\n");
        }
    }
}

From source file:net.rim.ejde.internal.util.PackageUtils.java

static public String parseFileForPackageId(File file) {
    if ((null == file) || file.isDirectory() || !file.exists()) {
        String msg = NLS.bind(Messages.PackageUtils_UNDEFINED_FILE_ERROR_MSG, IConstants.EMPTY_STRING);
        _logger.error(msg);/*from  w w w. j a  v  a 2  s . co m*/
        throw new RuntimeException(msg);
    }

    String packageId = null, filePath = file.getAbsolutePath(), line, token;

    BufferedReader bufferedReader = null;
    StringTokenizer tokenizer;

    try {
        if (PackageUtils.hasRRHExtension(filePath) || PackageUtils.hasRRCExtension(filePath)
                || PackageUtils.hasJavaExtension(filePath)) {

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

            if (!bufferedReader.ready()) {
                throw new RuntimeException(
                        NLS.bind(Messages.PackageUtils_EMPTY_FILE_ERROR_MSG, file.getPath()));
            }

            while (null != (line = bufferedReader.readLine())) {
                // pull lines from file till find the one containing
                // package definition
                line = line.trim();

                if ((0 < line.length()) && // criterion to recognize a
                // package declaration
                        line.startsWith("package")) {
                    while (!line.contains(IConstants.SEMICOLON_MARK)) {
                        line = line + bufferedReader.readLine();
                    }

                    tokenizer = new StringTokenizer(line);

                    while (tokenizer.hasMoreTokens()) {
                        // pull the package tokens
                        token = tokenizer.nextToken();

                        if (!"package".equals(token)) {
                            if (token.contains(IConstants.SEMICOLON_MARK)) {
                                token = token.replaceAll(IConstants.SEMICOLON_MARK, IConstants.EMPTY_STRING);
                            }

                            packageId = StringUtils.isNotBlank(token) ? token : IConstants.EMPTY_STRING;

                            break;
                        } // end pulling of eventual package tokens
                    }
                }

                if (null != packageId) {
                    // file
                    break;
                }
            }
        } else {
            throw new RuntimeException(
                    NLS.bind(Messages.PackageUtils_UNSUPPORTED_FILE_ERROR_MSG, file.getPath()));
        }
    } catch (Throwable t) {
        _logger.debug(t.getMessage(), t);
    } finally {
        if (null != bufferedReader) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                _logger.error(e.getMessage(), e);
            }
        }
    }

    return packageId;
}

From source file:com.moz.fiji.schema.tools.synth.DictionaryLoader.java

/**
 * Loads the dictionary from an input stream.
 *
 * @param inputStream The input stream of words, one per line.
 * @return The list of words from the stream.
 * @throws IOException If there is an error reading the words from the stream.
 *///  w  w  w .  j ava2  s.c  o m
public List<String> load(InputStream inputStream) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
    List<String> dict = new ArrayList<String>();
    while (reader.ready()) {
        dict.add(StringUtils.strip(reader.readLine()));
    }
    return dict;
}

From source file:de.erdesignerng.test.BaseERDesignerTestCaseImpl.java

protected String readResourceFile(String aResourceName) throws IOException {
    StringWriter theStringWriter = new StringWriter();
    PrintWriter thePrintWriter = new PrintWriter(theStringWriter);
    BufferedReader theBr = new BufferedReader(
            new InputStreamReader(getClass().getResourceAsStream(aResourceName)));
    while (theBr.ready()) {
        String theLine = theBr.readLine();
        if (theLine != null && theLine.length() > 0) {
            thePrintWriter.println(theLine);
        }//  w  ww. j av a  2s . com
    }
    theBr.close();
    thePrintWriter.flush();
    return theStringWriter.toString().trim();

}

From source file:com.google.gplus.processor.GooglePlusActivitySerDeTest.java

@Test
public void TestActivityObjects() {
    InputStream is = GooglePlusActivitySerDeTest.class.getResourceAsStream("/google_plus_activity_jsons.txt");
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);

    try {//from ww w  . j av a 2 s .c o  m
        while (br.ready()) {
            String line = br.readLine();
            if (!StringUtils.isEmpty(line)) {
                LOGGER.info("raw: {}", line);
                Activity activity = new Activity();

                com.google.api.services.plus.model.Activity gPlusActivity = objectMapper.readValue(line,
                        com.google.api.services.plus.model.Activity.class);

                googlePlusActivityUtil.updateActivity(gPlusActivity, activity);
                LOGGER.info("activity: {}", activity);

                assertNotNull(activity);
                assert (activity.getId().contains("id:googleplus:post"));
                assertEquals(activity.getVerb(), "post");

                Provider provider = activity.getProvider();
                assertEquals(provider.getId(), "id:providers:googleplus");
                assertEquals(provider.getDisplayName(), "GooglePlus");

                Actor actor = activity.getActor();
                assertNotNull(actor.getImage());
                assert (actor.getId().contains("id:googleplus:"));
                assertNotNull(actor.getUrl());

                assertNotNull(activity.getPublished());
                assertNotNull(activity.getTitle());
                assertNotNull(activity.getUrl());

                Map<String, Object> extensions = (Map<String, Object>) activity.getAdditionalProperties()
                        .get("extensions");
                assertNotNull(extensions);
                assertNotNull(extensions.get("googlePlus"));

                if (activity.getContent() != null) {
                    assertNotNull(extensions.get("rebroadcasts"));
                    assertNotNull(extensions.get("keywords"));
                    assertNotNull(extensions.get("likes"));
                    assert (((Map<String, Object>) extensions.get("rebroadcasts")).containsKey("count"));
                    assert (((Map<String, Object>) extensions.get("likes")).containsKey("count"));
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("Exception while testing serializability: {}", e);
    }
}