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:org.wso2.cdm.agent.utils.HTTPConnectorUtils.java

public static String readResponseBody(final HttpEntity entity) throws IOException, ParseException {

    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }//from  w  w  w  . j  ava 2s  .c  o  m

    InputStream instream = entity.getContent();

    if (instream == null) {
        return "";
    }

    if (entity.getContentLength() > Integer.MAX_VALUE) {
        throw new IllegalArgumentException(

                "HTTP entity too large to be buffered in memory");
    }

    String charset = getContentCharSet(entity);

    if (charset == null) {

        charset = HTTP.DEFAULT_CONTENT_CHARSET;

    }

    Reader reader = new InputStreamReader(instream, charset);

    StringBuilder buffer = new StringBuilder();

    try {

        char[] tmp = new char[1024];

        int l;

        while ((l = reader.read(tmp)) != -1) {

            buffer.append(tmp, 0, l);

        }

    } finally {

        reader.close();

    }

    return buffer.toString();

}

From source file:it.cloudicaro.disit.kb.rdf.HttpUtil.java

public static String post(URL url, String data, String contentType, String user, String passwd)
        throws Exception {
    //System.out.println("POST "+url);
    HttpClient client = HttpClients.createDefault();
    HttpPost request = new HttpPost(url.toURI());
    request.setEntity(new StringEntity(data, ContentType.create(contentType, "UTF-8")));

    HttpClientContext context = HttpClientContext.create();
    if (user != null && passwd != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, passwd));
        context.setCredentialsProvider(credsProvider);
    }/*from   w w w.j a  v  a  2  s .  c om*/

    HttpResponse response = client.execute(request, context);

    StatusLine s = response.getStatusLine();
    int code = s.getStatusCode();
    //System.out.println(code);
    if (code == 204)
        return "";
    if (code != 200)
        throw new Exception(
                "failed access to " + url.toString() + " code: " + code + " " + s.getReasonPhrase());

    Reader reader = null;
    try {
        reader = new InputStreamReader(response.getEntity().getContent());

        StringBuilder sb = new StringBuilder();
        {
            int read;
            char[] cbuf = new char[1024];
            while ((read = reader.read(cbuf)) != -1) {
                sb.append(cbuf, 0, read);
            }
        }

        return sb.toString();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.moss.appsnap.keeper.freedesktop.FreeDesktopAppHandler.java

public static void writeLaunchScript(boolean isKeeper, String launchCommand, File scriptLocation,
        final PosixFifoSocketAddress fifoSocketServer) throws IOException {
    FileWriter writer = new FileWriter(scriptLocation);
    writer.append("#!" + SHELL + "\n\n");

    if (!isKeeper) {
        {// WRITE THE FIFO SOCKETS FUNCTION
            Reader functionReader = new InputStreamReader(PosixFifoMisc.sendFifoSocketMessageBashFunction());
            char[] b = new char[1024];

            for (int x = functionReader.read(b); x != -1; x = functionReader.read(b)) {
                writer.write(b, 0, x);//from  w  w  w . j  a  v  a 2 s  .co  m
            }
        }

        {
            // WRITE THE POLLING CALL TO THE KEEPER
            final char EOL = '\n';
            writer.append(EOL + "CONTROL=" + fifoSocketServer.controlPipe().getAbsolutePath() + "\n" + "DIR="
                    + fifoSocketServer.socketsDir().getAbsolutePath() + EOL + "" + EOL
                    + "xmessage \"Checking for updates...\" -buttons \"\" -center -title \"Please Wait...\" &"
                    + EOL + "DIALOG=$!" + EOL + "" + EOL
                    + "RESPONSE=`echo -n \"LAUNCH_POLL\" | sendFifoSocketMessage $CONTROL $DIR`" + EOL + ""
                    + EOL + "echo \"RESPONSE: $RESPONSE\"" + EOL + "" + EOL + "kill $DIALOG" + EOL + "" + EOL
                    + "if [ \"$RESPONSE\" != \"OK\" ] " + EOL + "then" + EOL
                    + "   xmessage -center -buttons OK -default OK  \"Polling error: $RESPONSE\"" + EOL
                    + "   exit 1;" + EOL + "fi" + EOL + "" + EOL);
        }
        writer.append(launchCommand);
    } else {
        writer.append("while [ 1 ]; do \n");
        writer.append(launchCommand);
        writer.append('\n');
        writer.append("RESULT=$?\n");
        writer.append("if [ $RESULT != 0 ]; then echo \"Error: keeper quit with return $RESULT\"; exit; fi\n");
        writer.append("done");
    }

    writer.flush();
    writer.close();

}

From source file:it.cloudicaro.disit.kb.rdf.HttpUtil.java

public static String get(URL url, String accept, String user, String passwd) throws Exception {
    //System.out.println("GET "+url);
    HttpClient client = HttpClients.createDefault();
    HttpGet request = new HttpGet(url.toURI());
    if (accept != null)
        request.addHeader("Accept", accept);

    HttpClientContext context = HttpClientContext.create();
    if (user != null && passwd != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, passwd));

        /*// Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);*/

        // Add AuthCache to the execution context
        context.setCredentialsProvider(credsProvider);
    }/*from  ww  w  .  j  a  v a 2 s. c o  m*/
    HttpResponse response = client.execute(request, context);

    StatusLine s = response.getStatusLine();
    int code = s.getStatusCode();
    //System.out.println(code);
    if (code != 200)
        throw new Exception(
                "failed access to " + url.toString() + " code: " + code + " " + s.getReasonPhrase());

    Reader reader = null;
    try {
        reader = new InputStreamReader(response.getEntity().getContent());

        StringBuilder sb = new StringBuilder();
        {
            int read;
            char[] cbuf = new char[1024];
            while ((read = reader.read(cbuf)) != -1) {
                sb.append(cbuf, 0, read);
            }
        }

        return sb.toString();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.xxg.jdeploy.util.FileUtil.java

/**
*
*
* Search for the specified <code>searchString</code> in the given
* {@link Reader}.//  ww  w  .j  av a  2 s  .c o  m
*
* @param reader A Reader in which the String will be searched.
* @param searchString The String to search for
* @return <code>TRUE</code> if the <code>searchString</code> is found;
*         <code>FALSE</code> otherwise.
* @throws IOException
*/
public static boolean containsString(Reader reader, final String searchString) throws IOException {
    char[] buffer = new char[1024];
    int numCharsRead;
    int count = 0;
    while ((numCharsRead = reader.read(buffer)) > 0) {
        for (int c = 0; c < numCharsRead; ++c) {
            if (buffer[c] == searchString.charAt(count))
                count++;
            else
                count = 0;
            if (count == searchString.length())
                return true;
        }
    }
    return false;
}

From source file:cn.count.easydriver366.base.AppSettings.java

public static String readInputStream(InputStream stream) throws IOException, UnsupportedEncodingException {

    Reader reader = null;
    reader = new InputStreamReader(stream, "UTF-8");
    char[] buffer = new char[256];
    StringBuilder sb = new StringBuilder();
    while (reader.read(buffer) != -1) {
        sb.append(buffer);/*from  ww w.  ja  v a  2 s  .c om*/
    }
    return sb.toString();
}

From source file:com.cloudbees.eclipse.core.util.Utils.java

public final static String readString(final InputStream is) throws CloudBeesException {
    if (is == null) {
        return null;
    }/*from w  ww  .  j ava 2 s  . c  o  m*/
    try {
        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();
        }
        return writer.toString();
    } catch (Exception e) {
        throw new CloudBeesException("Failed to read inputstream", e);
    }
}

From source file:com.taveloper.http.test.ParseBenchmark.java

private static String resourceToString(String path) throws Exception {
    InputStream in = ParseBenchmark.class.getResourceAsStream(path);
    if (in == null) {
        throw new IllegalArgumentException("No such file: " + path);
    }//from w ww . j  av a  2  s.  c om

    Reader reader = new InputStreamReader(in, "UTF-8");
    char[] buffer = new char[8192];
    StringWriter writer = new StringWriter();
    int count;
    while ((count = reader.read(buffer)) != -1) {
        writer.write(buffer, 0, count);
    }
    reader.close();
    return writer.toString();
}

From source file:ca.simplegames.micro.utils.IO.java

/**
 * Copy the contents of the given Reader to the given Writer.
 * Closes both when done.//from ww  w. j  ava2s  .  c  om
 *
 * @param in  the Reader to copy from
 * @param out the Writer to copy to
 * @return the number of characters copied
 * @throws IOException in case of I/O errors
 */
public static int copy(Reader in, Writer out) throws IOException {
    try {
        int byteCount = 0;
        char[] buffer = new char[BUFFER_SIZE];
        int bytesRead;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
            byteCount += bytesRead;
        }
        out.flush();
        return byteCount;
    } finally {
        IO.close(out);
        IO.close(in);
    }
}

From source file:com.puppycrawl.tools.checkstyle.api.FileText.java

/**
 * Reads file using specific decoder and returns all its content as a String.
 * @param inputFile File to read//from w  w w . j  a  v  a  2 s.  c o  m
 * @param decoder Charset decoder
 * @return File's text
 * @throws IOException Unable to open or read the file
 */
private static String readFile(final File inputFile, final CharsetDecoder decoder) throws IOException {
    if (!inputFile.exists()) {
        throw new FileNotFoundException(inputFile.getPath() + " (No such file or directory)");
    }
    final StringBuilder buf = new StringBuilder();
    final FileInputStream stream = new FileInputStream(inputFile);
    final Reader reader = new InputStreamReader(stream, decoder);
    try {
        final char[] chars = new char[READ_BUFFER_SIZE];
        while (true) {
            final int len = reader.read(chars);
            if (len < 0) {
                break;
            }
            buf.append(chars, 0, len);
        }
    } finally {
        Closeables.closeQuietly(reader);
    }
    return buf.toString();
}