Search in sources :

Example 56 with Callback

use of com.linkedin.common.callback.Callback in project rest.li by linkedin.

the class ServerStreamCompressionFilter method onStreamResponse.

/**
   * Optionally compresses outgoing response
   * */
@Override
public void onStreamResponse(final StreamResponse res, final RequestContext requestContext, final Map<String, String> wireAttrs, final NextFilter<StreamRequest, StreamResponse> nextFilter) {
    StreamResponse response = res;
    try {
        String responseCompression = (String) requestContext.getLocalAttr(HttpConstants.ACCEPT_ENCODING);
        if (responseCompression == null) {
            throw new CompressionException(HttpConstants.ACCEPT_ENCODING + " not in local attribute.");
        }
        List<AcceptEncoding> parsedEncodings = AcceptEncoding.parseAcceptEncodingHeader(responseCompression, _supportedEncoding);
        StreamEncodingType selectedEncoding = AcceptEncoding.chooseBest(parsedEncodings);
        //Check if there exists an acceptable encoding
        if (selectedEncoding == null) {
            //Not acceptable encoding status
            response = new StreamResponseBuilder().setStatus(HttpConstants.NOT_ACCEPTABLE).build(EntityStreams.emptyStream());
        } else if (selectedEncoding != StreamEncodingType.IDENTITY) {
            final int threshold = (Integer) requestContext.getLocalAttr(HttpConstants.HEADER_RESPONSE_COMPRESSION_THRESHOLD);
            final StreamingCompressor compressor = selectedEncoding.getCompressor(_executor);
            PartialReader reader = new PartialReader(threshold, new Callback<EntityStream[]>() {

                @Override
                public void onError(Throwable ex) {
                    nextFilter.onError(ex, requestContext, wireAttrs);
                }

                @Override
                public void onSuccess(EntityStream[] results) {
                    if (// entity stream is less than threshold
                    results.length == 1) {
                        StreamResponse response = res.builder().build(results[0]);
                        nextFilter.onResponse(response, requestContext, wireAttrs);
                    } else {
                        EntityStream compressedStream = compressor.deflate(EntityStreams.newEntityStream(new CompositeWriter(results)));
                        StreamResponseBuilder builder = res.builder();
                        // remove original content-length header if presents.
                        if (builder.getHeader(HttpConstants.CONTENT_LENGTH) != null) {
                            Map<String, String> headers = stripHeaders(builder.getHeaders(), HttpConstants.CONTENT_LENGTH);
                            builder.setHeaders(headers);
                        }
                        StreamResponse response = builder.addHeaderValue(HttpConstants.CONTENT_ENCODING, compressor.getContentEncodingName()).build(compressedStream);
                        nextFilter.onResponse(response, requestContext, wireAttrs);
                    }
                }
            });
            res.getEntityStream().setReader(reader);
            return;
        }
    } catch (CompressionException e) {
        LOG.error(e.getMessage(), e.getCause());
    }
    nextFilter.onResponse(response, requestContext, wireAttrs);
}
Also used : StreamResponseBuilder(com.linkedin.r2.message.stream.StreamResponseBuilder) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) CompositeWriter(com.linkedin.r2.message.stream.entitystream.CompositeWriter) PartialReader(com.linkedin.r2.filter.compression.streaming.PartialReader) StreamEncodingType(com.linkedin.r2.filter.compression.streaming.StreamEncodingType) EntityStream(com.linkedin.r2.message.stream.entitystream.EntityStream) Callback(com.linkedin.common.callback.Callback) StreamingCompressor(com.linkedin.r2.filter.compression.streaming.StreamingCompressor) AcceptEncoding(com.linkedin.r2.filter.compression.streaming.AcceptEncoding)

Example 57 with Callback

use of com.linkedin.common.callback.Callback in project rest.li by linkedin.

the class TestStreamRequest method testErrorWriter.

@Test
public void testErrorWriter() throws Exception {
    for (Client client : clients()) {
        final long totalBytes = SMALL_BYTES_NUM;
        EntityStream entityStream = EntityStreams.newEntityStream(new ErrorWriter(totalBytes, BYTE));
        StreamRequestBuilder builder = new StreamRequestBuilder(Bootstrap.createHttpURI(PORT, FOOBAR_URI));
        StreamRequest request = builder.setMethod("POST").build(entityStream);
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicReference<Throwable> error = new AtomicReference<Throwable>();
        Callback<StreamResponse> callback = new Callback<StreamResponse>() {

            @Override
            public void onError(Throwable e) {
                error.set(e);
                latch.countDown();
            }

            @Override
            public void onSuccess(StreamResponse result) {
                latch.countDown();
            }
        };
        client.streamRequest(request, callback);
        latch.await();
        Assert.assertNotNull(error.get());
    }
}
Also used : StreamResponse(com.linkedin.r2.message.stream.StreamResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) StreamRequestBuilder(com.linkedin.r2.message.stream.StreamRequestBuilder) StreamRequest(com.linkedin.r2.message.stream.StreamRequest) EntityStream(com.linkedin.r2.message.stream.entitystream.EntityStream) Callback(com.linkedin.common.callback.Callback) Client(com.linkedin.r2.transport.common.Client) Test(org.testng.annotations.Test)

Example 58 with Callback

use of com.linkedin.common.callback.Callback in project rest.li by linkedin.

the class TestStreamRequest method expectErrorCallback.

private static Callback<StreamResponse> expectErrorCallback(final CountDownLatch latch, final AtomicInteger status) {
    return new Callback<StreamResponse>() {

        @Override
        public void onError(Throwable e) {
            if (e instanceof StreamException) {
                StreamResponse errorResponse = ((StreamException) e).getResponse();
                status.set(errorResponse.getStatus());
            }
            latch.countDown();
        }

        @Override
        public void onSuccess(StreamResponse result) {
            latch.countDown();
            throw new RuntimeException("Should have failed with 404");
        }
    };
}
Also used : Callback(com.linkedin.common.callback.Callback) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) StreamException(com.linkedin.r2.message.stream.StreamException)

Example 59 with Callback

use of com.linkedin.common.callback.Callback in project rest.li by linkedin.

the class MultiplexedRequestBuilder method buildParallel.

private MultiplexedRequest buildParallel() throws RestLiEncodingException {
    Map<Integer, Callback<RestResponse>> callbacks = new HashMap<Integer, Callback<RestResponse>>(_requestsWithCallbacks.size());
    IndividualRequestMap individualRequests = new IndividualRequestMap(_requestsWithCallbacks.size());
    // Dependent requests map is always empty
    IndividualRequestMap dependentRequests = new IndividualRequestMap();
    for (int i = 0; i < _requestsWithCallbacks.size(); i++) {
        RequestWithCallback<?> requestWithCallback = _requestsWithCallbacks.get(i);
        IndividualRequest individualRequest = toIndividualRequest(requestWithCallback.getRequest(), dependentRequests);
        individualRequests.put(Integer.toString(i), individualRequest);
        callbacks.put(i, wrapCallback(requestWithCallback));
    }
    return toMultiplexedRequest(individualRequests, callbacks);
}
Also used : IndividualRequestMap(com.linkedin.restli.common.multiplexer.IndividualRequestMap) IndividualRequest(com.linkedin.restli.common.multiplexer.IndividualRequest) Callback(com.linkedin.common.callback.Callback) HashMap(java.util.HashMap) RestResponse(com.linkedin.r2.message.rest.RestResponse)

Example 60 with Callback

use of com.linkedin.common.callback.Callback in project rest.li by linkedin.

the class MultiplexedRequestBuilder method buildSequential.

private MultiplexedRequest buildSequential() throws RestLiEncodingException {
    Map<Integer, Callback<RestResponse>> callbacks = new HashMap<Integer, Callback<RestResponse>>(_requestsWithCallbacks.size());
    // Dependent requests - requests which are dependent on the current request (executed after the current request)
    IndividualRequestMap dependentRequests = new IndividualRequestMap();
    // We start with the last request in the list and proceed backwards because sequential ordering is built using reverse dependencies
    for (int i = _requestsWithCallbacks.size() - 1; i >= 0; i--) {
        RequestWithCallback<?> requestWithCallback = _requestsWithCallbacks.get(i);
        IndividualRequest individualRequest = toIndividualRequest(requestWithCallback.getRequest(), dependentRequests);
        dependentRequests = new IndividualRequestMap();
        dependentRequests.put(Integer.toString(i), individualRequest);
        callbacks.put(i, wrapCallback(requestWithCallback));
    }
    return toMultiplexedRequest(dependentRequests, callbacks);
}
Also used : IndividualRequestMap(com.linkedin.restli.common.multiplexer.IndividualRequestMap) IndividualRequest(com.linkedin.restli.common.multiplexer.IndividualRequest) Callback(com.linkedin.common.callback.Callback) HashMap(java.util.HashMap) RestResponse(com.linkedin.r2.message.rest.RestResponse)

Aggregations

Callback (com.linkedin.common.callback.Callback)95 Test (org.testng.annotations.Test)64 AfterTest (org.testng.annotations.AfterTest)43 BeforeTest (org.testng.annotations.BeforeTest)43 RequestContext (com.linkedin.r2.message.RequestContext)37 RestResponse (com.linkedin.r2.message.rest.RestResponse)34 ByteString (com.linkedin.data.ByteString)29 RestRequest (com.linkedin.r2.message.rest.RestRequest)28 StreamResponse (com.linkedin.r2.message.stream.StreamResponse)28 AsyncStatusCollectionResource (com.linkedin.restli.server.twitter.AsyncStatusCollectionResource)28 URI (java.net.URI)28 RestLiCallback (com.linkedin.restli.internal.server.RestLiCallback)26 FilterChainCallback (com.linkedin.restli.internal.server.filter.FilterChainCallback)26 ResourceMethodDescriptor (com.linkedin.restli.internal.server.model.ResourceMethodDescriptor)26 ResourceModel (com.linkedin.restli.internal.server.model.ResourceModel)26 RequestExecutionCallback (com.linkedin.restli.server.RequestExecutionCallback)26 RestLiTestHelper.buildResourceModel (com.linkedin.restli.server.test.RestLiTestHelper.buildResourceModel)26 EasyMock.anyObject (org.easymock.EasyMock.anyObject)26 StreamRequest (com.linkedin.r2.message.stream.StreamRequest)25 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)22