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:org.sasabus.export2Freegis.network.DataReadyManager.java

@Override
public void handle(HttpExchange httpExchange) throws IOException {
    long start = System.currentTimeMillis();
    BufferedReader in = new BufferedReader(new InputStreamReader(httpExchange.getRequestBody(), "UTF-8"));
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(httpExchange.getResponseBody()));
    try {/*from  w  ww  .  ja v a 2 s .c  o  m*/
        StringBuilder requestStringBuff = new StringBuilder();
        int b;
        while ((b = in.read()) != -1) {
            requestStringBuff.append((char) b);
        }
        Scanner sc = new Scanner(new File(DATAACKNOWLEDGE));
        String rdyackstring = "";
        while (sc.hasNextLine()) {
            rdyackstring += sc.nextLine();
        }
        sc.close();
        SimpleDateFormat date_date = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat date_time = new SimpleDateFormat("HH:mm:ssZ");

        Date d = new Date();
        String timestamp = date_date.format(d) + "T" + date_time.format(d);
        timestamp = timestamp.substring(0, timestamp.length() - 2) + ":"
                + timestamp.substring(timestamp.length() - 2);

        rdyackstring = rdyackstring.replaceAll(":timestamp", timestamp);

        httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, rdyackstring.length());
        out.write(rdyackstring);
        out.flush();
        long before_elab = System.currentTimeMillis() - start;
        DataRequestManager teqrequest = new DataRequestManager(this.hostname, this.portnumber);
        String datarequest = teqrequest.datarequest();
        ArrayList<TeqObjects> requestelements = TeqXMLUtils.extractFromXML(datarequest);
        int vtcounter = 0;
        if (!requestelements.isEmpty()) {
            Iterator<TeqObjects> iterator = requestelements.iterator();
            System.out.println("Sending List of Elements!");
            String geoJson = "{\"type\":\"FeatureCollection\",\"features\":[";
            while (iterator.hasNext()) {
                TeqObjects object = iterator.next();
                if (object instanceof VehicleTracking) {
                    geoJson += ((VehicleTracking) object).toGeoJson() + ",";
                    ++vtcounter;
                }
            }
            if (geoJson.charAt(geoJson.length() - 1) == ',') {
                geoJson = geoJson.substring(0, geoJson.length() - 1);
            }
            geoJson += "]}";
            System.out.println(
                    "GeoJson sent! (Nr of elements: " + vtcounter + "/" + requestelements.size() + " )");
            HttpPost subrequest = new HttpPost(DATASEND);

            StringEntity requestEntity = new StringEntity(geoJson,
                    ContentType.create("application/json", "UTF-8"));

            CloseableHttpClient httpClient = HttpClients.createDefault();

            subrequest.setEntity(requestEntity);
            long after_elab = System.currentTimeMillis() - start;
            CloseableHttpResponse response = httpClient.execute(subrequest);
            //System.out.println("Stauts JsonSend Response: " + response.getStatusLine().getStatusCode());
            //System.out.println("Status JsonSend Phrase: " + response.getStatusLine().getReasonPhrase());
            httpClient.close();
            long before_db = System.currentTimeMillis() - start;
            dbmanager.insertIntoDatabase(requestelements);
            System.out.format(
                    "Thread time (ms) : Before elab: %d, After Elab (before http sending): %d, Before db: %d, Total: %d, Thread name: %s, Objects elaborated: %d",
                    before_elab, after_elab, before_db, (System.currentTimeMillis() - start),
                    Thread.currentThread().getName(), requestelements.size());
            System.out.println("");
        }

    } catch (IOException e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
        System.exit(-1);
        return;
    } finally {
        if (in != null)
            in.close();
        if (out != null)
            out.close();
        if (httpExchange != null)
            httpExchange.close();
    }
}

From source file:functionalTests.vfsprovider.TestProActiveProviderAutoclosing.java

@Test
public void testRandomReadOnlyAccessInputStreamOpenReadAutocloseRead() throws Exception {
    final FileObject fo = openFileObject(TEST_FILENAME);
    final RandomAccessContent rac = openRandomAccessContent(fo, RandomAccessMode.READ);
    final BufferedReader reader = getBufferedReader(rac.getInputStream());
    try {//from   ww  w .j  a v  a  2  s. com
        for (int i = 0; i < TEST_FILE_A_CHARS_NUMBER; i++) {
            assertTrue('a' == reader.read());
        }
        Thread.sleep(SLEEP_TIME);
        for (int i = 0; i < TEST_FILE_B_CHARS_NUMBER; i++) {
            assertTrue('b' == reader.read());
        }
    } finally {
        rac.close();
    }
    fo.close();
}

From source file:org.metaservice.core.utils.GitUtil.java

@NotNull
public Line[] getChangeList(@NotNull String relPath, @NotNull String revision, String revision2)
        throws GitException {
    try {//from   www.  j  ava  2s  .  c o  m
        if (relPath.startsWith("/"))
            relPath = relPath.replaceFirst("/", "");

        ProcessBuilder builder = new ProcessBuilder("git", "difftool",
                "--extcmd=diff -d --old-line-format=-%L --new-line-format=+%L --unchanged-line-format=_%L",
                "-y", revision2, revision, relPath).directory(workdir);
        LOGGER.info(StringUtils.join(builder.command(), " "));
        Process p = builder.start();

        Line[] lines;

        ArrayList<Line> list = new ArrayList<>();
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));

        int c;
        while ((c = in.read()) != -1) {
            Line l = new Line();
            switch (c) {
            case '+':
                l.changeType = Line.ChangeType.NEW;
                break;
            case '-':
                l.changeType = Line.ChangeType.OLD;
                break;
            case '_':
                l.changeType = Line.ChangeType.UNCHANGED;
                break;
            default:
                throw new RuntimeException("INVALID OUTPUT FORMAT '" + (char) c + "'" + in.readLine());
            }
            //readline alternative which does only halt on \n not \r
            //it also discards \r
            StringBuilder b = new StringBuilder(300);
            while ((c = in.read()) != '\n') {
                if (c == -1)
                    break;
                if (c == '\r')
                    continue;
                b.append((char) c);
            }
            l.line = b.toString();
            list.add(l);
        }
        debug(p);
        lines = list.toArray(new Line[list.size()]);
        LOGGER.debug("READ {} lines", lines.length);
        return lines;
    } catch (IOException e) {
        throw new GitException(e);
    }
}

From source file:org.openmrs.module.formentry.FormEntryUtil.java

/**
 * Converts utf-8 characters into unicode escape characters
 * //from w  w w . ja  va 2s .  c o m
 * @param s the string to convert
 * @return the string with characters converted to unicode escapes with backslashes
 * @should encode Utf8 string
 */
public static String encodeUTF8String(String s) {

    try {
        BufferedReader reader = null;
        BufferedWriter writer = null;
        ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
        try {
            reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(s.getBytes("UTF-8"))));
            writer = new BufferedWriter(new OutputStreamWriter(byteOutputStream, "ISO8859_1")); // or ASCII
            int temp;
            while ((temp = reader.read()) != -1) {
                if (temp <= 0x7f)
                    writer.write(temp);
                else
                    writer.write(toEscape((char) temp));
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } finally {
            try {
                if (reader != null)
                    reader.close();
                if (writer != null)
                    writer.close();
            } catch (IOException ex) {
                ;
            }
        }

        return byteOutputStream.toString("ISO8859-1");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        log.error("Unable to convert to unicode escape characters", e);
        return s;
    }
}

From source file:com.fujitsu.dc.test.jersey.DcResponse.java

/**
 * ???./*from  w ww .  j a v  a 2 s .c o  m*/
 * @param enc 
 * @return 
 * @throws DaoException DAO
 */
public final String bodyAsString(final String enc) throws DaoException {
    InputStream is = null;
    InputStreamReader isr = null;
    BufferedReader reader = null;
    try {
        is = this.getResponseBodyInputStream(response);
        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:org.owasp.jbrofuzz.graph.canvas.HammingDistanceChart.java

private int calculateValue(final File inputFile) {

    int hammingDistance = 0;

    BufferedReader inBuffReader = null;
    try {/*from w  w  w.ja v a2  s  .  c  om*/

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

        // Counter looping through the first response
        int counter1 = 0;
        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()) {

                if (counter1 >= firstSet.length()) {
                    // For each extra character add to the distance
                    hammingDistance++;

                } else {
                    // The current character is not equal to the
                    // one in the buffer, increment
                    if ((char) got != firstSet.charAt(counter1)) {
                        hammingDistance++;
                    }
                }

                counter1++;
            }
            // 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);

    }

    return hammingDistance;
}

From source file:com.b2international.snowowl.snomed.importer.net4j.SnomedSubsetImportUtil.java

private void setDefaultLineFeedCharacter(final SubsetEntry entry) throws IOException {
    FileInputStream inputStream = createFileInputStream(entry);
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

    int i;/*from  ww  w  . j  av  a  2 s .c o m*/
    boolean isNewLineFound = false;
    boolean containsCarriageReturn = false;

    while (!isNewLineFound && -1 != (i = reader.read())) {
        if (i == 13) {
            containsCarriageReturn = true;
            isNewLineFound = true;
        }
        if (i == 10) {
            isNewLineFound = true;
        }
    }

    if (containsCarriageReturn) {
        entry.setLineFeedCharacter("nlc");
    } else {
        entry.setLineFeedCharacter("nl");
    }

    reader.close();
    inputStream.close();
}

From source file:org.alfresco.repo.search.impl.lucene.analysis.VerbatimMLAnalayser.java

@Override
public TokenStream tokenStream(String fieldName, Reader reader) {
    // We use read ahead to get the language info - if this does not exist we need to restart
    // an use the default - there foer we need mark and restore.

    if (!(reader instanceof BufferedReader)) {
        BufferedReader breader = new BufferedReader(reader);
        try {//  w  ww .java  2s.  c o  m
            if (!breader.markSupported()) {
                throw new AnalysisException(
                        "Multilingual tokenisation requires a reader that supports marks and reset");
            }
            breader.mark(100);
            StringBuilder builder = new StringBuilder();
            if (breader.read() == '\u0000') {
                String language = "";
                String country = "";
                String varient = "";
                char c;
                int count = 0;
                while ((c = (char) breader.read()) != '\u0000') {
                    if (count++ > 99) {
                        breader.reset();
                        return getAnalyser().tokenStream(fieldName, breader);
                    }
                    if (c == '_') {
                        if (language.length() == 0) {
                            language = builder.toString();
                        } else if (country.length() == 0) {
                            country = builder.toString();
                        } else if (varient.length() == 0) {
                            varient = builder.toString();
                        } else {
                            breader.reset();
                            return getAnalyser().tokenStream(fieldName, breader);
                        }
                        builder = new StringBuilder();
                    } else {
                        builder.append(c);
                    }
                }
                if (builder.length() > 0) {
                    if (language.length() == 0) {
                        language = builder.toString();
                    } else if (country.length() == 0) {
                        country = builder.toString();
                    } else if (varient.length() == 0) {
                        varient = builder.toString();
                    } else {
                        breader.reset();
                        return getAnalyser().tokenStream(fieldName, breader);
                    }
                }
                Locale locale = new Locale(language, country, varient);
                // leave the reader where it is ....
                return new MLTokenDuplicator(getAnalyser().tokenStream(fieldName, breader), locale, breader,
                        mlAnalaysisMode);
            } else {
                breader.reset();
                return getAnalyser().tokenStream(fieldName, breader);
            }
        } catch (IOException io) {
            try {
                breader.reset();
            } catch (IOException e) {
                throw new AnalysisException("Failed to reset buffered reader - token stream will be invalid",
                        e);
            }
            return getAnalyser().tokenStream(fieldName, breader);
        }

    } else {
        throw new AnalysisException("Multilingual tokenisation requires a buffered reader");
    }
}

From source file:functionalTests.vfsprovider.TestProActiveProviderAutoclosing.java

@Test
public void testInputStreamOpenAutocloseRead() throws Exception {
    final FileObject fo = openFileObject(TEST_FILENAME);
    final BufferedReader reader = openBufferedReader(fo);
    try {//  ww w .  j a  v a 2s .co  m
        Thread.sleep(SLEEP_TIME);
        for (int i = 0; i < TEST_FILE_A_CHARS_NUMBER; i++) {
            assertTrue('a' == reader.read());
        }
    } finally {
        reader.close();
    }
    fo.close();
}

From source file:Opm_Package.New_CommitsInterval.java

public String callURL(String myURL) {
    //System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;/*from   w w w  .j  a v a 2s . co  m*/
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
        }
        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) {
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }

    return sb.toString();
}