Search in sources :

Example 1 with ByteString

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);
}
Also used : Buffer(okio.Buffer) ByteString(okio.ByteString) GzipSink(okio.GzipSink) Test(org.junit.Test)

Example 2 with ByteString

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;
}
Also used : ByteString(okio.ByteString)

Example 3 with ByteString

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);
    }
}
Also used : ByteString(okio.ByteString) BufferedSink(okio.BufferedSink) ByteString(okio.ByteString)

Example 4 with ByteString

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;
        }
    }
}
Also used : Buffer(okio.Buffer) ByteString(okio.ByteString)

Example 5 with ByteString

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');
            }
        }
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) ByteString(okio.ByteString) GzipSink(okio.GzipSink) Request(okhttp3.Request) BufferedSink(okio.BufferedSink) ByteString(okio.ByteString) Response(okhttp3.Response) Sink(okio.Sink) GzipSink(okio.GzipSink) BufferedSink(okio.BufferedSink) TreeSet(java.util.TreeSet) File(java.io.File) BufferedSource(okio.BufferedSource)

Aggregations

ByteString (okio.ByteString)59 Test (org.junit.Test)37 Buffer (okio.Buffer)26 MockResponse (okhttp3.mockwebserver.MockResponse)11 ProtocolException (java.net.ProtocolException)5 IOException (java.io.IOException)4 OneField (com.squareup.wire.protos.edgecases.OneField)3 EOFException (java.io.EOFException)3 BufferedSink (okio.BufferedSink)3 BufferedSource (okio.BufferedSource)3 AllTypes (com.squareup.wire.protos.alltypes.AllTypes)2 Person (com.squareup.wire.protos.person.Person)2 ArrayList (java.util.ArrayList)2 Headers (okhttp3.Headers)2 Request (okhttp3.Request)2 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)2 GzipSink (okio.GzipSink)2 Ignore (org.junit.Ignore)2 Phone (retrofit2.converter.protobuf.PhoneProtos.Phone)2 GsonBuilder (com.google.gson.GsonBuilder)1