Refine search
public RealWebSocket(Request request, WebSocketListener listener, Random random, long pingIntervalMillis) { if (!"GET".equals(request.method())) { throw new IllegalArgumentException("Request must be GET: " + request.method()); } this.originalRequest = request; this.listener = listener; this.random = random; this.pingIntervalMillis = pingIntervalMillis; byte[] nonce = new byte[16]; random.nextBytes(nonce); this.key = ByteString.of(nonce).base64(); this.writerRunnable = () -> { try { while (writeOneFrame()) { } } catch (IOException e) { failWebSocket(e, null); } }; }
public synchronized void connectionPreface() throws IOException { if (closed) throw new IOException("closed"); if (!client) return; // Nothing to write; servers don't send connection headers! if (logger.isLoggable(FINE)) { logger.fine(format(">> CONNECTION %s", CONNECTION_PREFACE.hex())); } sink.write(CONNECTION_PREFACE.toByteArray()); sink.flush(); }
private List<Certificate> readCertificateList(BufferedSource source) throws IOException { int length = readInt(source); if (length == -1) return Collections.emptyList(); // OkHttp v1.2 used -1 to indicate null. try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); List<Certificate> result = new ArrayList<>(length); for (int i = 0; i < length; i++) { String line = source.readUtf8LineStrict(); Buffer bytes = new Buffer(); bytes.write(ByteString.decodeBase64(line)); result.add(certificateFactory.generateCertificate(bytes.inputStream())); } return result; } catch (CertificateException e) { throw new IOException(e.getMessage()); } }
public static String basic(String username, String password, Charset charset) { String usernameAndPassword = username + ":" + password; String encoded = ByteString.encodeString(usernameAndPassword, charset).base64(); return "Basic " + encoded; } }
public static String acceptHeader(String key) { return ByteString.encodeUtf8(key + WebSocketProtocol.ACCEPT_MAGIC).sha1().base64(); }
@Test public void gunzipWhenCRCIncorrect() { Buffer gzipped = new Buffer(); gzipped.write(gzipHeader); gzipped.write(deflated); gzipped.writeInt(TestUtil.reverseBytes(0x1234567)); // wrong CRC gzipped.write(gzipTrailer.toByteArray(), 3, 4); try { gunzip(gzipped); fail(); } catch (IOException e) { assertEquals("CRC: actual 0x37ad8f8d != expected 0x01234567", e.getMessage()); } }
void writeByteString(ByteString data) throws IOException { if (useCompression && Huffman.get().encodedLength(data) < data.size()) { Buffer huffmanBuffer = new Buffer(); Huffman.get().encode(data, huffmanBuffer); ByteString huffmanBytes = huffmanBuffer.readByteString(); writeInt(huffmanBytes.size(), PREFIX_7_BITS, 0x80); out.write(huffmanBytes); } else { writeInt(data.size(), PREFIX_7_BITS, 0); out.write(data); } }
/** * Creates a relay that reads a recorded stream from {@code file}. * * <p><strong>Warning:</strong> callers to this method must immediately call {@link #newSource} to * create a source and close that when they're done. Otherwise a handle to {@code file} will be * leaked. */ public static Relay read(File file) throws IOException { RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); FileOperator fileOperator = new FileOperator(randomAccessFile.getChannel()); // Read the header. Buffer header = new Buffer(); fileOperator.read(0, header, FILE_HEADER_SIZE); ByteString prefix = header.readByteString(PREFIX_CLEAN.size()); if (!prefix.equals(PREFIX_CLEAN)) throw new IOException("unreadable cache file"); long upstreamSize = header.readLong(); long metadataSize = header.readLong(); // Read the metadata. Buffer metadataBuffer = new Buffer(); fileOperator.read(FILE_HEADER_SIZE + upstreamSize, metadataBuffer, metadataSize); ByteString metadata = metadataBuffer.readByteString(); // Return the result. return new Relay(randomAccessFile, null, upstreamSize, metadata, 0L); }
/** Use DeflaterOutputStream to deflate source. */ private Buffer deflate(ByteString source) throws IOException { Buffer result = new Buffer(); Sink sink = Okio.sink(new DeflaterOutputStream(result.outputStream())); sink.write(new Buffer().write(source), source.size()); sink.close(); return result; }
@Test public void gunzip_withHCRC() throws Exception { CRC32 hcrc = new CRC32(); ByteString gzipHeader = gzipHeaderWithFlags((byte) 0x02); hcrc.update(gzipHeader.toByteArray()); Buffer gzipped = new Buffer(); gzipped.write(gzipHeader); gzipped.writeShort(TestUtil.reverseBytes((short) hcrc.getValue())); // little endian gzipped.write(deflated); gzipped.write(gzipTrailer); assertGzipped(gzipped); }
private Buffer decodeBase64(String s) { return new Buffer().write(ByteString.decodeBase64(s)); }
private void assertUtf8(String string, String expectedHex) throws IOException { Buffer buffer = new Buffer(); ProtoWriter writer = new ProtoWriter(buffer); writer.writeString(string); assertThat(buffer.readByteString().hex()).isEqualTo(expectedHex); assertThat(Utf8.size(string)).isEqualTo(expectedHex.length() / 2); } }
@Test public void accessByteByByte() throws Exception { Buffer buffer = bufferFactory.newBuffer(); try (UnsafeCursor cursor = buffer.readUnsafe()) { byte[] actual = new byte[(int) buffer.size()]; for (int i = 0; i < buffer.size(); i++) { cursor.seek(i); actual[i] = cursor.data[cursor.start]; } assertEquals(ByteString.of(actual), buffer.snapshot()); } }
@Test public void utf8() throws Exception { ByteString byteString = factory.encodeUtf8(bronzeHorseman); assertByteArraysEquals(byteString.toByteArray(), bronzeHorseman.getBytes(Charsets.UTF_8)); assertTrue(byteString.equals(ByteString.of(bronzeHorseman.getBytes(Charsets.UTF_8)))); assertEquals(byteString.utf8(), bronzeHorseman); }
@Test public void rangeEqualsOnlyReadsUntilMismatch() throws IOException { assumeTrue(factory == Factory.ONE_BYTE_AT_A_TIME_BUFFERED_SOURCE); // Other sources read in chunks anyway. sink.writeUtf8("A man, a plan, a canal. Panama."); sink.emit(); assertFalse(source.rangeEquals(0, ByteString.encodeUtf8("A man."))); assertEquals("A man,", source.getBuffer().readUtf8()); }
public void readConnectionPreface(Handler handler) throws IOException { if (client) { // The client reads the initial SETTINGS frame. if (!nextFrame(true, handler)) { throw ioException("Required SETTINGS preface not received"); } } else { // The server reads the CONNECTION_PREFACE byte string. ByteString connectionPreface = source.readByteString(CONNECTION_PREFACE.size()); if (logger.isLoggable(FINE)) logger.fine(format("<< CONNECTION %s", connectionPreface.hex())); if (!CONNECTION_PREFACE.equals(connectionPreface)) { throw ioException("Expected a connection header but was %s", connectionPreface.utf8()); } } }