Search in sources :

Example 41 with Response

use of com.linkedin.r2.message.Response in project rest.li by linkedin.

the class AbstractCaptureFilterTest method testException.

@Test
public void testException() {
    final RestRequest req = request();
    final Exception ex = new Exception();
    FilterUtil.fireUntypedRequestError(getFilterChain(), req, ex);
    // Request / response should not be recorded
    Assert.assertNull(getDb().replay(req));
}
Also used : RestRequest(com.linkedin.r2.message.rest.RestRequest) Test(org.testng.annotations.Test)

Example 42 with Response

use of com.linkedin.r2.message.Response in project rest.li by linkedin.

the class AbstractCaptureFilterTest method testSameRequestDifferentResponses.

@Test
public void testSameRequestDifferentResponses() {
    final RestRequest req = request();
    final RestResponse res1 = response();
    final RestResponse res2 = res1.builder().setEntity("This is a different response".getBytes()).build();
    FilterUtil.fireUntypedRequestResponse(getFilterChain(), req, res1);
    FilterUtil.fireUntypedRequestResponse(getFilterChain(), req, res2);
    // Last one wins
    Assert.assertEquals(res2, getDb().<Response>replay(req));
}
Also used : RestRequest(com.linkedin.r2.message.rest.RestRequest) RestResponse(com.linkedin.r2.message.rest.RestResponse) Test(org.testng.annotations.Test)

Example 43 with Response

use of com.linkedin.r2.message.Response in project rest.li by linkedin.

the class AbstractReplayFilterTest method testReplayWithNoMatch.

@Test
public void testReplayWithNoMatch() {
    final RestRequest req = request();
    final RestResponse res = response();
    final CaptureLastCallFilter captureFilter = new CaptureLastCallFilter();
    final FilterChain fc = getFilterChain().addFirstRest(captureFilter);
    FilterUtil.fireUntypedRequestResponse(fc, req, res);
    Assert.assertEquals(res, captureFilter.getLastRes());
}
Also used : RestRequest(com.linkedin.r2.message.rest.RestRequest) CaptureLastCallFilter(com.linkedin.r2.testutils.filter.CaptureLastCallFilter) RestResponse(com.linkedin.r2.message.rest.RestResponse) FilterChain(com.linkedin.r2.filter.FilterChain) Test(org.testng.annotations.Test)

Example 44 with Response

use of com.linkedin.r2.message.Response in project rest.li by linkedin.

the class HttpDispatcher method handleRequest.

/**
 * handle a {@link com.linkedin.r2.message.stream.StreamRequest} using the given request context.
 * @see com.linkedin.r2.transport.common.bridge.server.TransportDispatcher#handleStreamRequest
 *
 * @param req the request to be handled.
 * @param context the request context.
 * @param callback the callback to be invoked with the response or error.
 */
public void handleRequest(StreamRequest req, RequestContext context, final TransportCallback<StreamResponse> callback) {
    markOnRequestTimings(context);
    final Map<String, String> headers = new HashMap<>(req.getHeaders());
    final Map<String, String> wireAttrs = WireAttributeHelper.removeWireAttributes(headers);
    final BaseConnector connector = new BaseConnector();
    try {
        MessageType.Type msgType = MessageType.getMessageType(wireAttrs, MessageType.Type.REST);
        switch(msgType) {
            default:
            case REST:
                req.getEntityStream().setReader(connector);
                StreamRequest newReq = req.builder().build(EntityStreams.newEntityStream(connector));
                // decorate the call back so that if response is error or response finishes streaming,
                // we cancel the request stream
                TransportCallback<StreamResponse> decorateCallback = new TransportCallback<StreamResponse>() {

                    @Override
                    public void onResponse(TransportResponse<StreamResponse> response) {
                        // no need to check StreamException because that's handled by HttpBridge.httpToStreamCallback
                        if (response.hasError()) {
                            connector.cancel();
                        } else {
                            Observer observer = new Observer() {

                                @Override
                                public void onDataAvailable(ByteString data) {
                                // do nothing
                                }

                                @Override
                                public void onDone() {
                                    connector.cancel();
                                }

                                @Override
                                public void onError(Throwable e) {
                                    connector.cancel();
                                }
                            };
                            response.getResponse().getEntityStream().addObserver(observer);
                        }
                        callback.onResponse(response);
                    }
                };
                _dispatcher.handleStreamRequest(HttpBridge.toStreamRequest(newReq, headers), wireAttrs, context, HttpBridge.httpToStreamCallback(decorateCallback));
        }
    } catch (Exception e) {
        connector.cancel();
        callback.onResponse(TransportResponseImpl.<StreamResponse>error(e, Collections.<String, String>emptyMap()));
    }
}
Also used : TransportCallback(com.linkedin.r2.transport.common.bridge.common.TransportCallback) HashMap(java.util.HashMap) BaseConnector(com.linkedin.r2.message.stream.entitystream.BaseConnector) ByteString(com.linkedin.data.ByteString) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) ByteString(com.linkedin.data.ByteString) TransportResponse(com.linkedin.r2.transport.common.bridge.common.TransportResponse) StreamRequest(com.linkedin.r2.message.stream.StreamRequest) Observer(com.linkedin.r2.message.stream.entitystream.Observer) MessageType(com.linkedin.r2.transport.common.MessageType)

Example 45 with Response

use of com.linkedin.r2.message.Response in project rest.li by linkedin.

the class SyncIOHandler method eventLoop.

private void eventLoop() throws ServletException, IOException, InterruptedException, TimeoutException {
    final long startTime = System.currentTimeMillis();
    byte[] buf = new byte[DEFAULT_DATA_CHUNK_SIZE];
    while (shouldContinue() && !_forceExit) {
        long timeSpent = System.currentTimeMillis() - startTime;
        long maxWaitTime = timeSpent < _timeout ? _timeout - timeSpent : 0;
        Event event = _eventQueue.poll(maxWaitTime, TimeUnit.MILLISECONDS);
        if (event == null) {
            throw new TimeoutException("Timeout after " + _timeout + " milliseconds.");
        }
        switch(event.getEventType()) {
            case ResponseDataAvailable:
                {
                    ByteString data = (ByteString) event.getData();
                    data.write(_os);
                    _rh.request(1);
                    break;
                }
            case WriteRequestPossible:
                {
                    while (_wh.remaining() > 0) {
                        final int actualLen = _is.read(buf);
                        if (actualLen < 0) {
                            _wh.done();
                            _requestReadFinished = true;
                            break;
                        }
                        _wh.write(ByteString.copy(buf, 0, actualLen));
                    }
                    break;
                }
            case FullResponseReceived:
                {
                    _os.close();
                    _responseWriteFinished = true;
                    break;
                }
            case ResponseDataError:
                {
                    _os.close();
                    _responseWriteFinished = true;
                    break;
                }
            case WriteRequestAborted:
                {
                    if (event.getData() instanceof AbortedException) {
                        // reader cancels, we'll drain the stream on behalf of reader
                        // we don't directly drain it here because we'd like to give other events
                        // some opportunities to be executed; e.g. return an error response
                        _eventQueue.add(Event.DrainRequestEvent);
                    } else {
                        // TODO: do we want to be smarter and return server error response?
                        throw new ServletException((Throwable) event.getData());
                    }
                    break;
                }
            case DrainRequest:
                {
                    for (int i = 0; i < 10; i++) {
                        final int actualLen = _is.read(buf);
                        if (actualLen < 0) {
                            _requestReadFinished = true;
                            break;
                        }
                    }
                    if (!_requestReadFinished) {
                        // add self back to event queue and give others a chance to run
                        _eventQueue.add(Event.DrainRequestEvent);
                    }
                    break;
                }
            case ForceExit:
                {
                    _forceExit = true;
                    break;
                }
            default:
                throw new IllegalStateException("Unknown event type:" + event.getEventType());
        }
    }
}
Also used : ServletException(javax.servlet.ServletException) ByteString(com.linkedin.data.ByteString) AbortedException(com.linkedin.r2.message.stream.entitystream.AbortedException) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

Test (org.testng.annotations.Test)155 RestResponse (com.linkedin.r2.message.rest.RestResponse)142 RestRequest (com.linkedin.r2.message.rest.RestRequest)101 RequestContext (com.linkedin.r2.message.RequestContext)95 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)87 URI (java.net.URI)77 StreamResponse (com.linkedin.r2.message.stream.StreamResponse)66 ByteString (com.linkedin.data.ByteString)58 StreamRequest (com.linkedin.r2.message.stream.StreamRequest)41 StreamRequestBuilder (com.linkedin.r2.message.stream.StreamRequestBuilder)40 HashMap (java.util.HashMap)39 FutureCallback (com.linkedin.common.callback.FutureCallback)36 RestException (com.linkedin.r2.message.rest.RestException)36 CountDownLatch (java.util.concurrent.CountDownLatch)35 RestResponseBuilder (com.linkedin.r2.message.rest.RestResponseBuilder)34 ExecutionException (java.util.concurrent.ExecutionException)32 TransportCallback (com.linkedin.r2.transport.common.bridge.common.TransportCallback)27 Callback (com.linkedin.common.callback.Callback)25 IOException (java.io.IOException)24 Map (java.util.Map)24