use of okio.ByteString in project zipkin by openzipkin.
the class ZipkinRuleTest method gzippedSpans.
@Test
public void gzippedSpans() throws IOException {
byte[] spansInJson = Codec.JSON.writeSpans(TRACE);
Buffer sink = new Buffer();
GzipSink gzipSink = new GzipSink(sink);
gzipSink.write(new Buffer().write(spansInJson), spansInJson.length);
gzipSink.close();
ByteString gzippedJson = sink.readByteString();
client.newCall(new Request.Builder().url(zipkin.httpUrl() + "/api/v1/spans").addHeader("Content-Encoding", "gzip").post(RequestBody.create(MediaType.parse("application/json"), gzippedJson)).build()).execute();
assertThat(zipkin.getTraces()).containsOnly(TRACE);
assertThat(zipkin.collectorMetrics().bytes()).isEqualTo(spansInJson.length);
}
use of okio.ByteString in project okhttp by square.
the class RealWebSocket method close.
synchronized boolean close(int code, String reason, long cancelAfterCloseMillis) {
validateCloseCode(code);
ByteString reasonBytes = null;
if (reason != null) {
reasonBytes = ByteString.encodeUtf8(reason);
if (reasonBytes.size() > CLOSE_MESSAGE_MAX) {
throw new IllegalArgumentException("reason.size() > " + CLOSE_MESSAGE_MAX + ": " + reason);
}
}
if (failed || enqueuedClose)
return false;
// Immediately prevent further frames from being enqueued.
enqueuedClose = true;
// Enqueue the close frame.
messageAndCloseQueue.add(new Close(code, reasonBytes, cancelAfterCloseMillis));
runWriter();
return true;
}
use of okio.ByteString in project okhttp by square.
the class RealWebSocket method writeOneFrame.
/**
* Attempts to remove a single frame from a queue and send it. This prefers to write urgent pongs
* before less urgent messages and close frames. For example it's possible that a caller will
* enqueue messages followed by pongs, but this sends pongs followed by messages. Pongs are always
* written in the order they were enqueued.
*
* <p>If a frame cannot be sent - because there are none enqueued or because the web socket is not
* connected - this does nothing and returns false. Otherwise this returns true and the caller
* should immediately invoke this method again until it returns false.
*
* <p>This method may only be invoked by the writer thread. There may be only thread invoking this
* method at a time.
*/
boolean writeOneFrame() throws IOException {
WebSocketWriter writer;
ByteString pong;
Object messageOrClose = null;
int receivedCloseCode = -1;
String receivedCloseReason = null;
Streams streamsToClose = null;
synchronized (RealWebSocket.this) {
if (failed) {
// Failed web socket.
return false;
}
writer = this.writer;
pong = pongQueue.poll();
if (pong == null) {
messageOrClose = messageAndCloseQueue.poll();
if (messageOrClose instanceof Close) {
receivedCloseCode = this.receivedCloseCode;
receivedCloseReason = this.receivedCloseReason;
if (receivedCloseCode != -1) {
streamsToClose = this.streams;
this.streams = null;
this.executor.shutdown();
} else {
// When we request a graceful close also schedule a cancel of the websocket.
cancelFuture = executor.schedule(new CancelRunnable(), ((Close) messageOrClose).cancelAfterCloseMillis, MILLISECONDS);
}
} else if (messageOrClose == null) {
// The queue is exhausted.
return false;
}
}
}
try {
if (pong != null) {
writer.writePong(pong);
} else if (messageOrClose instanceof Message) {
ByteString data = ((Message) messageOrClose).data;
BufferedSink sink = Okio.buffer(writer.newMessageSink(((Message) messageOrClose).formatOpcode, data.size()));
sink.write(data);
sink.close();
synchronized (this) {
queueSize -= data.size();
}
} else if (messageOrClose instanceof Close) {
Close close = (Close) messageOrClose;
writer.writeClose(close.code, close.reason);
// We closed the writer: now both reader and writer are closed.
if (streamsToClose != null) {
listener.onClosed(this, receivedCloseCode, receivedCloseReason);
}
} else {
throw new AssertionError();
}
return true;
} finally {
closeQuietly(streamsToClose);
}
}
use of okio.ByteString in project okhttp by square.
the class WebSocketWriter method writeClose.
/**
* Send a close frame with optional code and reason.
*
* @param code Status code as defined by <a
* href="http://tools.ietf.org/html/rfc6455#section-7.4">Section 7.4 of RFC 6455</a> or {@code 0}.
* @param reason Reason for shutting down or {@code null}.
*/
void writeClose(int code, ByteString reason) throws IOException {
ByteString payload = ByteString.EMPTY;
if (code != 0 || reason != null) {
if (code != 0) {
validateCloseCode(code);
}
Buffer buffer = new Buffer();
buffer.writeShort(code);
if (reason != null) {
buffer.write(reason);
}
payload = buffer.readByteString();
}
synchronized (this) {
try {
writeControlFrameSynchronized(OPCODE_CONTROL_CLOSE, payload);
} finally {
writerClosed = true;
}
}
}
use of okio.ByteString in project okhttp by square.
the class PublicSuffixListGenerator method main.
public static void main(String... args) throws IOException {
OkHttpClient client = new OkHttpClient.Builder().build();
Request request = new Request.Builder().url("https://publicsuffix.org/list/public_suffix_list.dat").build();
SortedSet<ByteString> sortedRules = new TreeSet<>();
SortedSet<ByteString> sortedExceptionRules = new TreeSet<>();
try (Response response = client.newCall(request).execute()) {
BufferedSource source = response.body().source();
int totalRuleBytes = 0;
int totalExceptionRuleBytes = 0;
while (!source.exhausted()) {
String line = source.readUtf8LineStrict();
if (line.trim().isEmpty() || line.startsWith("//"))
continue;
if (line.contains(WILDCARD_CHAR)) {
assertWildcardRule(line);
}
ByteString rule = ByteString.encodeUtf8(line);
if (rule.startsWith(EXCEPTION_RULE_MARKER)) {
rule = rule.substring(1);
// We use '\n' for end of value.
totalExceptionRuleBytes += rule.size() + 1;
sortedExceptionRules.add(rule);
} else {
// We use '\n' for end of value.
totalRuleBytes += rule.size() + 1;
sortedRules.add(rule);
}
}
File resources = new File(OKHTTP_RESOURCE_DIR);
if (!resources.mkdirs() && !resources.exists()) {
throw new RuntimeException("Unable to create resource directory!");
}
Sink fileSink = Okio.sink(new File(resources, PublicSuffixDatabase.PUBLIC_SUFFIX_RESOURCE));
try (BufferedSink sink = Okio.buffer(new GzipSink(fileSink))) {
sink.writeInt(totalRuleBytes);
for (ByteString domain : sortedRules) {
sink.write(domain).writeByte('\n');
}
sink.writeInt(totalExceptionRuleBytes);
for (ByteString domain : sortedExceptionRules) {
sink.write(domain).writeByte('\n');
}
}
}
}
Aggregations