okio.ByteString类的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(8.5k)|赞(0)|评价(0)|浏览(506)

本文整理了Java中okio.ByteString类的一些代码示例,展示了ByteString类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ByteString类的具体详情如下:
包路径:okio.ByteString
类名称:ByteString

ByteString介绍

[英]An immutable sequence of bytes.

Byte strings compare lexicographically as a sequence of unsigned bytes. That is, the byte string ff sorts after 00. This is counter to the sort order of the corresponding bytes, where -1 sorts before 0.

Full disclosure: this class provides untrusted input and output streams with raw access to the underlying byte array. A hostile stream implementation could keep a reference to the mutable byte string, violating the immutable guarantee of this class. For this reason a byte string's immutability guarantee cannot be relied upon for security in applets and other environments that run both trusted and untrusted code in the same process.
[中]不可变的字节序列。
字节字符串按字典顺序作为无符号字节序列进行比较。也就是说,字节字符串ff在00之后排序。这是对应字节排序顺序的计数器,其中-1在0之前排序。
完全公开:此类提供了对底层字节数组的原始访问的不受信任的输入和输出流。恶意流实现可能会保留对可变字节字符串的引用,从而违反此类的不可变保证。因此,在小程序和其他在同一进程中同时运行受信任和不受信任代码的环境中,字节字符串的不变性保证不能用于安全性。

代码示例

代码示例来源:origin: square/okhttp

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);
  }
 };
}

代码示例来源:origin: square/okhttp

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();
}

代码示例来源:origin: square/okhttp

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());
 }
}

代码示例来源:origin: square/okhttp

public static String basic(String username, String password, Charset charset) {
  String usernameAndPassword = username + ":" + password;
  String encoded = ByteString.encodeString(usernameAndPassword, charset).base64();
  return "Basic " + encoded;
 }
}

代码示例来源:origin: square/okhttp

int encodedLength(ByteString bytes) {
 long len = 0;
 for (int i = 0; i < bytes.size(); i++) {
  int b = bytes.getByte(i) & 0xFF;
  len += CODE_LENGTHS[b];
 }
 return (int) ((len + 7) >> 3);
}

代码示例来源:origin: square/okhttp

public static String acceptHeader(String key) {
 return ByteString.encodeUtf8(key + WebSocketProtocol.ACCEPT_MAGIC).sha1().base64();
}

代码示例来源:origin: square/okio

@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());
 }
}

代码示例来源:origin: square/okhttp

/** Returns a new response body that transmits {@code content}. */
public static ResponseBody create(@Nullable MediaType contentType, ByteString content) {
 Buffer buffer = new Buffer().write(content);
 return create(contentType, content.size(), buffer);
}

代码示例来源:origin: square/okhttp

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);
 }
}

代码示例来源:origin: square/okhttp

/**
 * 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);
}

代码示例来源:origin: square/okio

/** 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;
}

代码示例来源:origin: square/okio

@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);
}

代码示例来源:origin: square/okio

@Test public void snapshotReportsAccurateSize() {
  Buffer buf = new Buffer().write(new byte[] { 0, 1, 2, 3 });
  assertEquals(1, buf.snapshot(1).size());
 }
}

代码示例来源:origin: square/okio

private Buffer decodeBase64(String s) {
 return new Buffer().write(ByteString.decodeBase64(s));
}

代码示例来源:origin: square/wire

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);
 }
}

代码示例来源:origin: square/okio

@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());
 }
}

代码示例来源:origin: square/okio

@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);
}

代码示例来源:origin: square/okio

@Test public void ofCopyRange() {
 byte[] bytes = "Hello, World!".getBytes(Charsets.UTF_8);
 ByteString byteString = ByteString.of(bytes, 2, 9);
 // Verify that the bytes were copied out.
 bytes[4] = (byte) 'a';
 assertEquals("llo, Worl", byteString.utf8());
}

代码示例来源:origin: square/okio

@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());
}

代码示例来源:origin: square/okhttp

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());
  }
 }
}

相关文章