Search in sources :

Example 11 with RestResponse

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

the class RestLiResponseHandler method buildResponse.

/**
   * Build a RestResponse from PartialRestResponse and RoutingResult.
   *
   * @param routingResult
   *          {@link RoutingResult}
   * @param partialResponse
   *          {@link PartialRestResponse}
   * @return
   */
public RestResponse buildResponse(final RoutingResult routingResult, PartialRestResponse partialResponse) {
    List<String> cookies = CookieUtil.encodeSetCookies(partialResponse.getCookies());
    RestResponseBuilder builder = new RestResponseBuilder().setHeaders(partialResponse.getHeaders()).setCookies(cookies).setStatus(partialResponse.getStatus().getCode());
    if (partialResponse.hasData()) {
        DataMap dataMap = partialResponse.getDataMap();
        String mimeType = ((ServerResourceContext) routingResult.getContext()).getResponseMimeType();
        builder = encodeResult(mimeType, builder, dataMap);
    }
    return builder.build();
}
Also used : ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) DataMap(com.linkedin.data.DataMap)

Example 12 with RestResponse

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

the class TestRestLiServer method setUpServer.

private void setUpServer(Engine engine) {
    RestLiConfig config = new RestLiConfig();
    config.addResourcePackageNames("com.linkedin.restli.server.twitter");
    _resourceFactory = new EasyMockResourceFactory();
    RestLiDebugRequestHandler debugRequestHandlerA = new RestLiDebugRequestHandler() {

        @Override
        public void handleRequest(final RestRequest request, final RequestContext context, final ResourceDebugRequestHandler resourceRequestHandler, final RestLiAttachmentReader attachmentReader, final RequestExecutionCallback<RestResponse> callback) {
            handleRequestWithCustomResponse(callback, DEBUG_HANDLER_RESPONSE_A);
        }

        @Override
        public String getHandlerId() {
            return "a";
        }
    };
    RestLiDebugRequestHandler debugRequestHandlerB = new RestLiDebugRequestHandler() {

        @Override
        @SuppressWarnings("unchecked")
        public void handleRequest(final RestRequest request, final RequestContext context, final ResourceDebugRequestHandler resourceRequestHandler, final RestLiAttachmentReader attachmentReader, final RequestExecutionCallback<RestResponse> callback) {
            resourceRequestHandler.handleRequest(request, context, EasyMock.createMock(RequestExecutionCallback.class));
            handleRequestWithCustomResponse(callback, DEBUG_HANDLER_RESPONSE_B);
        }

        @Override
        public String getHandlerId() {
            return "b";
        }
    };
    config.addDebugRequestHandlers(debugRequestHandlerA, debugRequestHandlerB);
    _server = new RestLiServer(config, _resourceFactory, engine);
}
Also used : RestRequest(com.linkedin.r2.message.rest.RestRequest) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) RequestContext(com.linkedin.r2.message.RequestContext) RestLiAttachmentReader(com.linkedin.restli.common.attachments.RestLiAttachmentReader) EasyMockResourceFactory(com.linkedin.restli.server.test.EasyMockResourceFactory)

Example 13 with RestResponse

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

the class RAPResponseHandler method channelRead0.

@Override
protected void channelRead0(ChannelHandlerContext ctx, RestResponse response) throws Exception {
    final Map<String, String> headers = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
    final Map<String, String> wireAttrs = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
    headers.putAll(response.getHeaders());
    wireAttrs.putAll(WireAttributeHelper.removeWireAttributes(headers));
    final RestResponse newResponse = new RestResponseBuilder(response).unsafeSetHeaders(headers).build();
    // In general there should always be a callback to handle a received message,
    // but it could have been removed due to a previous exception or closure on the
    // channel
    TransportCallback<RestResponse> callback = ctx.channel().attr(CALLBACK_ATTR_KEY).getAndRemove();
    if (callback != null) {
        LOG.debug("{}: handling a response", ctx.channel().remoteAddress());
        callback.onResponse(TransportResponseImpl.success(newResponse, wireAttrs));
    } else {
        LOG.debug("{}: dropped a response", ctx.channel().remoteAddress());
    }
    ctx.fireChannelRead(response);
}
Also used : RestResponse(com.linkedin.r2.message.rest.RestResponse) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) TreeMap(java.util.TreeMap)

Example 14 with RestResponse

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

the class TestChannelPoolHandler method testConnectionClose.

@Test(dataProvider = "connectionClose")
public void testConnectionClose(String headerName, String headerValue) {
    EmbeddedChannel ch = new EmbeddedChannel(new ChannelPoolHandler());
    FakePool pool = new FakePool();
    ch.attr(ChannelPoolHandler.CHANNEL_POOL_ATTR_KEY).set(pool);
    RestResponse response = new RestResponseBuilder().setHeader(headerName, headerValue).build();
    ch.writeInbound(response);
    Assert.assertTrue(pool.isDisposeCalled());
    Assert.assertFalse(pool.isPutCalled());
}
Also used : RestResponse(com.linkedin.r2.message.rest.RestResponse) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Test(org.testng.annotations.Test)

Example 15 with RestResponse

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

the class HttpNettyClient method shutdown.

@Override
public void shutdown(final Callback<None> callback) {
    LOG.info("Shutdown requested");
    if (_state.compareAndSet(State.RUNNING, State.SHUTTING_DOWN)) {
        LOG.info("Shutting down");
        final long deadline = System.currentTimeMillis() + _shutdownTimeout;
        TimeoutCallback<None> closeChannels = new TimeoutCallback<None>(_scheduler, _shutdownTimeout, TimeUnit.MILLISECONDS, new Callback<None>() {

            private void finishShutdown() {
                _state.set(State.REQUESTS_STOPPING);
                // Timeout any waiters which haven't received a Channel yet
                for (Callback<Channel> callback : _channelPoolManager.cancelWaiters()) {
                    callback.onError(new TimeoutException("Operation did not complete before shutdown"));
                }
                // Timeout any requests still pending response
                for (Channel c : _allChannels) {
                    TransportCallback<RestResponse> callback = c.attr(RAPResponseHandler.CALLBACK_ATTR_KEY).getAndRemove();
                    if (callback != null) {
                        errorResponse(callback, new TimeoutException("Operation did not complete before shutdown"));
                    }
                }
                // Close all active and idle Channels
                final TimeoutRunnable afterClose = new TimeoutRunnable(_scheduler, deadline - System.currentTimeMillis(), TimeUnit.MILLISECONDS, new Runnable() {

                    @Override
                    public void run() {
                        _state.set(State.SHUTDOWN);
                        LOG.info("Shutdown complete");
                        callback.onSuccess(None.none());
                    }
                }, "Timed out waiting for channels to close, continuing shutdown");
                _allChannels.close().addListener(new ChannelGroupFutureListener() {

                    @Override
                    public void operationComplete(ChannelGroupFuture channelGroupFuture) throws Exception {
                        if (!channelGroupFuture.isSuccess()) {
                            LOG.warn("Failed to close some connections, ignoring");
                        }
                        afterClose.run();
                    }
                });
            }

            @Override
            public void onSuccess(None none) {
                LOG.info("All connection pools shut down, closing all channels");
                finishShutdown();
            }

            @Override
            public void onError(Throwable e) {
                LOG.warn("Error shutting down HTTP connection pools, ignoring and continuing shutdown", e);
                finishShutdown();
            }
        }, "Connection pool shutdown timeout exceeded (" + _shutdownTimeout + "ms)");
        _channelPoolManager.shutdown(closeChannels);
        _jmxManager.onProviderShutdown(_channelPoolManager);
    } else {
        callback.onError(new IllegalStateException("Shutdown has already been requested."));
    }
}
Also used : TransportCallback(com.linkedin.r2.transport.common.bridge.common.TransportCallback) TimeoutRunnable(com.linkedin.r2.util.TimeoutRunnable) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) ChannelGroupFutureListener(io.netty.channel.group.ChannelGroupFutureListener) TransportCallback(com.linkedin.r2.transport.common.bridge.common.TransportCallback) Callback(com.linkedin.common.callback.Callback) TimeoutRunnable(com.linkedin.r2.util.TimeoutRunnable) None(com.linkedin.common.util.None) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

RestResponse (com.linkedin.r2.message.rest.RestResponse)350 Test (org.testng.annotations.Test)277 RestRequest (com.linkedin.r2.message.rest.RestRequest)251 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)203 RequestContext (com.linkedin.r2.message.RequestContext)166 URI (java.net.URI)153 RestException (com.linkedin.r2.message.rest.RestException)78 RestResponseBuilder (com.linkedin.r2.message.rest.RestResponseBuilder)73 ByteString (com.linkedin.data.ByteString)69 HashMap (java.util.HashMap)54 ExecutionException (java.util.concurrent.ExecutionException)53 FutureCallback (com.linkedin.common.callback.FutureCallback)52 Map (java.util.Map)51 Callback (com.linkedin.common.callback.Callback)48 StreamResponse (com.linkedin.r2.message.stream.StreamResponse)38 StreamRequest (com.linkedin.r2.message.stream.StreamRequest)36 IOException (java.io.IOException)31 BeforeTest (org.testng.annotations.BeforeTest)31 FilterRequestContext (com.linkedin.restli.server.filter.FilterRequestContext)29 AfterTest (org.testng.annotations.AfterTest)28