Example usage for java.io Reader read

List of usage examples for java.io Reader read

Introduction

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

Prototype

public int read(char cbuf[]) throws IOException 

Source Link

Document

Reads characters into an array.

Usage

From source file:gov.nih.nci.evs.browser.servlet.UploadServlet.java

public String convertStreamToString(InputStream is, long size) throws IOException {

    if (is != null) {
        Writer writer = new StringWriter();
        char[] buffer = new char[(int) size];
        try {//from   w w w  . j  a  v  a2  s. co  m
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }

        } finally {
            is.close();
        }
        return writer.toString();

    } else {
        return "";
    }

}

From source file:com.siahmsoft.soundwaper.net.SoundcloudApi.java

public String convertStreamToString(InputStream is) throws IOException {
    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {/*from ww w .  j a  v a2s. c  o m*/
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {
        return "";
    }
}

From source file:com.krawler.common.util.ByteUtil.java

/**
 * Reads a <tt>String</tt> from the given <tt>Reader</tt>. Reads until
 * the either end of the stream is hit or until <tt>length</tt> characters
 * are read.//from   ww w  .  j  a va 2s . c om
 * 
 * @return the content or an empty <tt>String</tt> if no content is
 *         available
 */
public static String getContent(Reader reader, int length, boolean close) throws IOException {
    if (reader == null || length == 0) {
        return "";
    }
    if (length < 0) {
        length = Integer.MAX_VALUE;
    }
    char[] buf = new char[Math.min(1024, length)];
    int totalRead = 0;
    StringBuilder retVal = new StringBuilder(buf.length);

    try {
        while (true) {
            int numToRead = Math.min(buf.length, length - totalRead);
            if (numToRead <= 0) {
                break;
            }
            int numRead = reader.read(buf);
            if (numRead < 0) {
                break;
            }
            retVal.append(buf, 0, numRead);
            totalRead += numRead;
        }
        return retVal.toString();
    } finally {
        if (close) {
            try {
                reader.close();
            } catch (IOException e) {
                KrawlerLog.misc.warn("Unable to close Reader", e);
            }
        }
    }
}

From source file:es.eucm.eadventure.editor.plugin.vignette.ServerProxy.java

public String getJson() {
    String json = null;/*from  w ww  . j a  v a2  s.  c  o  m*/
    try {
        HttpClient httpclient = getProxiedHttpClient();
        String url = serviceURL + "/load.php?" + "m=" + getMac() + "&f=" + userPath;

        HttpGet hg = new HttpGet(url);
        HttpResponse response;
        response = httpclient.execute(hg);
        if (Integer.toString(response.getStatusLine().getStatusCode()).startsWith("2")) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();

                StringWriter strWriter = new StringWriter();

                char[] buffer = new char[1024];
                try {
                    Reader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
                    int n;
                    while ((n = reader.read(buffer)) != -1) {
                        strWriter.write(buffer, 0, n);
                    }
                } finally {
                    instream.close();
                }
                json = strWriter.toString();
            }
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return json;
}

From source file:hudson.Util.java

public static void copyStream(Reader in, Writer out) throws IOException {
    char[] buf = new char[8192];
    int len;//w w w  .jav  a  2s .  co  m
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
}

From source file:com.vmware.bdd.cli.auth.LoginClientImplTest.java

public LoginTestTemplate(final String expectedUserName, final String expectedPassword, final int responseCode,
        final String sessionId) {

    httpHandler = new HttpHandler() {
        @Override//from w w w .j  a  v a  2 s  .  c o m
        public void handle(HttpExchange httpExchange) throws IOException {
            Headers headers = httpExchange.getRequestHeaders();

            Assert.assertEquals("application/x-www-form-urlencoded; charset=UTF-8",
                    headers.getFirst("Content-Type"));
            Assert.assertEquals("POST", httpExchange.getRequestMethod());

            InputStream reqStream = httpExchange.getRequestBody();

            Reader reader = new InputStreamReader(reqStream);

            StringBuilder sb = new StringBuilder();

            char[] tmp = new char[16];
            int count = reader.read(tmp);
            while (count > 0) {
                sb.append(tmp, 0, count);
                count = reader.read(tmp);
            }

            //            String val = URLDecoder.decode(sb.toString(), "UTF-8");

            List<NameValuePair> namePasswordPairs = URLEncodedUtils.parse(sb.toString(),
                    Charset.forName("UTF-8"));
            Assert.assertEquals(namePasswordPairs.get(0).getValue(), expectedUserName);
            Assert.assertEquals(namePasswordPairs.get(1).getValue(), expectedPassword);

            if (sessionId != null) {
                Headers responseHeaders = httpExchange.getResponseHeaders();
                responseHeaders.set(LoginClientImpl.SET_COOKIE_HEADER,
                        "JSESSIONID=" + sessionId + "; Path=/serengeti; Secure");
            }

            String response = "LoginClientImplTest";
            httpExchange.sendResponseHeaders(responseCode, response.length());

            BufferedOutputStream os = new BufferedOutputStream(httpExchange.getResponseBody());

            os.write(response.getBytes());
            os.close();

        }
    };
}

From source file:com.archivas.clienttools.arcutils.impl.adapter.HCAPAdapter.java

protected static String getCustomMetadata(Reader reader) throws IOException, CustomMetadataTooLargeException {
    long maxCmdLength = HCPMoverProperties.CM_MAX_IN_MEMORY_SIZE.getAsLong();
    StringBuilder out = new StringBuilder();

    char[] chars = new char[CM_BUFFER_SIZE];
    int readCnt;//w  w w  . j  av  a  2s.c  om
    do {
        readCnt = reader.read(chars);
        if (readCnt > 0) {
            if (out.length() + readCnt > maxCmdLength) {
                throw new CustomMetadataTooLargeException();
            }
            out.append(chars, 0, readCnt);
        }
    } while (readCnt >= 0);

    return out.toString();
}

From source file:org.geosdi.geoplatform.gui.server.service.impl.PublisherService.java

@Override
public String publishLayerPreview(HttpServletRequest httpServletRequest, List<String> layerList,
        boolean reloadCluster) throws GeoPlatformException {
    try {//from w  w  w  .  j a va 2 s  . co  m
        sessionUtility.getLoggedAccount(httpServletRequest);
    } catch (GPSessionTimeout timeout) {
        throw new GeoPlatformException(timeout);
    }
    String result = null;
    try {
        geoPlatformPublishClient.publishAll(httpServletRequest.getSession().getId(), "previews", "dataTest",
                layerList);

        if (reloadCluster) {
            HttpResponse response = httpclient.execute(targetHost, httpget, localContext);
            //                HttpResponse response = httpclient.execute(get, localContext);
            InputStream is = response.getEntity().getContent();
            Writer writer = new StringWriter();
            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                is.close();
            }
            result = writer.toString();
        }
    } catch (ResourceNotFoundFault ex) {
        logger.error("Error on publish shape: " + ex);
        throw new GeoPlatformException("Error on publish shape.");
    } catch (FileNotFoundException ex) {
        logger.error("Error on publish shape: " + ex);
        throw new GeoPlatformException("Error on publish shape.");
    } catch (MalformedURLException e) {
        logger.error("Error on cluster url: " + e);
        throw new GeoPlatformException(new GPReloadURLException("Error on cluster url."));
    } catch (IOException e) {
        logger.error("Error on reloading cluster: " + e);
        throw new GeoPlatformException(new GPReloadURLException("Error on reloading cluster."));
    }
    return result;
}

From source file:net.jadler.stubbing.StubbingTest.java

@Test(expected = JadlerException.class)
public void withBodyReaderThrowingIOE() throws Exception {
    final Reader reader = mock(Reader.class);
    when(reader.read(any(char[].class))).thenThrow(new IOException());

    try {/*  w w w  .j  av  a2 s  . c  o m*/
        this.stubbing.respond().withBody(reader);
    } finally {
        verify(reader).close();
    }
}

From source file:com.sg2net.utilities.ListaCAP.ListaComuniCapFromInternet.java

private Collection<String> getListaCAPFromHTMLPage(String url) throws ClientProtocolException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    InputStream instream = entity.getContent();
    Reader reader = new InputStreamReader(instream, HTML_ENCODING);
    StringWriter writer = new StringWriter();
    int charsRead = 0;
    char[] buffer = new char[BUFFER];
    while ((charsRead = reader.read(buffer)) > 0) {
        writer.write(buffer, 0, charsRead);
    }/*  w w w .  ja v a  2  s.  c o  m*/
    instream.close();
    String content = writer.toString();
    Collection<String> capList = new HashSet<>();
    Matcher m = pattern.matcher(content);
    if (m.matches()) {
        String capMinAsString = m.group(2);
        String capPrefix = "";
        int index = 0;
        while (capMinAsString.charAt(index) == '0') {
            capPrefix += "0";
            index++;
        }
        Integer minCap = Integer.parseInt(m.group(2));
        Integer maxCap = Integer.parseInt(m.group(3));
        for (int i = minCap; i <= maxCap; i++) {
            capList.add(capPrefix + i);
        }
        logger.trace("trovati cap nella pagina html " + url);
    } else {
        logger.info("cap non trovati nella pagina html " + url);
        logger.info(content);
    }
    return capList;

}