Search in sources :

Example 11 with Callback

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

the class ServerQueryTunnelFilter method onStreamRequest.

@Override
public void onStreamRequest(final StreamRequest req, final RequestContext requestContext, final Map<String, String> wireAttrs, final NextFilter<StreamRequest, StreamResponse> nextFilter) {
    Callback<StreamRequest> callback = new Callback<StreamRequest>() {

        @Override
        public void onError(Throwable e) {
            if (e instanceof MessagingException || e instanceof URISyntaxException) {
                RestResponse errorResponse = RestStatus.responseForStatus(RestStatus.BAD_REQUEST, e.toString());
                nextFilter.onResponse(Messages.toStreamResponse(errorResponse), requestContext, wireAttrs);
            } else {
                nextFilter.onError(e, requestContext, wireAttrs);
            }
        }

        @Override
        public void onSuccess(StreamRequest newReq) {
            nextFilter.onRequest(newReq, requestContext, wireAttrs);
        }
    };
    // the entire request would be buffered in memory if decoding is needed
    // this usually is not a problem as request with extremely query parameters is usually get request with no body
    QueryTunnelUtil.decode(req, requestContext, callback);
}
Also used : Callback(com.linkedin.common.callback.Callback) MessagingException(javax.mail.MessagingException) RestResponse(com.linkedin.r2.message.rest.RestResponse) URISyntaxException(java.net.URISyntaxException) StreamRequest(com.linkedin.r2.message.stream.StreamRequest)

Example 12 with Callback

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

the class SimpleLoggingFilter method trace.

private void trace(final String method, final StreamResponse response, final Map<String, String> wireAttrs, final RequestContext requestContext) {
    final URI requestUri = (URI) requestContext.getLocalAttr(REQUEST_URI);
    final String requestMethod = (String) requestContext.getLocalAttr(REQUEST_METHOD);
    Callback<Integer> callback = new Callback<Integer>() {

        @Override
        public void onError(Throwable e) {
            _log.warn("Cannot get the length of the response", e);
        }

        @Override
        public void onSuccess(Integer result) {
            _log.debug(buildLogMessage(method, "response", formatResponse(response, result, requestUri, requestMethod), wireAttrs, requestContext));
        }
    };
    response.getEntityStream().addObserver(new LengthObserver(callback));
}
Also used : Callback(com.linkedin.common.callback.Callback) ByteString(com.linkedin.data.ByteString) URI(java.net.URI)

Example 13 with Callback

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

the class AsyncPoolImpl method create.

/**
   * DO NOT call this method while holding the lock!  It invokes user code.
   */
private void create() {
    trc("initiating object creation");
    _rateLimiter.submit(new Task() {

        @Override
        public void run(final SimpleCallback callback) {
            _lifecycle.create(new Callback<T>() {

                @Override
                public void onSuccess(T t) {
                    synchronized (_lock) {
                        _statsTracker.incrementCreated();
                        _lastCreateError = null;
                    }
                    add(t);
                    callback.onDone();
                }

                @Override
                public void onError(final Throwable e) {
                    _rateLimiter.incrementPeriod();
                    // Note we drain all waiters and cancel all pending creates if a create fails.
                    // When a create fails, rate-limiting logic will be applied.  In this case,
                    // we may be initiating creations at a lower rate than incoming requests.  While
                    // creations are suppressed, it is better to deny all waiters and let them see
                    // the real reason (this exception) rather than keep them around to eventually
                    // get an unhelpful timeout error
                    final Collection<Callback<T>> waitersDenied;
                    final Collection<Task> cancelledCreate = _rateLimiter.cancelPendingTasks();
                    boolean create;
                    synchronized (_lock) {
                        _statsTracker.incrementCreateErrors();
                        _lastCreateError = e;
                        create = objectDestroyed(1 + cancelledCreate.size());
                        if (!_waiters.isEmpty()) {
                            waitersDenied = cancelWaiters();
                        } else {
                            waitersDenied = Collections.<Callback<T>>emptyList();
                        }
                    }
                    for (Callback<T> denied : waitersDenied) {
                        try {
                            denied.onError(e);
                        } catch (Exception ex) {
                            LOG.error("Encountered error while invoking error waiter callback", ex);
                        }
                    }
                    if (create) {
                        create();
                    }
                    LOG.error(_poolName + ": object creation failed", e);
                    callback.onDone();
                }
            });
        }
    });
}
Also used : Task(com.linkedin.r2.transport.http.client.RateLimiter.Task) SimpleCallback(com.linkedin.common.callback.SimpleCallback) Callback(com.linkedin.common.callback.Callback) SimpleCallback(com.linkedin.common.callback.SimpleCallback) SizeLimitExceededException(com.linkedin.r2.SizeLimitExceededException)

Example 14 with Callback

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

the class AbstractPerfServerFactory method createPureStreamServer.

public Server createPureStreamServer(int port, URI echoUri, final int msg_size, int numHeaders, int headerSize) {
    String headerContent = new StringGenerator(headerSize).nextMessage();
    StreamRequestHandler handler = new StreamRequestHandler() {

        @Override
        public void handleRequest(StreamRequest request, RequestContext requestContext, final Callback<StreamResponse> callback) {
            request.getEntityStream().setReader(new PerfStreamReader<None>(new Callback<None>() {

                @Override
                public void onError(Throwable e) {
                    callback.onError(e);
                }

                @Override
                public void onSuccess(None result) {
                    StreamResponseBuilder builder = new StreamResponseBuilder();
                    for (int i = 0; i < numHeaders; i++) {
                        builder.setHeader(STATIC_HEADER_PREFIX + i, headerContent);
                    }
                    callback.onSuccess(builder.build(EntityStreams.newEntityStream(new PerfStreamWriter(msg_size))));
                }
            }, None.none()));
        }
    };
    final TransportDispatcher dispatcher = new TransportDispatcherBuilder().addStreamHandler(echoUri, handler).build();
    return createServer(port, dispatcher, true);
}
Also used : StreamResponseBuilder(com.linkedin.r2.message.stream.StreamResponseBuilder) TransportDispatcher(com.linkedin.r2.transport.common.bridge.server.TransportDispatcher) StreamRequest(com.linkedin.r2.message.stream.StreamRequest) PerfStreamWriter(test.r2.perf.PerfStreamWriter) StreamRequestHandler(com.linkedin.r2.transport.common.StreamRequestHandler) Callback(com.linkedin.common.callback.Callback) StringGenerator(test.r2.perf.StringGenerator) RequestContext(com.linkedin.r2.message.RequestContext) None(com.linkedin.common.util.None) TransportDispatcherBuilder(com.linkedin.r2.transport.common.bridge.server.TransportDispatcherBuilder)

Example 15 with Callback

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

the class TestMultiplexedCallback method testMixed.

@Test
public void testMixed() throws Exception {
    FutureCallback<RestResponse> callback1 = new FutureCallback<RestResponse>();
    FutureCallback<RestResponse> callback2 = new FutureCallback<RestResponse>();
    ImmutableMap<Integer, Callback<RestResponse>> individualCallbacks = ImmutableMap.<Integer, Callback<RestResponse>>of(ID1, callback1, ID2, callback2);
    FutureCallback<MultiplexedResponse> aggregatedCallback = new FutureCallback<MultiplexedResponse>();
    TestRecord entity1 = fakeEntity(ID1);
    IndividualResponse ir1 = fakeIndividualResponse(entity1);
    IndividualResponse ir2 = fakeIndividualErrorResponse();
    MultiplexedResponseContent responseContent = new MultiplexedResponseContent().setResponses(new IndividualResponseMap(ImmutableMap.of(Integer.toString(ID1), ir1, Integer.toString(ID2), ir2)));
    MultiplexedCallback multiplexedCallback = new MultiplexedCallback(individualCallbacks, aggregatedCallback);
    multiplexedCallback.onSuccess(fakeRestResponse(responseContent));
    assertRestResponseEquals(callback1.get(), fakeRestResponse(entity1));
    RestException actualError = (RestException) getError(callback2);
    assertRestResponseEquals(actualError.getResponse(), fakeRestErrorResponse());
    MultiplexedResponse multiplexedResponse = aggregatedCallback.get();
    Assert.assertEquals(multiplexedResponse.getStatus(), HttpStatus.S_200_OK.getCode());
    Assert.assertEquals(multiplexedResponse.getHeaders(), HEADERS);
}
Also used : MultiplexedResponseContent(com.linkedin.restli.common.multiplexer.MultiplexedResponseContent) RestResponse(com.linkedin.r2.message.rest.RestResponse) RestException(com.linkedin.r2.message.rest.RestException) IndividualResponse(com.linkedin.restli.common.multiplexer.IndividualResponse) FutureCallback(com.linkedin.common.callback.FutureCallback) Callback(com.linkedin.common.callback.Callback) TestRecord(com.linkedin.restli.client.test.TestRecord) IndividualResponseMap(com.linkedin.restli.common.multiplexer.IndividualResponseMap) FutureCallback(com.linkedin.common.callback.FutureCallback) Test(org.testng.annotations.Test)

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