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() throws IOException 

Source Link

Document

Reads a single character.

Usage

From source file:com.mirth.connect.plugins.datatypes.delimited.DelimitedReader.java

/**
 * This low level reader gets the next non-ignored character from the input, and returns it.
 * //from   w  w w  . j a  v a  2s.c o  m
 * @param in
 *            The input stream (it's a BufferedReader, because operations on it require
 *            in.mark()).
 * @param remark
 *            Iff true, remarks the input stream after reading an ignored character.
 * @return The next non-ignored character read, or -1 if end of input stream.
 * @throws IOException
 */
private int getNonIgnoredChar(BufferedReader in, boolean remark) throws IOException {
    int ch;

    // If configured, gobble \r
    if (serializationProperties.isIgnoreCR()) {
        while (((char) (ch = in.read())) == '\r') {
            if (remark) {
                in.mark(1);
            }
        }
    } else {
        ch = in.read();
    }

    return ch;
}

From source file:com.mirth.connect.plugins.datatypes.delimited.DelimitedBatchReader.java

/**
  * Finds the next message in the input stream and returns it.
  * /*  w w  w  .  ja v a2 s.  com*/
  * @param in
  *            The input stream (it's a BufferedReader, because operations on
  *            it require in.mark()).
  * @param skipHeader
  *            Pass true to skip the configured number of header rows,
  *            otherwise false.
  * @return The next message, or null if there are no more messages.
  * @throws IOException
  * @throws InterruptedException
  */
public String getMessage(final BufferedReader in, final boolean skipHeader, final String batchScriptId)
        throws IOException, InterruptedException {
    char recDelim = reader.getRecordDelimiter().charAt(0);
    int ch;

    // If skipping the header, and the option is configured
    if (skipHeader && batchProperties.getBatchSkipRecords() > 0) {

        for (int i = 0; i < batchProperties.getBatchSkipRecords(); i++) {
            while ((ch = in.read()) != -1 && ((char) ch) != recDelim) {
            }
        }
    }

    StringBuilder message = new StringBuilder();

    if (batchProperties.isBatchSplitByRecord()) {
        // Each record is treated as a message
        reader.getRecord(in, message);
    } else if (StringUtils.isNotEmpty(batchProperties.getBatchMessageDelimiter())) {
        if (batchMessageDelimiter == null) {
            batchMessageDelimiter = StringUtil.unescape(batchProperties.getBatchMessageDelimiter());
        }
        // All records until the message delimiter (or end of input) is a
        // message.
        for (;;) {
            // Get the next record
            ArrayList<String> record = reader.getRecord(in, message);

            if (record == null) {
                break;
            }

            // If the next sequence of characters is the message delimiter
            String lookAhead = reader.peekChars(in, batchMessageDelimiter.length());
            if (lookAhead.equals(batchMessageDelimiter)) {

                // Consume it.
                for (int i = 0; i < batchMessageDelimiter.length(); i++) {
                    ch = reader.getChar(in, null);
                }

                // Append it if it is being included
                if (batchProperties.isBatchMessageDelimiterIncluded()) {
                    message.append(batchMessageDelimiter);
                }

                break;
            }
        }
    } else if (StringUtils.isNotEmpty(batchProperties.getBatchGroupingColumn())) {
        // Each message is a collection of records with the same value in
        // the specified column.
        // The end of the current message occurs when a transition in the
        // value of the specified
        // column occurs.

        // Prime the pump: get the first record, and save the grouping
        // column.
        ArrayList<String> record = reader.getRecord(in, message);

        if (record != null) {

            if (groupingColumnIndex == null) {
                updateGroupingColumnIndex(batchProperties.getBatchGroupingColumn(),
                        serializationProperties.getColumnNames());
            }

            String lastColumnValue = record.get(groupingColumnIndex);

            // Read records until the value in the grouping column changes
            // or there are no more records
            for (;;) {

                StringBuilder recordText = new StringBuilder();
                record = reader.getRecord(in, recordText);

                if (record == null) {
                    break;
                }

                if (!record.get(groupingColumnIndex).equals(lastColumnValue)) {
                    reader.ungetRecord(record, recordText.toString());
                    break;
                }

                message.append(recordText.toString());
            }
        }
    } else if (StringUtils.isNotEmpty(batchProperties.getBatchScript())) {
        try {
            final int batchSkipRecords = batchProperties.getBatchSkipRecords();
            String result = JavaScriptUtil.execute(new JavaScriptTask<String>() {
                @Override
                public String call() throws Exception {
                    Script compiledScript = CompiledScriptCache.getInstance().getCompiledScript(batchScriptId);

                    if (compiledScript == null) {
                        logger.error("Batch script could not be found in cache");
                        return null;
                    } else {
                        Logger scriptLogger = Logger.getLogger(ScriptController.BATCH_SCRIPT_KEY.toLowerCase());

                        Scriptable scope = JavaScriptScopeUtil.getBatchProcessorScope(scriptLogger,
                                batchScriptId,
                                getScopeObjects(in, serializationProperties, skipHeader, batchSkipRecords));
                        return Context.toString(executeScript(compiledScript, scope));
                    }
                }
            });

            if (result != null) {
                message.append(result);
            }
        } catch (InterruptedException e) {
            throw e;
        } catch (JavaScriptExecutorException e) {
            logger.error(e.getCause());
        } catch (Throwable e) {
            logger.error(e);
        }
    } else {
        // There is no batching method configured. Treat the entire input
        // stream as the message.
        logger.warn("No batch splitting method configured (processing entire input as one message)");
        while ((ch = in.read()) != -1) {
            message.append((char) ch);
        }
    }

    String result = message.toString();
    if (result.length() == 0) {
        return null;
    } else {
        return result;
    }
}

From source file:org.onosproject.netconf.ctl.impl.NetconfSshdTestSubsystem.java

@Override
public void run() {
    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(in));
    boolean socketClosed = false;
    try {//from   w ww . j a va  2 s  .  c om
        StringBuilder deviceRequestBuilder = new StringBuilder();
        while (!socketClosed) {
            int cInt = bufferReader.read();
            if (cInt == -1) {
                log.info("Netconf client sent error");
                socketClosed = true;
            }
            char c = (char) cInt;
            state = state.evaluateChar(c);
            deviceRequestBuilder.append(c);
            if (state == NetconfMessageState.END_PATTERN) {
                String deviceRequest = deviceRequestBuilder.toString();
                if (deviceRequest.equals(END_PATTERN)) {
                    socketClosed = true;
                    this.interrupt();
                } else {
                    deviceRequest = deviceRequest.replace(END_PATTERN, "");
                    Optional<Integer> messageId = NetconfStreamThread.getMsgId(deviceRequest);
                    log.info("Client Request on session {}. MsgId {}: {}", session.getSessionId(), messageId,
                            deviceRequest);
                    synchronized (outputStream) {

                        if (HELLO_REQ_PATTERN.matcher(deviceRequest).matches()) {

                            String helloReply = getTestHelloReply(
                                    Optional.of(ByteBuffer.wrap(session.getSessionId()).asLongBuffer().get()),
                                    false);
                            outputStream.write(helloReply + END_PATTERN);
                            outputStream.flush();
                        } else if (HELLO_REQ_PATTERN_1_1.matcher(deviceRequest).matches()) {

                            String helloReply = getTestHelloReply(
                                    Optional.of(ByteBuffer.wrap(session.getSessionId()).asLongBuffer().get()),
                                    true);
                            outputStream.write(helloReply + END_PATTERN);
                            outputStream.flush();
                        } else {
                            Pair<String, Boolean> replyClosedPair = dealWithRequest(deviceRequest, messageId);
                            String reply = replyClosedPair.getLeft();
                            if (reply != null) {
                                Boolean newSockedClosed = replyClosedPair.getRight();
                                socketClosed = newSockedClosed.booleanValue();
                                outputStream.write(reply + END_PATTERN);
                                outputStream.flush();
                            }
                        }
                    }
                    deviceRequestBuilder.setLength(0);
                }
            } else if (state == NetconfMessageState.END_CHUNKED_PATTERN) {
                String deviceRequest = deviceRequestBuilder.toString();
                if (!validateChunkedFraming(deviceRequest)) {
                    log.error("Netconf client send badly framed message {}", deviceRequest);
                } else {
                    deviceRequest = deviceRequest.replaceAll(MSGLEN_REGEX_PATTERN, "");
                    deviceRequest = deviceRequest.replaceAll(CHUNKED_END_REGEX_PATTERN, "");
                    Optional<Integer> messageId = NetconfStreamThread.getMsgId(deviceRequest);
                    log.info("Client Request on session {}. MsgId {}: {}", session.getSessionId(), messageId,
                            deviceRequest);

                    synchronized (outputStream) {

                        if (HELLO_REQ_PATTERN.matcher(deviceRequest).matches()) {
                            String helloReply = getTestHelloReply(
                                    Optional.of(ByteBuffer.wrap(session.getSessionId()).asLongBuffer().get()),
                                    true);
                            outputStream.write(helloReply + END_PATTERN);
                            outputStream.flush();
                        } else {
                            Pair<String, Boolean> replyClosedPair = dealWithRequest(deviceRequest, messageId);
                            String reply = replyClosedPair.getLeft();
                            if (reply != null) {
                                Boolean newSockedClosed = replyClosedPair.getRight();
                                socketClosed = newSockedClosed.booleanValue();
                                outputStream.write(formatChunkedMessage(reply));
                                outputStream.flush();
                            }
                        }
                    }

                }
                deviceRequestBuilder.setLength(0);
            }
        }
    } catch (Throwable t) {
        if (!socketClosed && !(t instanceof EOFException)) { // Ignore
            log.error("Exception caught in NETCONF Server subsystem", t.getMessage());
        }
    } finally {
        try {
            bufferReader.close();
        } catch (IOException ioe) {
            log.error("Could not close DataInputStream", ioe);
        }

        callback.onExit(0);
    }
}

From source file:org.apache.openjpa.lib.meta.ClassArgParser.java

/**
 * Returns the classes named in the given common format metadata stream.
 *//*from www.  j  a  v a  2s.  com*/
private Collection<String> getFromMetaData(Reader xml) throws IOException {
    Collection<String> names = new ArrayList<String>();
    BufferedReader in = new BufferedReader(xml);

    boolean comment = false;
    int token = TOKEN_NONE;
    String pkg = "";
    String name;
    read: for (int ch = 0, last = 0, last2 = 0; ch == '<' || (ch = in.read()) != -1; last2 = last, last = ch) {
        // handle comments
        if (comment && last2 == '-' && last == '-' && ch == '>') {
            comment = false;
            continue;
        }
        if (comment) {
            if (ch == '<') {
                ch = in.read();
                if (ch == -1)
                    break read;
            }
            continue;
        }
        if (last2 == '<' && last == '!' && ch == '-') {
            comment = true;
            continue;
        }

        // if not an element start, skip it
        if (ch != '<')
            continue;
        token = TOKEN_NONE; // reset token
        last = ch; // update needed for comment detection
        ch = readThroughWhitespace(in);
        if (ch == '/' || ch == '!' || ch == '?')
            continue;

        // read element name; look for packages and classes
        token = readElementToken(ch, in);
        switch (token) {
        case TOKEN_EOF:
            break read;
        case TOKEN_PACKAGE:
            pkg = readAttribute(in, _packageAttr);
            if (pkg == null)
                break read;
            break;
        case TOKEN_PACKAGE_NOATTR:
            pkg = readElementText(in);
            if (pkg == null)
                break read;
            ch = '<'; // reading element text reads to next '<'
            break;
        case TOKEN_CLASS:
            name = readAttribute(in, _classAttr);
            if (name == null)
                break read;
            if (pkg.length() > 0 && name.indexOf('.') == -1)
                names.add(pkg + "." + name);
            else
                names.add(name);
            break;
        case TOKEN_CLASS_NOATTR:
            name = readElementText(in);
            if (name == null)
                break read;
            ch = '<'; // reading element text reads to next '<'
            if (pkg.length() > 0 && name.indexOf('.') == -1)
                names.add(pkg + "." + name);
            else
                names.add(name);
            break;
        }
    }
    return names;
}

From source file:org.apache.velocity.tools.view.ImportSupport.java

/**
 *
 * @param url the URL resource to return as string
 * @return the URL resource as string/* www. j a va  2 s  .c  om*/
 * @throws IOException
 * @throws java.lang.Exception
 */
protected String acquireString(String url) throws IOException, Exception {
    // Record whether our URL is absolute or relative
    if (isAbsoluteUrl(url)) {
        // for absolute URLs, delegate to our peer
        BufferedReader r = null;
        try {
            r = new BufferedReader(acquireReader(url));
            StringBuffer sb = new StringBuffer();
            int i;
            // under JIT, testing seems to show this simple loop is as fast
            // as any of the alternatives
            while ((i = r.read()) != -1) {
                sb.append((char) i);
            }
            return sb.toString();
        } finally {
            if (r != null) {
                try {
                    r.close();
                } catch (IOException ioe) {
                    LOG.error("Could not close reader.", ioe);
                }
            }
        }
    } else // handle relative URLs ourselves
    {
        // URL is relative, so we must be an HTTP request
        if (!(request instanceof HttpServletRequest && response instanceof HttpServletResponse)) {
            throw new Exception("Relative import from non-HTTP request not allowed");
        }

        // retrieve an appropriate ServletContext
        // normalize the URL if we have an HttpServletRequest
        if (!url.startsWith("/")) {
            String sp = ((HttpServletRequest) request).getServletPath();
            url = sp.substring(0, sp.lastIndexOf('/')) + '/' + url;
        }

        // strip the session id from the url
        url = stripSession(url);

        // from this context, get a dispatcher
        RequestDispatcher rd = application.getRequestDispatcher(url);
        if (rd == null) {
            throw new Exception("Couldn't get a RequestDispatcher for \"" + url + "\"");
        }

        // include the resource, using our custom wrapper
        ImportResponseWrapper irw = new ImportResponseWrapper((HttpServletResponse) response);
        try {
            rd.include(request, irw);
        } catch (IOException ex) {
            throw new Exception("Problem importing the relative URL \"" + url + "\". " + ex);
        } catch (RuntimeException ex) {
            throw new Exception("Problem importing the relative URL \"" + url + "\". " + ex);
        }

        // disallow inappropriate response codes per JSTL spec
        if (irw.getStatus() < 200 || irw.getStatus() > 299) {
            throw new Exception("Invalid response code '" + irw.getStatus() + "' for \"" + url + "\"");
        }

        // recover the response String from our wrapper
        return irw.getString();
    }
}

From source file:com.krawler.portal.tools.FileImpl.java

public String extractText(InputStream is, String fileExt) {
    String text = null;//from   ww  w .j av  a2s .  co m

    try {
        fileExt = GetterUtil.getString(fileExt).toLowerCase();

        TextExtractor extractor = null;

        String contentType = null;
        String encoding = System.getProperty("encoding");

        if (fileExt.equals(".doc")) {
            extractor = new MsWordTextExtractor();

            contentType = "application/vnd.ms-word";
        }
        //         else if (fileExt.equals(".htm") || fileExt.equals(".html")) {
        //            extractor = new JerichoHTMLTextExtractor();
        //
        //            contentType = "text/html";
        //         }
        else if (fileExt.equals(".odb") || fileExt.equals(".odf") || fileExt.equals(".odg")
                || fileExt.equals(".odp") || fileExt.equals(".ods") || fileExt.equals(".odt")) {

            extractor = new OpenOfficeTextExtractor();

            contentType = "application/vnd.oasis.opendocument.";

            if (fileExt.equals(".odb")) {
                contentType += "database";
            } else if (fileExt.equals(".odf")) {
                contentType += "formula";
            } else if (fileExt.equals(".odg")) {
                contentType += "graphics";
            } else if (fileExt.equals(".odp")) {
                contentType += "presentation";
            } else if (fileExt.equals(".ods")) {
                contentType += "spreadsheet";
            } else if (fileExt.equals(".odt")) {
                contentType += "text";
            }
        } else if (fileExt.equals(".pdf")) {
            extractor = new PdfTextExtractor();

            contentType = "application/pdf";
        } else if (fileExt.equals(".ppt")) {
            extractor = new MsPowerPointTextExtractor();

            contentType = "application/vnd.ms-powerpoint";
        } else if (fileExt.equals(".rtf")) {
            extractor = new RTFTextExtractor();

            contentType = "application/rtf";
        } else if (fileExt.equals(".txt")) {
            extractor = new PlainTextExtractor();

            contentType = "text/plain";
        } else if (fileExt.equals(".xls")) {
            extractor = new MsExcelTextExtractor();

            contentType = "application/vnd.ms-excel";
        } else if (fileExt.equals(".xml")) {
            extractor = new XMLTextExtractor();

            contentType = "text/xml";
        }

        if (extractor != null) {
            //            if (_log.isInfoEnabled()) {
            //               _log.info(
            //                  "Using extractor " + extractor.getClass().getName() +
            //                     " for extension " + fileExt);
            //            }

            StringBuilder sb = new StringBuilder();

            BufferedReader reader = new BufferedReader(extractor.extractText(is, contentType, encoding));

            int i;

            while ((i = reader.read()) != -1) {
                sb.append((char) i);
            }

            reader.close();

            text = sb.toString();
        } else {
            //            if (_log.isInfoEnabled()) {
            //               _log.info("No extractor found for extension " + fileExt);
            //            }
        }
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        //         _log.error(e);
    }

    //      if (_log.isDebugEnabled()) {
    //         _log.debug("Extractor returned text:\n\n" + text);
    //      }

    if (text == null) {
        text = StringPool.BLANK;
    }

    return text;
}

From source file:org.ballerinalang.test.context.ServerInstance.java

/**
 * Reading output from input stream./*w ww. j  ava2  s.  c  o  m*/
 *
 * @param inputStream input steam of a process
 * @return the output string generated by java process
 */
private String readProcessInputStream(InputStream inputStream) {
    InputStreamReader inputStreamReader = null;
    BufferedReader bufferedReader = null;
    StringBuilder stringBuilder = new StringBuilder();
    try {
        inputStreamReader = new InputStreamReader(inputStream, Charset.defaultCharset());
        bufferedReader = new BufferedReader(inputStreamReader);
        int x;
        while ((x = bufferedReader.read()) != -1) {
            stringBuilder.append((char) x);
        }
    } catch (Exception ex) {
        log.error("Error reading process id", ex);
    } finally {
        if (inputStreamReader != null) {
            try {
                inputStream.close();
                inputStreamReader.close();
            } catch (IOException e) {
                log.error("Error occurred while closing stream: " + e.getMessage(), e);
            }
        }
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                log.error("Error occurred while closing stream: " + e.getMessage(), e);
            }
        }
    }
    return stringBuilder.toString();
}

From source file:org.geppetto.simulation.test.GeppettoManagerTest.java

/**
 * @param variable/*from   www .j a v  a  2  s .  c o  m*/
 * @param columnIndexInTheDATFile
 * @throws NumberFormatException
 * @throws IOException
 */
private void checkValues(VariableValue variable, int columnIndexInTheDATFile)
        throws NumberFormatException, IOException {
    // read DAT into a buffered reader
    BufferedReader input = new BufferedReader(new FileReader("./src/test/resources/test/testResults.dat"));

    ArrayList<Double> storedValues = new ArrayList<Double>();

    // read rest of DAT file and extract values
    while (input.read() != -1) {
        String line = input.readLine();
        String[] columns = line.split("\\s+");
        storedValues.add(Double.valueOf(columns[columnIndexInTheDATFile]));

    }

    Assert.assertArrayEquals(storedValues.toArray(), ((TimeSeries) variable.getValue()).getValue().toArray());

    input.close();
}

From source file:me.jdknight.ums.ccml.core.CcmlRootFolderListener.java

/**
 * Parse a meta value for category type mappings.
 * //  www.ja  v  a  2 s.c o m
 * @param metaFile The meta file to parse.
 * @return         The map of category types to category values.
 */
private Map<String, List<String>> parseMetaFile(File metaFile) {
    BufferedReader reader = null;
    try {
        // Load file based on known encoding.
        String characterEncoding = ByteOrderMarkHelper.getEncoding(metaFile);
        if (characterEncoding != null) {
            reader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(metaFile), characterEncoding));
            reader.read();
        } else {
            reader = new BufferedReader(new FileReader(metaFile));
        }

        Map<String, List<String>> mapOfCategories = new HashMap<String, List<String>>();

        // Parse the meta file for category types to category mappings.
        String rawCategoryDefine;
        while ((rawCategoryDefine = reader.readLine()) != null) {
            String[] propertyAndValue = rawCategoryDefine.split("=", 2); //$NON-NLS-1$
            if (propertyAndValue.length != 2) {
                continue;
            }

            String categoryName = WordUtils.capitalize(propertyAndValue[0]);
            String categoryValue = WordUtils.capitalize(propertyAndValue[1]);
            if (categoryName.isEmpty() == true || categoryValue.isEmpty() == true) {
                continue;
            }

            List<String> categoryValuesList = mapOfCategories.get(categoryName);
            if (categoryValuesList == null) {
                categoryValuesList = new ArrayList<String>();
                mapOfCategories.put(categoryName, categoryValuesList);
            }

            categoryValuesList.add(categoryValue);
        }

        return mapOfCategories;
    } catch (FileNotFoundException e) {
        _logger.error("[CCML] Error opening meta file: " + metaFile); //$NON-NLS-1$
    } catch (IOException e) {
        _logger.error("[CCML] Error parsing meta file: " + metaFile); //$NON-NLS-1$
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // Ignore issues with closing a file.
            }
        }
    }

    return null;
}

From source file:au.gov.aims.atlasmapperserver.URLCache.java

public static String getUncachedResponse(String urlStr) throws IOException, JSONException, URISyntaxException {
    URL url = Utils.toURL(urlStr);

    URLConnection connection = url.openConnection();
    InputStream in = null;//from www. j  a  v  a  2  s. co m
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    try {
        in = connection.getInputStream();
        if (in != null) {
            reader = new BufferedReader(new InputStreamReader(in));

            int cp;
            while ((cp = reader.read()) != -1) {
                sb.append((char) cp);
            }
        }
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
                LOGGER.log(Level.WARNING, "Can not close the URL input stream: {0}",
                        Utils.getExceptionMessage(e));
                LOGGER.log(Level.FINE, "Stack trace:", e);
            }
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception e) {
                LOGGER.log(Level.WARNING, "Can not close the URL reader: {0}", Utils.getExceptionMessage(e));
                LOGGER.log(Level.FINE, "Stack trace:", e);
            }
        }
    }

    return sb.toString();
}