Search in sources :

Example 96 with Buffer

use of io.servicetalk.buffer.api.Buffer in project servicetalk by apple.

the class DefaultSerializerDeserializationTest method iterableCompletesWithLeftOverData.

@Test
void iterableCompletesWithLeftOverData() {
    Buffer first = mock(Buffer.class);
    Buffer second = mock(Buffer.class);
    final List<Buffer> source = asList(first, second);
    when(deSerializer.deserialize(source)).thenReturn(singletonList("Hello1"));
    when(deSerializer.hasData()).thenReturn(true);
    final SerializationException e = new SerializationException(DELIBERATE_EXCEPTION);
    doThrow(e).when(deSerializer).close();
    final CloseableIterable<String> deserialized = factory.deserialize(source, String.class);
    verify(provider).getDeserializer(String.class);
    verify(deSerializer).deserialize(source);
    verify(deSerializer, times(0)).close();
    final CloseableIterator<String> iterator = deserialized.iterator();
    assertThat("Iterator does not contain data.", iterator.hasNext(), is(true));
    assertThat("Unexpected data received from iterator.", iterator.next(), is("Hello1"));
    try {
        iterator.hasNext();
        Assertions.fail();
    } catch (RuntimeException re) {
        assertThat("Unexpected exception.", re.getCause(), sameInstance(e));
    }
    verify(deSerializer).close();
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer) Test(org.junit.jupiter.api.Test)

Example 97 with Buffer

use of io.servicetalk.buffer.api.Buffer in project servicetalk by apple.

the class Serializer method serialize.

/**
 * Serialize the {@link T} parameter to a {@link Buffer}.
 * @param toSerialize The {@link T} to serialize.
 * @param allocator Used to allocate the buffer to serialize to.
 * @return The results of the serialization.
 */
default Buffer serialize(T toSerialize, BufferAllocator allocator) {
    Buffer b = allocator.newBuffer();
    serialize(toSerialize, allocator, b);
    return b;
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer)

Example 98 with Buffer

use of io.servicetalk.buffer.api.Buffer in project servicetalk by apple.

the class HttpReporterTest method verifyRequest.

private List<Span> verifyRequest(final Codec codec, final HttpRequest request) {
    SpanBytesDecoder decoder;
    switch(codec) {
        case JSON_V1:
            assertThat("Unexpected path.", request.path(), equalTo(V1_PATH));
            decoder = SpanBytesDecoder.JSON_V1;
            break;
        case JSON_V2:
            assertThat("Unexpected path.", request.path(), equalTo(V2_PATH));
            decoder = SpanBytesDecoder.JSON_V2;
            break;
        case THRIFT:
            assertThat("Unexpected path.", request.path(), equalTo(V2_PATH));
            decoder = SpanBytesDecoder.THRIFT;
            break;
        case PROTO3:
            assertThat("Unexpected path.", request.path(), equalTo(V2_PATH));
            decoder = SpanBytesDecoder.PROTO3;
            break;
        default:
            throw new IllegalArgumentException("Unknown codec: " + codec);
    }
    Buffer buffer = request.payloadBody();
    byte[] data = new byte[buffer.readableBytes()];
    buffer.readBytes(data);
    List<Span> decoded = new ArrayList<>();
    decoder.decodeList(data, decoded);
    return decoded;
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer) SpanBytesDecoder(zipkin2.codec.SpanBytesDecoder) ArrayList(java.util.ArrayList) SpanUtils.verifySpan(io.servicetalk.opentracing.zipkin.publisher.reporter.SpanUtils.verifySpan) Span(zipkin2.Span) SpanUtils.newSpan(io.servicetalk.opentracing.zipkin.publisher.reporter.SpanUtils.newSpan)

Example 99 with Buffer

use of io.servicetalk.buffer.api.Buffer in project servicetalk by apple.

the class ProtoBufSerializationProviderBuilder method build0.

@SuppressWarnings("unchecked")
private void build0() {
    for (Map.Entry<Class<? extends MessageLite>, Parser<? extends MessageLite>> entry : types.entrySet()) {
        Class<MessageLite> messageType = (Class<MessageLite>) entry.getKey();
        Parser<MessageLite> parser = (Parser<MessageLite>) entry.getValue();
        Map<ContentCodec, HttpSerializer> serializersForType = new HashMap<>();
        Map<ContentCodec, HttpDeserializer> deserializersForType = new HashMap<>();
        for (ContentCodec codec : supportedCodings) {
            DefaultSerializer serializer = new DefaultSerializer(new ProtoBufSerializationProvider<>(messageType, codec, parser));
            HttpSerializer<MessageLite> httpSerializer = new ProtoHttpSerializer<>(serializer, codec, messageType);
            serializersForType.put(codec, httpSerializer);
            deserializersForType.put(codec, new HttpDeserializer<MessageLite>() {

                @Override
                public MessageLite deserialize(final HttpHeaders headers, final Buffer payload) {
                    return serializer.deserializeAggregatedSingle(payload, messageType);
                }

                @Override
                public BlockingIterable<MessageLite> deserialize(final HttpHeaders headers, final BlockingIterable<Buffer> payload) {
                    return serializer.deserialize(payload, messageType);
                }

                @Override
                public Publisher<MessageLite> deserialize(final HttpHeaders headers, final Publisher<Buffer> payload) {
                    return serializer.deserialize(payload, messageType);
                }
            });
        }
        serializers.put(messageType, serializersForType);
        deserializers.put(messageType, deserializersForType);
    }
}
Also used : HttpHeaders(io.servicetalk.http.api.HttpHeaders) HashMap(java.util.HashMap) DefaultSerializer(io.servicetalk.serialization.api.DefaultSerializer) HttpDeserializer(io.servicetalk.http.api.HttpDeserializer) BlockingIterable(io.servicetalk.concurrent.BlockingIterable) HttpSerializer(io.servicetalk.http.api.HttpSerializer) Buffer(io.servicetalk.buffer.api.Buffer) Publisher(io.servicetalk.concurrent.api.Publisher) MessageLite(com.google.protobuf.MessageLite) ContentCodec(io.servicetalk.encoding.api.ContentCodec) Parser(com.google.protobuf.Parser) HashMap(java.util.HashMap) Map(java.util.Map) Collections.unmodifiableMap(java.util.Collections.unmodifiableMap)

Example 100 with Buffer

use of io.servicetalk.buffer.api.Buffer in project servicetalk by apple.

the class BeforeFinallyHttpOperatorTest method cancelWhileDeliveringPayload.

@Test
void cancelWhileDeliveringPayload() {
    TestPublisher<Buffer> payload = new TestPublisher.Builder<Buffer>().disableAutoOnSubscribe().build();
    Subscription payloadSubscription = mock(Subscription.class);
    LegacyTestSingle<StreamingHttpResponse> responseSingle = new LegacyTestSingle<>(true);
    final ResponseSubscriber subscriber = new ResponseSubscriber();
    toSource(responseSingle.liftSync(new BeforeFinallyHttpOperator(beforeFinally, true))).subscribe(subscriber);
    assertThat("onSubscribe not called.", subscriber.cancellable, is(notNullValue()));
    responseSingle.onSuccess(reqRespFactory.ok().payloadBody(payload));
    verifyNoInteractions(beforeFinally);
    responseSingle.verifyNotCancelled();
    subscriber.verifyResponseReceived();
    assert subscriber.response != null;
    BlockingQueue<Buffer> receivedPayload = new LinkedBlockingDeque<>();
    AtomicReference<TerminalNotification> subscriberTerminal = new AtomicReference<>();
    toSource(subscriber.response.payloadBody()).subscribe(new PublisherSource.Subscriber<Buffer>() {

        @Nullable
        private Subscription subscription;

        @Override
        public void onSubscribe(final Subscription subscription) {
            this.subscription = subscription;
            subscription.request(MAX_VALUE);
        }

        @Override
        public void onNext(@Nullable final Buffer buffer) {
            assert buffer != null;
            receivedPayload.add(buffer);
            if (receivedPayload.size() == 1) {
                assert subscription != null;
                subscription.cancel();
                // intentionally cancel two times to make sure it's idempotent
                subscription.cancel();
                verify(payloadSubscription, Mockito.never()).cancel();
                verifyNoMoreInteractions(beforeFinally);
                payload.onNext(EMPTY_BUFFER);
            }
            verify(payloadSubscription, Mockito.never()).cancel();
            verifyNoMoreInteractions(beforeFinally);
        // Cancel will be propagated after this method returns
        }

        @Override
        public void onError(final Throwable t) {
            subscriberTerminal.set(TerminalNotification.error(t));
        }

        @Override
        public void onComplete() {
            subscriberTerminal.set(TerminalNotification.complete());
        }
    });
    payload.onSubscribe(payloadSubscription);
    verify(payloadSubscription, Mockito.never()).cancel();
    payload.onNext(EMPTY_BUFFER);
    verify(payloadSubscription).cancel();
    verify(beforeFinally).cancel();
    assertThat("Unexpected payload body items", receivedPayload, contains(EMPTY_BUFFER, EMPTY_BUFFER));
    assertThat("Unexpected payload body termination", subscriberTerminal.get(), is(nullValue()));
    verifyNoMoreInteractions(beforeFinally);
}
Also used : Buffer(io.servicetalk.buffer.api.Buffer) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) PublisherSource(io.servicetalk.concurrent.PublisherSource) TerminalNotification(io.servicetalk.concurrent.internal.TerminalNotification) AtomicReference(java.util.concurrent.atomic.AtomicReference) TestSubscription(io.servicetalk.concurrent.api.TestSubscription) Subscription(io.servicetalk.concurrent.PublisherSource.Subscription) StreamingHttpResponse(io.servicetalk.http.api.StreamingHttpResponse) Nullable(javax.annotation.Nullable) LegacyTestSingle(io.servicetalk.concurrent.api.LegacyTestSingle) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Aggregations

Buffer (io.servicetalk.buffer.api.Buffer)243 Test (org.junit.jupiter.api.Test)117 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)83 MethodSource (org.junit.jupiter.params.provider.MethodSource)56 StreamingHttpResponse (io.servicetalk.http.api.StreamingHttpResponse)39 StreamingHttpRequest (io.servicetalk.http.api.StreamingHttpRequest)30 StreamingHttpClient (io.servicetalk.http.api.StreamingHttpClient)29 HttpHeaders (io.servicetalk.http.api.HttpHeaders)26 Nullable (javax.annotation.Nullable)24 List (java.util.List)23 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)22 Publisher (io.servicetalk.concurrent.api.Publisher)21 CountDownLatch (java.util.concurrent.CountDownLatch)21 AtomicReference (java.util.concurrent.atomic.AtomicReference)20 CompositeBuffer (io.servicetalk.buffer.api.CompositeBuffer)18 Single (io.servicetalk.concurrent.api.Single)18 InputStream (java.io.InputStream)18 ArrayList (java.util.ArrayList)17 MatcherAssert.assertThat (org.hamcrest.MatcherAssert.assertThat)16 BufferAllocator (io.servicetalk.buffer.api.BufferAllocator)15