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.controller.CuotasController.java

@RequestMapping("cuotasAdmin.htm")
public ModelAndView getCuotasAdmin(HttpServletRequest request) {
    sesion = request.getSession();/*from w  w w . ja v  a  2s .co  m*/
    ModelAndView mav = new ModelAndView();
    String mensaje = null;
    Detalles detalle = (Detalles) sesion.getAttribute("cuenta");

    String country = detalle.getCiudad();
    String amount = "5";
    String myURL = "http://192.168.5.39/app_dev.php/public/get/rates";
    // System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
            urlConn.setDoOutput(true);
            String data = URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8");
            data += "&" + URLEncoder.encode("amount", "UTF-8") + "=" + URLEncoder.encode(amount, "UTF-8");

            System.out.println("los Datos a enviar por POST son " + data);

            try ( //obtenemos el flujo de escritura
                    OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) {
                //escribimos
                wr.write(data);
                wr.flush();
                //cerramos la conexin
            }
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String resultado = sb.toString();

    if (sesion.getAttribute("usuario") == null) {

        mav.setViewName("login/login");

    } else {
        sesionUser = sesion.getAttribute("usuario").toString();
        //Detalles detalle = (Detalles) sesion.getAttribute("cuenta");
        mav.addObject("country", detalle.getCiudad());
        mav.addObject("resultado", resultado);

        if (sesion.getAttribute("tipoUsuario").toString().compareTo("Administrador") == 0) {
            mav.setViewName("viewsAdmin/cuotasAdmin");
            System.out.println("el usuario es administrador");
        } else {
            mav.setViewName("panel/cuotas");
        }
    }
    return mav;
}

From source file:org.openehealth.ipf.platform.camel.lbs.mina.mllp.MllpEncoder.java

@Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    notNull(message, "message cannot be null");
    notNull(out, "out cannot be null");

    InputStream inputStream = typeConverter.convertTo(InputStream.class, message);
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

    try {/*ww  w.ja  v  a2 s.  com*/
        AutoCreateByteBuffer buffer = new AutoCreateByteBuffer();

        putAndSendIfFull(out, buffer, (byte) MllpStoreCodec.START_MESSAGE);
        int data = 0;
        while (data != -1) {
            data = reader.read();
            if (data != -1) {
                putAndSendIfFull(out, buffer, data);
            }
        }

        putAndSendIfFull(out, buffer, (byte) MllpStoreCodec.END_MESSAGE);
        putAndSendIfFull(out, buffer, (byte) MllpStoreCodec.LAST_CHARACTER);

        out.write(buffer.getAndDrop());
        log.debug("encoded message: " + message);
    } finally {
        reader.close();
    }
}

From source file:com.controller.CuotasController.java

@RequestMapping(value = "postCuotas.htm", method = RequestMethod.POST)
public ModelAndView postCuotas(HttpServletRequest request) {

    sesion = request.getSession();/*from  www  .  j  ava  2 s  .c o m*/
    String country = request.getParameter("country");
    String amount = request.getParameter("amount");

    Detalles detalle = (Detalles) sesion.getAttribute("cuenta");
    System.out.print(detalle.getCiudad());

    String myURL = "http://192.168.5.39/app_dev.php/public/get/rates";
    // System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
            urlConn.setDoOutput(true);
            String data = URLEncoder.encode("country", "UTF-8") + "=" + URLEncoder.encode(country, "UTF-8");
            data += "&" + URLEncoder.encode("amount", "UTF-8") + "=" + URLEncoder.encode(amount, "UTF-8");

            System.out.println("los Datos a enviar por POST son " + data);

            try ( //obtenemos el flujo de escritura
                    OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) {
                //escribimos
                wr.write(data);
                wr.flush();
                //cerramos la conexin
            }
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String resultado = sb.toString();

    ModelAndView mav = new ModelAndView();
    if (sesion.getAttribute("usuario") == null) {

        mav.setViewName("login/login");

    } else {
        sesionUser = sesion.getAttribute("usuario").toString();
        //Detalles detalle = (Detalles) sesion.getAttribute("cuenta");
        mav.addObject("country", detalle.getCiudad());
        mav.addObject("resultado", resultado);

        if (sesion.getAttribute("tipoUsuario").toString().compareTo("Administrador") == 0) {
            mav.setViewName("viewsAdmin/cuotasAdmin");
            System.out.println("el usuario es administrador");
        } else {
            mav.setViewName("panel/cuotas");
        }
    }
    return mav;

}

From source file:org.owasp.jbrofuzz.graph.canvas.ResponseHeaderSizeChart.java

private int calculateValue(final File inputFile) {

    if (inputFile.isDirectory()) {
        return -1;
    }//ww  w.j  a v  a 2  s.  c om

    int headerLength = 0;

    BufferedReader inBuffReader = null;
    try {

        inBuffReader = new BufferedReader(new FileReader(inputFile));

        final StringBuffer one = new StringBuffer();
        int counter = 0;
        int got;
        while (((got = inBuffReader.read()) > 0) && (counter < MAX_CHARS)) {

            one.append((char) got);
            counter++;

        }
        inBuffReader.close();

        one.delete(0, one.indexOf(END_SIGNATURE) + END_SIGNATURE.length());

        headerLength = one.indexOf("\r\n\r\n");

        if (headerLength < 0) {

            headerLength = one.indexOf("\n\n");

        }

    } catch (final IOException e1) {

        return -2;

    } catch (final StringIndexOutOfBoundsException e2) {

        return -3;

    } catch (final NumberFormatException e3) {

        return -4;

    } finally {

        IOUtils.closeQuietly(inBuffReader);

    }

    return headerLength;
}

From source file:org.owasp.jbrofuzz.graph.canvas.ResponseTimeChart.java

private int calculateValue(final File inputFile) {

    if (inputFile.isDirectory()) {
        return -1;
    }/*from  w  w w .  j av  a 2s  . com*/

    int responseTime = 0;

    BufferedReader inBuffReader = null;
    try {

        inBuffReader = new BufferedReader(new FileReader(inputFile));

        final StringBuffer one = new StringBuffer(MAX_CHARS);
        int counter = 0;
        int got;
        while (((got = inBuffReader.read()) > 0) && (counter < MAX_CHARS)) {

            one.append((char) got);
            counter++;

        }
        inBuffReader.close();

        one.delete(0, 5);
        one.delete(one.indexOf("\n--"), one.length());

        responseTime = Integer.parseInt(one.toString());

    } catch (final IOException e1) {

        return -2;

    } catch (final StringIndexOutOfBoundsException e2) {

        return -3;

    } catch (final NumberFormatException e3) {

        return -4;

    } finally {

        IOUtils.closeQuietly(inBuffReader);

    }

    return responseTime;
}

From source file:com.migratebird.script.ScriptContentHandle.java

public String getScriptContentsAsString(long maxNrChars) {
    try {/*www  . j a  v  a 2  s.c  om*/
        InputStream inputStream = this.getScriptInputStream();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, encoding));
            StringWriter stringWriter = new StringWriter();
            long count = 0;
            int c;
            while ((c = bufferedReader.read()) != -1) {
                stringWriter.write(c);
                if (++count >= maxNrChars) {
                    stringWriter.write("... <remainder of script is omitted>");
                    break;
                }
            }
            return stringWriter.toString();
        } finally {
            inputStream.close();
        }
    } catch (IOException e) {
        return "<script content could not be retrieved>";
    }
}

From source file:org.apache.jmeter.save.CSVSaveService.java

/**
 * Reads from file and splits input into strings according to the delimiter,
 * taking note of quoted strings.// ww w . j ava2 s  .  c om
 * <p>
 * Handles DOS (CRLF), Unix (LF), and Mac (CR) line-endings equally.
 * <p>
 * A blank line - or a quoted blank line - both return an array containing
 * a single empty String.
 * @param infile
 *            input file - must support mark(1)
 * @param delim
 *            delimiter (e.g. comma)
 * @return array of strings, will be empty if there is no data, i.e. if the input is at EOF.
 * @throws IOException
 *             also for unexpected quote characters
 */
public static String[] csvReadFile(BufferedReader infile, char delim) throws IOException {
    int ch;
    ParserState state = ParserState.INITIAL;
    List<String> list = new ArrayList<>();
    CharArrayWriter baos = new CharArrayWriter(200);
    boolean push = false;
    while (-1 != (ch = infile.read())) {
        push = false;
        switch (state) {
        case INITIAL:
            if (ch == QUOTING_CHAR) {
                state = ParserState.QUOTED;
            } else if (isDelimOrEOL(delim, ch)) {
                push = true;
            } else {
                baos.write(ch);
                state = ParserState.PLAIN;
            }
            break;
        case PLAIN:
            if (ch == QUOTING_CHAR) {
                baos.write(ch);
                throw new IOException("Cannot have quote-char in plain field:[" + baos.toString() + "]");
            } else if (isDelimOrEOL(delim, ch)) {
                push = true;
                state = ParserState.INITIAL;
            } else {
                baos.write(ch);
            }
            break;
        case QUOTED:
            if (ch == QUOTING_CHAR) {
                state = ParserState.EMBEDDEDQUOTE;
            } else {
                baos.write(ch);
            }
            break;
        case EMBEDDEDQUOTE:
            if (ch == QUOTING_CHAR) {
                baos.write(QUOTING_CHAR); // doubled quote => quote
                state = ParserState.QUOTED;
            } else if (isDelimOrEOL(delim, ch)) {
                push = true;
                state = ParserState.INITIAL;
            } else {
                baos.write(QUOTING_CHAR);
                throw new IOException(
                        "Cannot have single quote-char in quoted field:[" + baos.toString() + "]");
            }
            break;
        default:
            throw new IllegalStateException("Unexpected state " + state);
        } // switch(state)
        if (push) {
            if (ch == '\r') {// Remove following \n if present
                infile.mark(1);
                if (infile.read() != '\n') {
                    infile.reset(); // did not find \n, put the character
                                    // back
                }
            }
            String s = baos.toString();
            list.add(s);
            baos.reset();
        }
        if ((ch == '\n' || ch == '\r') && state != ParserState.QUOTED) {
            break;
        }
    } // while not EOF
    if (ch == -1) {// EOF (or end of string) so collect any remaining data
        if (state == ParserState.QUOTED) {
            throw new IOException("Missing trailing quote-char in quoted field:[\"" + baos.toString() + "]");
        }
        // Do we have some data, or a trailing empty field?
        if (baos.size() > 0 // we have some data
                || push // we've started a field
                || state == ParserState.EMBEDDEDQUOTE // Just seen ""
        ) {
            list.add(baos.toString());
        }
    }
    return list.toArray(new String[list.size()]);
}

From source file:org.owasp.jbrofuzz.graph.canvas.JaccardIndexChart.java

private void calculateFirstSet(final File inputFile) {

    BufferedReader inBuffReader = null;
    try {//ww w. j  a  va2  s.  co  m

        inBuffReader = new BufferedReader(new FileReader(inputFile));

        int counter = 0;
        int check = 0;
        int got;
        while (((got = inBuffReader.read()) > 0) && (counter < MAX_CHARS)) {

            // If we are passed "--jbrofuzz-->\n" in the file
            if (check == END_SIGNATURE.length()) {

                firstSet.add((char) got);

            }
            // Else find "--jbrofuzz-->\n" using a counter
            else {
                // Increment the counter for each success
                if (got == END_SIGNATURE.charAt(check)) {
                    check++;
                } else {
                    check = 0;
                }
            }

            counter++;

        }
        inBuffReader.close();

    } catch (final IOException e1) {
        System.out.println("An IOException occurred.");
    } finally {

        IOUtils.closeQuietly(inBuffReader);
    }

}

From source file:org.owasp.jbrofuzz.graph.canvas.HammingDistanceChart.java

private void calculateFirstSet(final File inputFile) {

    BufferedReader inBuffReader = null;
    try {//from ww w .ja v a  2 s.  c  om

        inBuffReader = new BufferedReader(new FileReader(inputFile));

        int counter = 0;
        int check = 0;
        int got;
        while (((got = inBuffReader.read()) > 0) && (counter < MAX_CHARS)) {

            // If we are passed "--jbrofuzz-->\n" in the file
            if (check == END_SIGNATURE.length()) {

                firstSet.append((char) got);

            }
            // Else find "--jbrofuzz-->\n" using a counter
            else {
                // Increment the counter for each success
                if (got == END_SIGNATURE.charAt(check)) {
                    check++;
                } else {
                    check = 0;
                }
            }

            counter++;

        }
        inBuffReader.close();

    } catch (final IOException e1) {
        System.out.println("An IOException occurred.");
    } finally {

        IOUtils.closeQuietly(inBuffReader);
    }

}

From source file:org.owasp.jbrofuzz.graph.canvas.JaccardIndexChart.java

private double calculateValue(final File inputFile) {

    final HashSet<Character> secondSet = new HashSet<Character>();

    BufferedReader inBuffReader = null;
    try {/*from  w  ww.  j  a v  a2s  .  c  om*/

        inBuffReader = new BufferedReader(new FileReader(inputFile));

        int counter = 0;
        int check = 0;
        int c;
        while (((c = inBuffReader.read()) > 0) && (counter < MAX_CHARS)) {

            // If we are passed "--jbrofuzz-->\n" in the file
            if (check == END_SIGNATURE.length()) {

                secondSet.add((char) c);

            }
            // Else find "--jbrofuzz-->\n" using a counter
            else {
                // Increment the counter for each success
                if (c == END_SIGNATURE.charAt(check)) {
                    check++;
                } else {
                    check = 0;
                }
            }

            counter++;

        }
        inBuffReader.close();

    } catch (final IOException e1) {
        System.out.println("An IOExcepiton occurred.");
    } finally {

        IOUtils.closeQuietly(inBuffReader);

    }

    // Calculate the Jaccard Index, between the 2 sets of chars
    final Set<Character> intersectionSet = new HashSet<Character>(firstSet);
    intersectionSet.retainAll(secondSet);

    final Set<Character> unionSet = new HashSet<Character>(firstSet);
    unionSet.addAll(secondSet);
    // The index is the ratio
    return ((double) intersectionSet.size() / (double) unionSet.size());
}