Example usage for java.io BufferedReader read

List of usage examples for java.io BufferedReader read

Introduction

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

Prototype

public int read(java.nio.CharBuffer target) throws IOException 

Source Link

Document

Attempts to read characters into the specified character buffer.

Usage

From source file:com.songcode.materialnotes.ui.NotesListActivity.java

private void setAppInfoFromRawRes() {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) {
        StringBuilder sb = new StringBuilder();
        InputStream in = null;/*from  w w w . ja  va 2s. c om*/
        try {
            in = getResources().openRawResource(R.raw.introduction);
            if (in != null) {
                InputStreamReader isr = new InputStreamReader(in);
                BufferedReader br = new BufferedReader(isr);
                char[] buf = new char[1024];
                int len = 0;
                while ((len = br.read(buf)) > 0) {
                    sb.append(buf, 0, len);
                }
            } else {
                Log.e(TAG, "Read introduction file error");
                return;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER,
                AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE, ResourceParser.RED);
        note.setWorkingText(sb.toString());
        if (note.saveNote()) {
            sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit();
        } else {
            Log.e(TAG, "Save introduction note error");
            return;
        }
    }
}

From source file:org.glite.slcs.shibclient.ShibbolethClient.java

/**
 * Fully reads an {@link InputStream} into a {@link String}.
 * /*  w w w. j  av  a  2s .  c o m*/
 * @param is
 *            The InputStream to read.
 * @return The context of the input stream.
 */
private String inputStreamToString(InputStream is) {
    StringBuffer sb = new StringBuffer(1024);
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    try {
        char[] chars = new char[1024];
        while (reader.read(chars) > -1) {
            sb.append(chars);
            chars = new char[1024];
        }
        reader.close();
    } catch (IOException e) {
        LOG.error(e);
    }
    return sb.toString();
}

From source file:nl.privacybarometer.privacyvandaag.service.FetcherService.java

private int refreshFeed(String feedId, long keepDateBorderTime) {
    RssAtomParser handler = null;/* w  w  w .j  a v  a  2s. c o  m*/

    ContentResolver cr = getContentResolver();
    Cursor cursor = cr.query(FeedColumns.CONTENT_URI(feedId), null, null, null, null);

    if (cursor.moveToFirst()) {
        int urlPosition = cursor.getColumnIndex(FeedColumns.URL);
        int idPosition = cursor.getColumnIndex(FeedColumns._ID);
        int titlePosition = cursor.getColumnIndex(FeedColumns.NAME);
        int fetchModePosition = cursor.getColumnIndex(FeedColumns.FETCH_MODE);
        int realLastUpdatePosition = cursor.getColumnIndex(FeedColumns.REAL_LAST_UPDATE);
        int iconPosition = cursor.getColumnIndex(FeedColumns.ICON);
        int retrieveFullscreenPosition = cursor.getColumnIndex(FeedColumns.RETRIEVE_FULLTEXT);

        /* ModPrivacyVandaag: if Fetchmode = 99, do not refresh this feed. */
        int fetchMode = cursor.getInt(fetchModePosition);
        if (fetchMode == FETCHMODE_DO_NOT_FETCH) {
            cursor.close();
            return 0;
        }
        // end of this added block of code; commented out initialize of fetchmode on line 520
        String id = cursor.getString(idPosition);
        HttpURLConnection connection = null;
        try {
            String feedUrl = cursor.getString(urlPosition);
            connection = NetworkUtils.setupConnection(feedUrl);
            String contentType = connection.getContentType();
            handler = new RssAtomParser(new Date(cursor.getLong(realLastUpdatePosition)), keepDateBorderTime,
                    id, cursor.getString(titlePosition), feedUrl,
                    cursor.getInt(retrieveFullscreenPosition) == 1);
            handler.setFetchImages(NetworkUtils.needDownloadPictures());
            // Log.e (TAG,"feedUrl = "+feedUrl);

            if (fetchMode == 0) {
                if (contentType != null && contentType.startsWith(CONTENT_TYPE_TEXT_HTML)) {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(connection.getInputStream()));

                    String line;
                    int posStart = -1;

                    while ((line = reader.readLine()) != null) {
                        if (line.contains(HTML_BODY)) {
                            break;
                        } else {
                            Matcher matcher = FEED_LINK_PATTERN.matcher(line);

                            if (matcher.find()) { // not "while" as only one link is needed
                                line = matcher.group();
                                posStart = line.indexOf(HREF);

                                if (posStart > -1) {
                                    String url = line.substring(posStart + 6, line.indexOf('"', posStart + 10))
                                            .replace(Constants.AMP_SG, Constants.AMP);

                                    ContentValues values = new ContentValues();

                                    if (url.startsWith(Constants.SLASH)) {
                                        int index = feedUrl.indexOf('/', 8);

                                        if (index > -1) {
                                            url = feedUrl.substring(0, index) + url;
                                        } else {
                                            url = feedUrl + url;
                                        }
                                    } else if (!url.startsWith(Constants.HTTP_SCHEME)
                                            && !url.startsWith(Constants.HTTPS_SCHEME)) {
                                        url = feedUrl + '/' + url;
                                    }
                                    values.put(FeedColumns.URL, url);
                                    cr.update(FeedColumns.CONTENT_URI(id), values, null, null);
                                    connection.disconnect();
                                    connection = NetworkUtils.setupConnection(url);
                                    contentType = connection.getContentType();
                                    break;
                                }
                            }
                        }
                    }
                    // this indicates a badly configured feed
                    if (posStart == -1) {
                        connection.disconnect();
                        connection = NetworkUtils.setupConnection(feedUrl);
                        contentType = connection.getContentType();
                    }
                }

                if (contentType != null) {
                    int index = contentType.indexOf(CHARSET);
                    if (index > -1) {
                        int index2 = contentType.indexOf(';', index);

                        try {
                            Xml.findEncodingByName(index2 > -1 ? contentType.substring(index + 8, index2)
                                    : contentType.substring(index + 8));
                            fetchMode = FETCHMODE_DIRECT;
                        } catch (UnsupportedEncodingException ignored) {
                            fetchMode = FETCHMODE_REENCODE;
                        }
                    } else {
                        fetchMode = FETCHMODE_REENCODE;
                    }

                } else {
                    BufferedReader bufferedReader = new BufferedReader(
                            new InputStreamReader(connection.getInputStream()));

                    char[] chars = new char[20];

                    int length = bufferedReader.read(chars);

                    String xmlDescription = new String(chars, 0, length);

                    connection.disconnect();
                    connection = NetworkUtils.setupConnection(connection.getURL());

                    int start = xmlDescription.indexOf(ENCODING);

                    if (start > -1) {
                        try {
                            Xml.findEncodingByName(xmlDescription.substring(start + 10,
                                    xmlDescription.indexOf('"', start + 11)));
                            fetchMode = FETCHMODE_DIRECT;
                        } catch (UnsupportedEncodingException ignored) {
                            fetchMode = FETCHMODE_REENCODE;
                        }
                    } else {
                        // absolutely no encoding information found
                        fetchMode = FETCHMODE_DIRECT;
                    }
                }

                ContentValues values = new ContentValues();
                values.put(FeedColumns.FETCH_MODE, fetchMode);
                cr.update(FeedColumns.CONTENT_URI(id), values, null, null);
            }

            switch (fetchMode) {
            default:
            case FETCHMODE_DIRECT: {
                if (contentType != null) {
                    int index = contentType.indexOf(CHARSET);
                    int index2 = contentType.indexOf(';', index);

                    InputStream inputStream = connection.getInputStream();
                    Xml.parse(inputStream,
                            Xml.findEncodingByName(index2 > -1 ? contentType.substring(index + 8, index2)
                                    : contentType.substring(index + 8)),
                            handler);
                } else {
                    InputStreamReader reader = new InputStreamReader(connection.getInputStream());
                    Xml.parse(reader, handler);
                }
                break;
            }
            case FETCHMODE_REENCODE: {
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                InputStream inputStream = connection.getInputStream();

                byte[] byteBuffer = new byte[4096];

                int n;
                while ((n = inputStream.read(byteBuffer)) > 0) {
                    outputStream.write(byteBuffer, 0, n);
                }

                String xmlText = outputStream.toString();

                int start = xmlText != null ? xmlText.indexOf(ENCODING) : -1;

                if (start > -1) {
                    Xml.parse(new StringReader(new String(outputStream.toByteArray(),
                            xmlText.substring(start + 10, xmlText.indexOf('"', start + 11)))), handler);
                } else {
                    // use content type
                    if (contentType != null) {
                        int index = contentType.indexOf(CHARSET);
                        if (index > -1) {
                            int index2 = contentType.indexOf(';', index);

                            try {
                                StringReader reader = new StringReader(new String(outputStream.toByteArray(),
                                        index2 > -1 ? contentType.substring(index + 8, index2)
                                                : contentType.substring(index + 8)));
                                Xml.parse(reader, handler);
                            } catch (Exception e) {
                                Log.e("Privacy Vandaag: ", "Error reading string " + e.getMessage());
                            }
                        } else {
                            StringReader reader = new StringReader(xmlText);
                            Xml.parse(reader, handler);
                        }
                    }
                }
                break;
            }
            }

            connection.disconnect();
        } catch (FileNotFoundException e) {
            if (handler == null || (!handler.isDone() && !handler.isCancelled())) {
                ContentValues values = new ContentValues();

                // resets the fetch mode to determine it again later
                values.put(FeedColumns.FETCH_MODE, 0);

                values.put(FeedColumns.ERROR, getString(R.string.error_feed_error));
                cr.update(FeedColumns.CONTENT_URI(id), values, null, null);
            }
        } catch (Throwable e) {
            if (handler == null || (!handler.isDone() && !handler.isCancelled())) {
                ContentValues values = new ContentValues();

                // resets the fetch mode to determine it again later
                values.put(FeedColumns.FETCH_MODE, 0);

                values.put(FeedColumns.ERROR,
                        e.getMessage() != null ? e.getMessage() : getString(R.string.error_feed_process));
                cr.update(FeedColumns.CONTENT_URI(id), values, null, null);
                handler = null; // If an error has occurred, reset the new articles counter for this feed to avoid notifications.
            }
        } finally {
            /* check and optionally find favicon */
            /* No longer needed, because the icons of the feeds are included in the package */
            /*
                try {
                    if (handler != null && cursor.getBlob(iconPosition) == null) {
                        String feedLink = handler.getFeedLink();
                        if (feedLink != null) {
                            NetworkUtils.retrieveFavicon(this, new URL(feedLink), id);
                        } else {
                            NetworkUtils.retrieveFavicon(this, connection.getURL(), id);
                        }
                    }
                } catch (Throwable ignored) {
                }
            */
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    cursor.close();

    int newArticles = (handler != null) ? handler.getNewCount() : 0;
    //Log.e(TAG, "Test notification is gegeven voor feedID " + feedId);
    //if (newArticles == 0 ) newArticles =2;      // ONLY FOR TESTING !!!!

    // Check of meldingen voor deze feed aanstaat, anders newArticles op 0 zetten
    if (newArticles > 0) {
        boolean notifyFeed = true;
        switch (Integer.parseInt(feedId)) {
        case 1: // feedID Privacy Barometer
            notifyFeed = PrefUtils.getBoolean(PrefUtils.NOTIFY_PRIVACYBAROMETER, true);
            break;
        case 2: // feedID Bits of Freedom
            notifyFeed = PrefUtils.getBoolean(PrefUtils.NOTIFY_BITSOFFREEDOM, true);
            break;
        case 3: // feedID Privacy First
            notifyFeed = PrefUtils.getBoolean(PrefUtils.NOTIFY_PRIVACYFIRST, true);
            break;
        case 4: // feedID Autoriteit Persoonsgegevens
            notifyFeed = PrefUtils.getBoolean(PrefUtils.NOTIFY_AUTORITEITPERSOONSGEGEVENS, true);
        }
        if (!notifyFeed)
            newArticles = 0; // geen melding als de meldingen voor deze feed uitstaan.
    }
    //Log.e(TAG, "Nieuwe artikelen is " + newArticles);

    return newArticles;
}

From source file:org.fenixedu.academic.ui.faces.bean.teacher.evaluation.EvaluationManagementBackingBean.java

private Map<String, String> loadMarks(final InputStream inputStream) throws IOException {
    final Map<String, String> marks = new HashMap<String, String>();

    final InputStreamReader input = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
    final BufferedReader reader = new BufferedReader(input);

    char[] buffer = new char[4096];
    StringBuilder fileContents = new StringBuilder();
    int i = 0;//ww  w  .  ja v  a 2 s.c o  m
    while ((i = reader.read(buffer)) != -1) {
        fileContents.append(buffer, 0, i);
    }

    try {
        final StringTokenizer stringTokenizer = new StringTokenizer(fileContents.toString());
        while (true) {
            String studentNumber = getNextToken(stringTokenizer);
            if (studentNumber == null) {
                return marks;
            }

            String mark = getNextToken(stringTokenizer);
            if (mark == null) {
                throw new Exception();
            }
            marks.put(studentNumber, mark);
        }
    } catch (Exception e) {
        throw new IOException("error.file.badFormat");
    }
}

From source file:com.enonic.vertical.engine.PresentationEngine.java

private Document getURL(String address, String encoding, int timeoutMs) {
    InputStream in = null;/*from  w  w  w .j a v  a  2 s .  c  o  m*/
    BufferedReader reader = null;
    Document result;
    try {
        URL url = new URL(address);
        URLConnection urlConn = url.openConnection();
        urlConn.setConnectTimeout(timeoutMs > 0 ? timeoutMs : DEFAULT_CONNECTION_TIMEOUT);
        urlConn.setRequestProperty("User-Agent",
                VerticalProperties.getVerticalProperties().getDataSourceUserAgent());
        String userInfo = url.getUserInfo();
        if (StringUtils.isNotBlank(userInfo)) {
            String userInfoBase64Encoded = new String(Base64.encodeBase64(userInfo.getBytes()));
            urlConn.setRequestProperty("Authorization", "Basic " + userInfoBase64Encoded);
        }
        in = urlConn.getInputStream();

        // encoding == null: XML file
        if (encoding == null) {
            result = XMLTool.domparse(in);
        } else {
            StringBuffer sb = new StringBuffer(1024);
            reader = new BufferedReader(new InputStreamReader(in, encoding));
            char[] line = new char[1024];
            int charCount = reader.read(line);
            while (charCount > 0) {
                sb.append(line, 0, charCount);
                charCount = reader.read(line);
            }

            result = XMLTool.createDocument("urlresult");
            Element root = result.getDocumentElement();
            XMLTool.createCDATASection(result, root, sb.toString());
        }
    } catch (SocketTimeoutException ste) {
        String message = "Socket timeout when trying to get url: " + address;
        VerticalEngineLogger.warn(this.getClass(), 0, message, null);
        result = null;
    } catch (IOException ioe) {
        String message = "Failed to get URL: %t";
        VerticalEngineLogger.warn(this.getClass(), 0, message, ioe);
        result = null;
    } catch (RuntimeException re) {
        String message = "Failed to get URL: %t";
        VerticalEngineLogger.warn(this.getClass(), 0, message, re);
        result = null;
    } finally {
        try {
            if (reader != null) {
                reader.close();
            } else if (in != null) {
                in.close();
            }
        } catch (IOException ioe) {
            String message = "Failed to close URL connection: %t";
            VerticalEngineLogger.warn(this.getClass(), 0, message, ioe);
        }
    }

    if (result == null) {
        result = XMLTool.createDocument("noresult");
    }

    return result;
}

From source file:net.sourceforge.fenixedu.presentationTier.backBeans.teacher.evaluation.EvaluationManagementBackingBean.java

private Map<String, String> loadMarks(final InputStream inputStream) throws IOException {
    final Map<String, String> marks = new HashMap<String, String>();

    final InputStreamReader input = new InputStreamReader(inputStream);
    final BufferedReader reader = new BufferedReader(input);

    char[] buffer = new char[4096];
    StringBuilder fileContents = new StringBuilder();
    int i = 0;//  w  ww .ja va 2s  .  c o  m
    while ((i = reader.read(buffer)) != -1) {
        fileContents.append(buffer, 0, i);
    }

    try {
        final StringTokenizer stringTokenizer = new StringTokenizer(fileContents.toString());
        while (true) {
            String studentNumber = getNextToken(stringTokenizer);
            if (studentNumber == null) {
                return marks;
            }

            String mark = getNextToken(stringTokenizer);
            if (mark == null) {
                throw new Exception();
            }
            marks.put(studentNumber, mark);
        }
    } catch (Exception e) {
        throw new IOException("error.file.badFormat");
    }
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.por.PORFileReader.java

private String getNumericFieldAsRawString(BufferedReader reader) throws IOException {
    String temp = null;// www.jav  a2 s  .c  om
    char[] tmp = new char[1];
    StringBuilder sb = new StringBuilder();
    while (reader.read(tmp) > 0) {
        temp = Character.toString(tmp[0]);//new String(tmp);
        if (temp.equals("/")) {
            break;
        } else {
            sb.append(temp);
        }
        //temp = sb.toString();//new String(tmp);
    }
    String base30numberString = sb.toString();
    dbgLog.finer("base30numberString=" + base30numberString);

    return base30numberString;
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.por.PORFileReader.java

private int parseNumericField(BufferedReader reader) throws IOException {
    String temp = null;/* w  w  w.  j av a2s.c  o m*/
    char[] tmp = new char[1];
    StringBuilder sb = new StringBuilder();
    while (reader.read(tmp) > 0) {
        temp = Character.toString(tmp[0]);//new String(tmp);
        if (temp.equals("/")) {
            break;
        } else {
            sb.append(temp);
        }
        //temp = sb.toString();//new String(tmp);
    }
    String base30numberString = sb.toString();
    dbgLog.finer("base30numberString=" + base30numberString);
    int base10equivalent = Integer.valueOf(base30numberString, 30);
    dbgLog.finer("base10equivalent=" + base10equivalent);
    return base10equivalent;
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.por.PORFileReader.java

private String parseStringField(BufferedReader reader) throws IOException {
    String temp = null;//  ww  w  . ja  v a2 s .  c  om
    char[] tmp = new char[1];
    StringBuilder sb = new StringBuilder();
    while (reader.read(tmp) > 0) {
        temp = Character.toString(tmp[0]);//new String(tmp);
        if (temp.equals("/")) {
            break;
        } else {
            sb.append(temp);
        }
        //temp = sb.toString();//new String(tmp);
    }
    String base30numberString = sb.toString();
    //dbgLog.fine("base30numberString="+base30numberString);
    int base10equivalent = Integer.valueOf(base30numberString, 30);
    //dbgLog.fine("base10equivalent="+base10equivalent);
    char[] stringBody = new char[base10equivalent];
    reader.read(stringBody);
    String stringData = new String(stringBody);
    dbgLog.finer("stringData=" + stringData);
    return stringData;
}

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.por.PORFileReader.java

private void decodeNumberOfVariables(BufferedReader reader) throws IOException {
    if (reader == null) {
        throw new IllegalArgumentException("decodeNumberOfVariables: reader == null!");
    }//from   w  w  w . j  av a2 s  . c  o  m

    String temp = null;
    char[] tmp = new char[1];
    StringBuilder sb = new StringBuilder();

    while (reader.read(tmp) > 0) {
        temp = Character.toString(tmp[0]);
        if (temp.equals("/")) {
            break;
        } else {
            sb.append(temp);
        }
    }

    String rawNumberOfVariables = sb.toString();
    int rawLength = rawNumberOfVariables.length();

    String numberOfVariables = StringUtils.stripStart((StringUtils.strip(rawNumberOfVariables)), "0");

    if ((numberOfVariables.equals("")) && (numberOfVariables.length() == rawLength)) {
        numberOfVariables = "0";
    }

    varQnty = Integer.valueOf(numberOfVariables, 30);
    smd.getFileInformation().put("varQnty", varQnty);
}