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:hudson.plugins.emailext.plugins.content.BuildLogMultilineRegexContent.java

private String getContent(BufferedReader reader) throws IOException {
    final Pattern pattern = Pattern.compile(regex);
    final boolean asHtml = matchedSegmentHtmlStyle != null;
    escapeHtml = asHtml || escapeHtml;/*from   w w w.ja  v  a 2 s.  c o m*/

    StringBuilder line = new StringBuilder();
    StringBuilder fullLog = new StringBuilder();
    int ch;
    // Buffer log contents including line terminators, and remove console notes
    while ((ch = reader.read()) != -1) {
        if (ch == '\r' || ch == '\n') {
            if (line.length() > 0) {
                // Remove console notes (JENKINS-7402)
                fullLog.append(ConsoleNote.removeNotes(line.toString()));
                line.setLength(0);
            }
            fullLog.append((char) ch);
        } else {
            line.append((char) ch);
        }
    }
    // Buffer the final log line if it has no line terminator
    if (line.length() > 0) {
        // Remove console notes (JENKINS-7402)
        fullLog.append(ConsoleNote.removeNotes(line.toString()));
    }
    StringBuilder content = new StringBuilder();
    int numMatches = 0;
    boolean insidePre = false;
    int lastMatchEnd = 0;
    final Matcher matcher = pattern.matcher(fullLog);
    while (matcher.find()) {
        if (maxMatches != 0 && ++numMatches > maxMatches) {
            break;
        }
        if (showTruncatedLines) {
            if (matcher.start() > lastMatchEnd) {
                // Append information about truncated lines.
                int numLinesTruncated = countLineTerminators(
                        fullLog.subSequence(lastMatchEnd, matcher.start()));
                if (numLinesTruncated > 0) {
                    insidePre = stopPre(content, insidePre);
                    appendLinesTruncated(content, numLinesTruncated, asHtml);
                }
            }
        }
        if (asHtml) {
            insidePre = startPre(content, insidePre);
        }
        if (substText != null) {
            final StringBuffer substBuf = new StringBuffer();
            matcher.appendReplacement(substBuf, substText);
            // Remove prepended text between matches
            final String segment = substBuf.substring(matcher.start() - lastMatchEnd);
            appendMatchedSegment(content, segment, escapeHtml, matchedSegmentHtmlStyle);
        } else {
            appendMatchedSegment(content, matcher.group(), escapeHtml, matchedSegmentHtmlStyle);
        }
        lastMatchEnd = matcher.end();
    }
    if (showTruncatedLines) {
        if (fullLog.length() > lastMatchEnd) {
            // Append information about truncated lines.
            int numLinesTruncated = countLineTerminators(fullLog.subSequence(lastMatchEnd, fullLog.length()));
            if (numLinesTruncated > 0) {
                insidePre = stopPre(content, insidePre);
                appendLinesTruncated(content, numLinesTruncated, asHtml);
            }
        }
    }
    stopPre(content, insidePre);
    return content.toString();
}

From source file:net.sf.xmm.moviemanager.http.HttpUtil.java

public HTTPResult readData2(URL url) throws Exception {

    if (!isSetup())
        setup();/*from   w w  w.j av a2  s . c o  m*/

    GetMethod method = new GetMethod(url.toString());
    int statusCode = client.executeMethod(method);

    if (statusCode != HttpStatus.SC_OK) {
        log.debug("HTTP StatusCode not HttpStatus.SC_OK:(" + statusCode + "):" + method.getStatusLine());
    }

    java.io.BufferedReader stream = new java.io.BufferedReader(
            new java.io.InputStreamReader(method.getResponseBodyAsStream(), "ISO-8859-1"));

    StringBuffer data = new StringBuffer();

    // Saves the page data in a string buffer... 
    int buffer;

    while ((buffer = stream.read()) != -1) {
        data.append((char) buffer);
    }

    stream.close();

    return new HTTPResult(url, statusCode == HttpStatus.SC_OK ? data : null, method.getStatusLine());
}

From source file:com.fujitsu.dc.client.http.DcResponse.java

/**
 * This method is used to the response body in string format.
 * @param enc Character code/*from   w  ww  .j  av a  2s  . co m*/
 * @return Body text
 * @throws DaoException Exception thrown
 */
public final String bodyAsString(final String enc) throws DaoException {
    InputStream is = null;
    InputStreamReader isr = null;
    BufferedReader reader = null;
    try {
        is = this.getResponseBodyInputStream(response);
        if (is == null) {
            return "";
        }
        isr = new InputStreamReader(is, enc);
        reader = new BufferedReader(isr);
        StringBuffer sb = new StringBuffer();
        int chr;
        while ((chr = reader.read()) != -1) {
            sb.append((char) chr);
        }
        return sb.toString();
    } catch (IOException e) {
        throw DaoException.create("io exception", 0);
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (reader != null) {
                reader.close();
            }
        } catch (Exception e) {
            throw DaoException.create("io exception", 0);
        } finally {
            try {
                if (isr != null) {
                    isr.close();
                }
                if (reader != null) {
                    reader.close();
                }
            } catch (Exception e2) {
                throw DaoException.create("io exception", 0);
            } finally {
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (Exception e3) {
                    throw DaoException.create("io exception", 0);
                }
            }
        }
    }
}

From source file:com.fujitsu.dc.test.utils.TResponse.java

String readBodyChunked(BufferedReader br) throws IOException {
    StringBuilder body = new StringBuilder();
    String line;/* w ww  .  ja  va 2  s  .c  o  m*/
    while ((line = br.readLine()) != null) {
        int hex = 2 * 2 * 2 * 2;
        int chunk = Integer.parseInt(line, hex);
        if (chunk == 0) {
            break;
        }
        int chr;
        for (int i = 0; i < chunk; i++) {
            chr = br.read();
            body.append((char) chr);
        }
        chr = br.read();
        if (chr != '\r') {
            fail("Chunk?CR??");
        }
        chr = br.read();
        if (chr != '\n') {
            fail("Chunk?LF??");
        }
    }
    return body.toString();
}

From source file:com.cts.ptms.carrier.ups.UPSHTTPClient.java

/**
 * This method read all of the data from a URL connection to a String
 *///w ww  . j a  v  a  2s  .co m

private String readURLConnection(URLConnection uc) throws Exception {
    StringBuffer buffer = new StringBuffer();
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        int letter = 0;
        reader.readLine();
        while ((letter = reader.read()) != -1) {
            buffer.append((char) letter);
        }
        reader.close();
    } catch (Exception e) {
        throw e;
    } finally {
        if (reader != null) {
            reader.close();
            reader = null;
        }
    }
    return buffer.toString();
}

From source file:org.onebusaway.transit_data_federation.util.RestApiLibrary.java

public String getContentsOfUrlAsString(URL requestUrl) throws IOException {
    BufferedReader br = null;
    InputStream inStream = null;/*  w ww.j av  a2 s . c  o  m*/
    URLConnection conn = null;

    try {
        conn = requestUrl.openConnection();
        conn.setConnectTimeout(connectionTimeout);
        conn.setReadTimeout(readTimeout);
        inStream = conn.getInputStream();
        br = new BufferedReader(new InputStreamReader(inStream));
        StringBuilder output = new StringBuilder();

        int cp;
        while ((cp = br.read()) != -1) {
            output.append((char) cp);
        }

        return output.toString();
    } catch (IOException ioe) {
        String url = requestUrl != null ? requestUrl.toExternalForm() : "url unavailable";
        log.error("Error getting contents of url: " + url);
        throw ioe;
    } finally {
        try {
            if (br != null)
                br.close();
            if (inStream != null)
                inStream.close();
        } catch (IOException ioe2) {
            log.error("Error closing connection");
        }
    }

}

From source file:net.krautchan.parser.KCPageParser.java

public void parse(BufferedReader reader) {
    if (null == threadHandler) {
        throw new IllegalArgumentException("Cannot parse without a handler");
    }//w  w w.ja  va 2s . com
    if ((null == url) || (url.length() == 0)) {
        throw new IllegalArgumentException("Cannot parse a NULL or empty url");
    }
    tParser.setHandler(threadHandler, token);
    final char[] filter = tParser.getFilterMarker();

    try {
        ThreadState state = new ThreadState();
        int curChar;
        int pos = 0;
        curChar = reader.read();
        while (-1 != curChar) {
            if ((state.curState == StateEnum.START) || (state.curState == StateEnum.READ_THREAD)) {
                if (curChar == filter[pos]) {
                    pos++;
                    if (pos == filter.length) {
                        if (null != thread) {
                            tParser.parse(reader, thread);
                        } else {
                            tParser.parse(reader);
                        }
                        state.curState = StateEnum.START;
                        pos = 0;
                    }
                } else {
                    pos = 0;
                }
            }
            curChar = reader.read();
        }

    } catch (Exception e) {
        e.printStackTrace();
        threadHandler.notifyError(e, token);
    }
    tParser.notifyDone();
}

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

/**
 * @param switchState//from  w w w  .  j  a  v  a2  s . co  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();
    }
}

From source file:org.intermine.install.swing.CreateDatabaseWorker.java

/**
 * Create a database using the Postgres <code>createdb</code> program.
 * /*from   www.jav a  2s. com*/
 * @param server The database server.
 * @param databaseName The database name.
 * @param userName The database user name.
 * @param password The user password.
 * @param encoding The encoding for the database.
 * 
 * @throws IOException if there is a problem running <code>createdb</code>.
 *  
 * @throws InterruptedException if the thread is interrupted while running
 * the <code>createdb</code>.
 * 
 * @throws DatabaseCreationException if the process completes but failed
 * to create the database.
 */
protected void createDatabaseWithCreatedb(String server, String databaseName, String userName, String password,
        String encoding) throws IOException, InterruptedException, DatabaseCreationException {

    String[] commands = { "/usr/bin/createdb", "-h", server, "-E", encoding, "-O", userName, "-W", "-T",
            "template0", databaseName };

    if (logger.isDebugEnabled()) {
        StringBuilder command = new StringBuilder();
        for (int i = 0; i < commands.length; i++) {
            if (i > 0) {
                command.append(' ');
            }
            command.append(commands[i]);
        }
        logger.debug(command);
    }

    StringBuilder output = new StringBuilder();
    StringBuilder errorOutput = new StringBuilder();

    Integer exitCode = null;
    Process p = Runtime.getRuntime().exec(commands);
    try {
        BufferedReader stdin = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        boolean passwordSet = false;
        while (true) {
            try {
                while (stdin.ready()) {
                    char c = (char) stdin.read();
                    output.append(c);
                }
                while (stderr.ready()) {
                    char c = (char) stderr.read();
                    errorOutput.append(c);
                }

                if (!passwordSet && errorOutput.indexOf("Password:") >= 0) {
                    PrintStream out = new PrintStream(p.getOutputStream(), true);
                    out.println(password);
                    passwordSet = true;
                }

                exitCode = p.exitValue();
                // If this succeeds, we're done.
                break;
            } catch (IllegalThreadStateException e) {
                // Process not done, so wait and continue.
                Thread.sleep(250);
            }
        }
    } finally {
        try {
            p.exitValue();
        } catch (IllegalThreadStateException e) {
            // Not finished, but something has failed.
            p.destroy();
        }
    }

    if (errorOutput.length() > 0) {
        throw new DatabaseCreationException(exitCode, output.toString(), errorOutput.toString());
    }

    if (exitCode != 0) {
        throw new DatabaseCreationException("Return code from createdb = " + exitCode, exitCode,
                output.toString(), errorOutput.toString());
    }
}

From source file:com.wabacus.config.database.type.Oracle.java

public void setClobValueInSelectMode(Object value, oracle.sql.CLOB clob) throws SQLException {
    if (clob == null)
        return;//from w  ww.  j  ava  2 s.c  o  m
    String strvalue = "";
    if (value != null)
        strvalue = String.valueOf(value);
    BufferedWriter out = new BufferedWriter(clob.getCharacterOutputStream());
    BufferedReader in = new BufferedReader(new StringReader(strvalue));
    try {
        int c;
        while ((c = in.read()) != -1) {
            out.write(c);
        }
        in.close();
        out.flush();
        out.close();
    } catch (IOException e) {
        throw new WabacusRuntimeException("" + value + "CLOB", e);
    }
}