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() throws IOException 

Source Link

Document

Reads a single character.

Usage

From source file:org.wymiwyg.wrhapi.test.BaseTests.java

private void testSimpleBody(final boolean writeBody) throws Exception {
    final String body = "This is the content of the body";
    WebServer webServer = createServer().startNewWebServer(new Handler() {

        public void handle(Request request, Response response) throws HandlerException {
            log.info("handling testSimpleBody");

            if (writeBody) {
                response.setBody(new MessageBody2Write() {

                    public void writeTo(WritableByteChannel out) throws IOException {
                        out.write(ByteBuffer.wrap(body.getBytes()));
                    }/* w ww. j  a  v  a 2 s  .  co  m*/
                });
            } else {
                response.setBody(new MessageBody2Read() {

                    public ReadableByteChannel read() throws IOException {
                        return Channels.newChannel(new ByteArrayInputStream(body.getBytes()));
                    }
                });
            }
        }
    }, serverBinding);

    try {
        URL serverURL = new URL("http://" + serverBinding.getInetAddress().getHostAddress() + ":"
                + serverBinding.getPort() + "/");
        Reader reader = new InputStreamReader(serverURL.openStream());
        StringWriter stringWriter = new StringWriter();

        for (int ch = reader.read(); ch != -1; ch = reader.read()) {
            stringWriter.write(ch);
        }

        assertEquals(body, stringWriter.toString());
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        webServer.stop();
    }
}

From source file:com.cognitect.transit.TransitTest.java

public void testReadMany() throws IOException {

    Reader r = reader("true null false \"foo\" 42.2 42");
    assertTrue((Boolean) r.read());
    assertNull(r.read());/*  w ww.  j a  v a  2 s.  com*/
    assertFalse((Boolean) r.read());
    assertEquals("foo", r.read());
    assertEquals(42.2, r.read());
    assertEquals(42L, r.read());
}

From source file:org.wymiwyg.wrhapi.test.BaseTests.java

@Test
public void testEmptyBodyAnHeader() throws Exception {
    final String body = "";
    WebServer webServer = createServer().startNewWebServer(new Handler() {

        public void handle(Request request, final Response response) throws HandlerException {
            log.info("handling testEmptyBody");
            response.setResponseStatus(ResponseStatus.CREATED);
            response.setBody(new MessageBody2Write() {

                public void writeTo(WritableByteChannel out) throws IOException {
                    try {
                        response.setHeader(HeaderName.CONTENT_TYPE, "text/plain");
                    } catch (HandlerException ex) {
                        throw new RuntimeException(ex);
                    }/*w w w .  j ava2s. c o  m*/
                    out.write(ByteBuffer.wrap(body.getBytes()));
                    out.close();
                }
            });
        }
    }, serverBinding);

    try {
        URL serverURL = new URL("http://" + serverBinding.getInetAddress().getHostAddress() + ":"
                + serverBinding.getPort() + "/");
        HttpURLConnection connection = (HttpURLConnection) serverURL.openConnection();
        assertEquals("text/plain", connection.getHeaderField("Content-Type"));
        assertEquals(ResponseStatus.CREATED.getCode(), connection.getResponseCode());
        Reader reader = new InputStreamReader(connection.getInputStream());
        StringWriter stringWriter = new StringWriter();

        for (int ch = reader.read(); ch != -1; ch = reader.read()) {
            stringWriter.write(ch);
        }

        assertEquals(body, stringWriter.toString());
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        webServer.stop();
    }
}

From source file:com.cognitect.transit.TransitTest.java

public void testRoundTrip() throws Exception {

    Object inObject = true;//w  w  w .j  a v  a2  s .c  om

    OutputStream out = new ByteArrayOutputStream();
    Writer w = TransitFactory.writer(TransitFactory.Format.JSON_VERBOSE, out);
    w.write(inObject);
    String s = out.toString();
    InputStream in = new ByteArrayInputStream(s.getBytes());
    Reader reader = TransitFactory.reader(TransitFactory.Format.JSON, in);
    Object outObject = reader.read();

    assertTrue(isEqual(inObject, outObject));
}

From source file:de.micromata.genome.gwiki.page.gspt.ExtendedTemplate.java

/**
 * Groovy comment.//from w  w w .  j  a  v a2 s. co m
 *
 * @param reader the reader
 * @param elements the elements
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void groovyComment(Reader reader, List<ParseElement> elements) throws IOException {
    StringBuilder sw = new StringBuilder();
    int c;
    while ((c = reader.read()) != -1) {
        if (c == '-') {
            c = reader.read();
            if (c == '-') {
                c = reader.read();
                if (c == '%') {
                    c = reader.read();
                    if (c == '>') {
                        break;
                    } else {
                        sw.append("--%");
                    }
                } else {
                    sw.append("--");
                }
            } else {
                sw.append("-");
            }
        } else {
            sw.append((char) c);
        }
    }
    elements.add(new ParseElement(Type.Comment, sw.toString()));
}

From source file:de.micromata.genome.gwiki.page.gspt.ExtendedTemplate.java

/**
 * Closes the currently open write and writes the following text as normal Groovy script code until it reaches an end %>.
 *
 * @param global the global//from  ww w. j a  v  a 2 s . com
 * @param reader the reader
 * @param elements the elements
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void groovySection(Type global, Reader reader, List<ParseElement> elements) throws IOException {
    // sw.write("\");");
    int c;
    StringBuilder sw = new StringBuilder();
    while ((c = reader.read()) != -1) {
        if (c == '%') {
            c = reader.read();
            if (c != '>') {
                sw.append('%');
            } else {
                break;
            }
        }
        /*
         * Don't eat EOL chars in sections - as they are valid instruction separators. See http://jira.codehaus.org/browse/GROOVY-980
         */
        // if (c != '\n' && c != '\r') {
        sw.append((char) c);
        // }
    }
    elements.add(new ParseElement(global, sw.toString()));
    // sw.write(";\nout.print(\"");
}

From source file:org.wymiwyg.wrhapi.test.BaseTests.java

/**
 * test is the returned status code matches the one of the HandlerException
 * thrown, with a HandlerException thrown after a body is set
 * //from   w  ww . j a v  a 2  s .  c  o  m
 * @throws Exception
 *             on failure
 */
/*public void testExceptionStatusCodeAfterBody() throws Exception {
final int statusCode = 302;
WebServer webServer = createServer().startNewWebServer(new Handler() {
public void handle(Request request, Response response)
throws HandlerException {
log.info("handling testStatusCode");
response.setHeader(HeaderName.SERVER, "Ad-Hoc testing server");
response.setBody(new MessageBody2Write() {
public void writeTo(WritableByteChannel out)
throws IOException {
out.write(ByteBuffer.wrap("my body\n\ncontent\n"
.getBytes()));
}
});
        
throw new HandlerException(ResponseStatus.getInstanceByCode(statusCode));
}
}, serverBinding);
        
try {
URL serverURL = new URL("http://"
+ serverBinding.getInetAddress().getHostAddress() + ":"
+ serverBinding.getPort() + "/");
HttpClient client = new HttpClient();
HttpMethod method = new HeadMethod(serverURL.toString());
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(0, false));
client.executeMethod(method);
// for the handler to be invoked, something of the response has to
// be asked
assertEquals(statusCode, method.getStatusCode());
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
webServer.stop();
}
}*/
@Test
public void testRepeated() throws Exception {
    final String body = "This is the content of the body";
    final boolean writeBody = false;
    WebServer webServer = createServer().startNewWebServer(new Handler() {

        public void handle(Request request, Response response) throws HandlerException {
            log.info("handling testSimpleBody");

            if (writeBody) {
                response.setBody(new MessageBody2Write() {

                    public void writeTo(WritableByteChannel out) throws IOException {
                        out.write(ByteBuffer.wrap(body.getBytes()));
                    }
                });
            } else {
                response.setBody(new MessageBody2Read() {

                    public ReadableByteChannel read() throws IOException {
                        return Channels.newChannel(new ByteArrayInputStream(body.getBytes()));
                    }
                });
            }
        }
    }, serverBinding);

    TimeLogger tl = new TimeLogger();
    for (int r = 0; r < 10000; r++) {
        tl.startSection("iteration");
        URL serverURL = new URL("http://" + serverBinding.getInetAddress().getHostAddress() + ":"
                + serverBinding.getPort() + "/");
        Reader reader = new InputStreamReader(serverURL.openStream());
        StringWriter stringWriter = new StringWriter();

        for (int ch = reader.read(); ch != -1; ch = reader.read()) {
            stringWriter.write(ch);
        }

        assertEquals(body, stringWriter.toString());
        tl.endSection();
    }

    webServer.stop();

    tl.writeReport(new PrintWriter(System.out));
    System.out.println("Using SummaryReportWriter:");
    tl.setReportWriter(new SummaryReportWriter());
    tl.writeReport(new PrintWriter(System.out));
}

From source file:de.micromata.genome.gwiki.page.gspt.ExtendedTemplate.java

/**
 * Closes the currently open write and writes out the following text as a GString expression until it reaches an end %>.
 *
 * @param reader the reader/*ww  w  .  ja va  2  s.  co m*/
 * @param elements the elements
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void groovyExpression(Reader reader, List<ParseElement> elements) throws IOException {
    // sw.write("\");out.print(\"${");
    StringBuilder sw = new StringBuilder();
    int c;
    while ((c = reader.read()) != -1) {
        if (c == '%') {
            c = reader.read();
            if (c != '>') {
                // sw.write('%');
                sw.append('%');
            } else {
                break;
            }
        }
        if (c != '\n' && c != '\r') {
            sw.append((char) c);
        }
    }
    elements.add(new ParseElement(Type.AssignExpr, sw.toString()));
    // sw.write("}\");\nout.print(\"");
}

From source file:ca.sqlpower.enterprise.JSONResponseHandler.java

public JSONMessage handleResponse(Reader reader, int status) {
    if (status == 404) {
        throw new RuntimeException("Server resource is not available.");
    }/*from  w w w.  jav a  2 s. c om*/
    if (status == 403) {
        throw new AccessDeniedException("Insufficient priviledges");
    }

    JSONTokener tokener = new JSONTokener(reader);
    try {
        JSONObject message;
        try {
            message = (JSONObject) tokener.nextValue();
        } catch (ClassCastException ex) {
            StringBuffer sb = new StringBuffer();
            sb.append("Internal server error. Server responded with the following.\n");
            try {
                int charAsInt = reader.read();
                while (charAsInt != -1) {
                    sb.append((char) charAsInt);
                    charAsInt = reader.read();
                }
                logger.error(sb.toString());
            } catch (IOException e) {
                logger.error("Failed to parse the root exception. The following was received " + sb.toString());
            }
            throw new RuntimeException(
                    "Server error " + status + ". See logs or server logs for more details.");
        }

        // Does the response contain data? If so, return it. Communication
        // with the resource has been successful.
        if (message.getString("responseKind").equals("data")) {
            return new JSONMessage(message.getString("data"), status);
        } else {
            // Has the request been unsuccessful?
            if (message.getString("responseKind").equals("unsuccessful")) {
                return new JSONMessage(message.getString("data"), status);
            } else {
                // Does the response contain an exception? If so, reconstruct, and then
                // re-throw it. There has been an exception on the server.
                if (message.getString("responseKind").equals("exceptionStackTrace")) {

                    JSONArray stackTraceStrings = new JSONArray(message.getString("data"));
                    StringBuffer stackTraceMessage = new StringBuffer();

                    if (stackTraceStrings.length() > 0) {
                        String firstLine = stackTraceStrings.getString(0);
                        String userMessage = null;
                        if (firstLine.contains(FriendlyRuntimeSPPersistenceException.class.getName())) {
                            userMessage = firstLine.substring(
                                    firstLine.indexOf(FriendlyRuntimeSPPersistenceException.class.getName())
                                            + FriendlyRuntimeSPPersistenceException.class.getName().length()
                                            + 2);
                        } else if (firstLine.contains(FriendlySPPersistenceException.class.getName())) {
                            userMessage = firstLine
                                    .substring(firstLine.indexOf(FriendlySPPersistenceException.class.getName())
                                            + FriendlySPPersistenceException.class.getName().length() + 2);
                        }

                        if (userMessage != null) {
                            for (int i = 0; i < stackTraceStrings.length(); i++) {
                                stackTraceMessage.append("\n").append(stackTraceStrings.get(i));
                            }
                            logger.info(stackTraceMessage.toString());

                            throw new FriendlyRuntimeSPPersistenceException(userMessage);
                        }
                    }

                    for (int i = 0; i < stackTraceStrings.length(); i++) {
                        stackTraceMessage.append("\n").append(stackTraceStrings.get(i));
                    }

                    throw new SPPersistenceException(null, stackTraceMessage.toString());

                } else {
                    // This exception represents a(n epic) client-server miscommunication
                    throw new Exception("Unable to parse response ");
                }
            }
        }
    } catch (JSONException ex) {
        StringBuffer sb = new StringBuffer();
        sb.append("Internal server error. Server responded with the following.\n");
        try {
            int charAsInt = reader.read();
            while (charAsInt != -1) {
                sb.append(charAsInt);
                charAsInt = reader.read();
            }
            logger.error(sb.toString());
        } catch (IOException e) {
            logger.error("Failed to parse the root exception. The following was received " + sb.toString());
        }
        throw new RuntimeException("Server error. See logs or server logs for more details.");
    } catch (RuntimeException ex) {
        throw ex;
    } catch (Exception ex) {
        String message = ex.getMessage();
        if (message.contains("\n")) {
            String[] messages = message.split("\n");
            for (String serverMsg : messages) {
                if (serverMsg.trim().length() > 0) {
                    message = serverMsg.trim();
                    break;
                }
            }
        }
        throw new RuntimeException("Server returned status " + status + "\n" + message, ex);
    }
}

From source file:net.metanotion.json.StreamingParser.java

private String lexInt(final Reader in, final int firstChar) throws IOException {
    final StringBuilder sb = new StringBuilder();
    int digits = 0;
    if (firstChar == '-') {
        sb.append("-");
    } else if (Character.isDigit(firstChar)) {
        sb.append(Character.toChars(firstChar));
        digits++;//from   w  ww.  j  av a  2 s .  c o  m
    } else {
        final String found = new String(Character.toChars(firstChar));
        throw new ParserException("Expecting a number, instead found: '" + found + QUOTE);
    }
    while (true) {
        in.mark(MAX_BUFFER);
        final int c = in.read();
        if (Character.isDigit(c)) {
            digits++;
            sb.append(Character.toChars(c));
        } else {
            in.reset();
            if (digits == 0) {
                throw new ParserException(EXPECTED_DIGIT);
            }
            return sb.toString();
        }
    }
}