/** * Reads a double-quoted string, unescaping quoted pairs like {@code \"} to the 2nd character in * each sequence. Returns the unescaped string, or null if the buffer isn't prefixed with a * double-quoted string. */ private static String readQuotedString(Buffer buffer) { if (buffer.readByte() != '\"') throw new IllegalArgumentException(); Buffer result = new Buffer(); while (true) { long i = buffer.indexOfElement(QUOTED_STRING_DELIMITERS); if (i == -1L) return null; // Unterminated quoted string. if (buffer.getByte(i) == '"') { result.write(buffer, i); buffer.readByte(); // Consume '"'. return result.readUtf8(); } if (buffer.size() == i + 1L) return null; // Dangling escape. result.write(buffer, i); buffer.readByte(); // Consume '\'. result.write(buffer, 1L); // The escaped character. } }
private String readFromBuffer(Buffer buffer, Charset charset) { long bufferSize = buffer.size(); long maxBytes = Math.min(bufferSize, maxContentLength); String body = ""; try { body = buffer.readString(maxBytes, charset); } catch (EOFException e) { body += context.getString(R.string.chuck_body_unexpected_eof); } if (bufferSize > maxContentLength) { body += context.getString(R.string.chuck_body_content_truncated); } return body; }
/** * Consumes and returns a non-empty token, terminating at special characters in {@link * #TOKEN_DELIMITERS}. Returns null if the buffer is empty or prefixed with a delimiter. */ private static String readToken(Buffer buffer) { try { long tokenSize = buffer.indexOfElement(TOKEN_DELIMITERS); if (tokenSize == -1L) tokenSize = buffer.size(); return tokenSize != 0L ? buffer.readUtf8(tokenSize) : null; } catch (EOFException e) { throw new AssertionError(); } }
@Override public String readUtf8LineStrict() throws EOFException { long newline = indexOf((byte) '\n'); if (newline == -1) { Buffer data = new Buffer(); copyTo(data, 0, Math.min(32, size)); throw new EOFException("\\n not found: size=" + size() + " content=" + data.readByteString().hex() + "..."); } return readUtf8Line(newline); }
if (!source.request(1)) { throw syntaxError("Unterminated escape sequence"); byte escaped = buffer.readByte(); switch (escaped) { case 'u': if (!source.request(4)) { throw new EOFException("Unterminated escape sequence at path " + getPath()); byte c = buffer.getByte(i); result <<= 4; if (c >= '0' && c <= '9') { result += (c - 'A' + 10); } else { throw syntaxError("\\u" + buffer.readUtf8(4)); buffer.skip(4); return result;
synchronized (Http2Stream.this) { finished = this.finished; flowControlError = byteCount + readBuffer.size() > maxByteCount; in.skip(byteCount); closeLater(ErrorCode.FLOW_CONTROL_ERROR); return; in.skip(byteCount); return; long read = in.read(receiveBuffer, byteCount); if (read == -1) throw new EOFException(); byteCount -= read; boolean wasEmpty = readBuffer.size() == 0; readBuffer.writeAll(receiveBuffer); if (wasEmpty) { Http2Stream.this.notifyAll();
@Override public void skip(long byteCount) throws IOException { if (closed) throw new IllegalStateException("closed"); while (byteCount > 0) { if (buffer.size == 0 && source.read(buffer, Segment.SIZE) == -1) { throw new EOFException(); } long toSkip = Math.min(byteCount, buffer.size()); buffer.skip(toSkip); byteCount -= toSkip; } }
@Test public void testReadChannel() throws Exception { ReadableByteChannel channel = new Buffer().writeUtf8(quote); Buffer buffer = new Buffer(); Source source = new ByteChannelSource(channel, Timeout.NONE); source.read(buffer, 75); assertThat(buffer.readUtf8()) .isEqualTo("John, the kind of control you're attempting simply is... it's not possible."); }
logger.log("--> END " + request.method() + " (encoded body omitted)"); } else { Buffer buffer = new Buffer(); requestBody.writeTo(buffer); logger.log(buffer.readString(charset)); } else { BufferedSource source = responseBody.source(); source.request(Long.MAX_VALUE); // Buffer the entire body. Buffer buffer = source.buffer(); logger.log(buffer.clone().readString(charset)); logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
logger.log("--> END " + request.method() + " (encoded body omitted)"); } else { Buffer buffer = new Buffer(); requestBody.writeTo(buffer); logger.log(buffer.readString(charset)); logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)"); } else { BufferedSource source = responseBody.source(); source.request(Long.MAX_VALUE); // Buffer the entire body. Buffer buffer = source.getBuffer(); gzippedLength = buffer.size(); try (GzipSource gzippedResponseBody = new GzipSource(buffer.clone())) { buffer = new Buffer(); buffer.writeAll(gzippedResponseBody); logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)"); return response; logger.log(buffer.clone().readString(charset)); logger.log("<-- END HTTP (" + buffer.size() + "-byte, " + gzippedLength + "-gzipped-byte body)"); } else { logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
public static ByteString encodeQuery(String host, int type) { Buffer buf = new Buffer(); buf.writeShort(0); // query id buf.writeShort(256); // flags with recursion buf.writeShort(1); // question count buf.writeShort(0); // answerCount buf.writeShort(0); // authorityResourceCount buf.writeShort(0); // additional Buffer nameBuf = new Buffer(); final String[] labels = host.split("\\."); for (String label : labels) { long utf8ByteCount = Utf8.size(label); if (utf8ByteCount != label.length()) { throw new IllegalArgumentException("non-ascii hostname: " + host); } nameBuf.writeByte((byte) utf8ByteCount); nameBuf.writeUtf8(label); } nameBuf.writeByte(0); // end nameBuf.copyTo(buf, 0, nameBuf.size()); buf.writeShort(type); buf.writeShort(1); // CLASS_IN return buf.readByteString(); }
@Test public void readFullyByteArray() throws IOException { Buffer data = new Buffer(); data.writeUtf8("Hello").writeUtf8(repeat('e', SEGMENT_SIZE)); byte[] expected = data.clone().readByteArray(); sink.write(data, data.size()); sink.emit(); byte[] sink = new byte[SEGMENT_SIZE + 5]; source.readFully(sink); assertByteArraysEquals(expected, sink); }
@Test public void writeAll() throws IOException { MockSink mockSink = new MockSink(); BufferedSink bufferedSink = Okio.buffer(mockSink); bufferedSink.getBuffer().writeUtf8("abc"); assertEquals(3, bufferedSink.writeAll(new Buffer().writeUtf8("def"))); assertEquals(6, bufferedSink.getBuffer().size()); assertEquals("abcdef", bufferedSink.getBuffer().readUtf8(6)); mockSink.assertLog(); // No writes. }
/** * Sets the response body to {@code body}, chunked every {@code maxChunkSize} bytes. */ public MockResponse setChunkedBody(Buffer body, int maxChunkSize) { removeHeader("Content-Length"); headers.add(CHUNKED_BODY_HEADER); Buffer bytesOut = new Buffer(); while (!body.exhausted()) { long chunkSize = Math.min(body.size(), maxChunkSize); bytesOut.writeHexadecimalUnsignedLong(chunkSize); bytesOut.writeUtf8("\r\n"); bytesOut.write(body, chunkSize); bytesOut.writeUtf8("\r\n"); } bytesOut.writeUtf8("0\r\n"); // Last chunk. Trailers follow! this.body = bytesOut; return this; }
static String percentDecode(String encoded, int pos, int limit, boolean plusIsSpace) { for (int i = pos; i < limit; i++) { char c = encoded.charAt(i); if (c == '%' || (c == '+' && plusIsSpace)) { // Slow path: the character at i requires decoding! Buffer out = new Buffer(); out.writeUtf8(encoded, pos, i); percentDecode(out, encoded, i, limit, plusIsSpace); return out.readUtf8(); } } // Fast path: no characters in [pos..limit) required decoding. return encoded.substring(pos, limit); }