Search in sources :

Example 1 with Server

use of com.linkedin.r2.transport.common.Server in project rest.li by linkedin.

the class TestHttpClientFactory method testShutdownAfterClients.

@Test
public void testShutdownAfterClients() throws Exception {
    NioEventLoopGroup eventLoop = new NioEventLoopGroup();
    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    HttpClientFactory factory = getHttpClientFactory(eventLoop, true, scheduler, true);
    Server server = new HttpServerBuilder().build();
    try {
        server.start();
        List<Client> clients = new ArrayList<Client>();
        for (int i = 0; i < 1; i++) {
            clients.add(new TransportClientAdapter(factory.getClient(Collections.<String, String>emptyMap()), true));
        }
        for (Client c : clients) {
            RestRequest r = new RestRequestBuilder(new URI(URI)).build();
            FutureCallback<RestResponse> futureCallback = new FutureCallback<RestResponse>();
            c.restRequest(r, futureCallback);
            futureCallback.get(30, TimeUnit.SECONDS);
        }
        for (Client c : clients) {
            FutureCallback<None> callback = new FutureCallback<None>();
            c.shutdown(callback);
            callback.get(30, TimeUnit.SECONDS);
        }
        FutureCallback<None> factoryShutdown = new FutureCallback<None>();
        factory.shutdown(factoryShutdown);
        factoryShutdown.get(30, TimeUnit.SECONDS);
        Assert.assertTrue(eventLoop.awaitTermination(30, TimeUnit.SECONDS), "Failed to shut down event-loop");
        Assert.assertTrue(scheduler.awaitTermination(30, TimeUnit.SECONDS), "Failed to shut down scheduler");
    } finally {
        server.stop();
    }
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Server(org.eclipse.jetty.server.Server) RestResponse(com.linkedin.r2.message.rest.RestResponse) ArrayList(java.util.ArrayList) URI(java.net.URI) RestRequest(com.linkedin.r2.message.rest.RestRequest) TransportClientAdapter(com.linkedin.r2.transport.common.bridge.client.TransportClientAdapter) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) TransportClient(com.linkedin.r2.transport.common.bridge.client.TransportClient) Client(com.linkedin.r2.transport.common.Client) None(com.linkedin.common.util.None) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) FutureCallback(com.linkedin.common.callback.FutureCallback) Test(org.testng.annotations.Test)

Example 2 with Server

use of com.linkedin.r2.transport.common.Server in project rest.li by linkedin.

the class RestClientTest method testRestLiRemoteInvocationException.

@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "sendRequestOptions")
public void testRestLiRemoteInvocationException(SendRequestOption option, TimeoutOption timeoutOption, ProtocolVersionOption versionOption, ProtocolVersion protocolVersion, String errorResponseHeaderName) throws ExecutionException, TimeoutException, InterruptedException, RestLiDecodingException {
    final int HTTP_CODE = 404;
    final String ERR_MSG = "WHOOPS!";
    RestClient client = mockClient(HTTP_CODE, ERR_MSG, protocolVersion);
    Request<EmptyRecord> request = mockRequest(EmptyRecord.class, versionOption);
    RequestBuilder<Request<EmptyRecord>> requestBuilder = mockRequestBuilder(request);
    FutureCallback<Response<EmptyRecord>> callback = new FutureCallback<Response<EmptyRecord>>();
    try {
        sendRequest(option, client, request, requestBuilder, callback);
        Long l = timeoutOption._l;
        TimeUnit timeUnit = timeoutOption._timeUnit;
        Response<EmptyRecord> response = l == null ? callback.get() : callback.get(l, timeUnit);
        Assert.fail("Should have thrown");
    } catch (ExecutionException e) {
        Throwable cause = e.getCause();
        Assert.assertTrue(cause instanceof RemoteInvocationException, "Expected RemoteInvocationException not " + cause.getClass().getName());
        RemoteInvocationException rlre = (RemoteInvocationException) cause;
        Assert.assertTrue(rlre.getMessage().startsWith("Received error " + HTTP_CODE + " from server"));
        Throwable rlCause = rlre.getCause();
        Assert.assertTrue(rlCause instanceof RestException, "Excepted RestException not " + rlCause.getClass().getName());
        RestException rle = (RestException) rlCause;
        Assert.assertEquals(ERR_MSG, rle.getResponse().getEntity().asString("UTF-8"));
        Assert.assertEquals(HTTP_CODE, rle.getResponse().getStatus());
    }
}
Also used : EmptyRecord(com.linkedin.restli.common.EmptyRecord) RestRequest(com.linkedin.r2.message.rest.RestRequest) RestException(com.linkedin.r2.message.rest.RestException) RestResponse(com.linkedin.r2.message.rest.RestResponse) ErrorResponse(com.linkedin.restli.common.ErrorResponse) TimeUnit(java.util.concurrent.TimeUnit) RemoteInvocationException(com.linkedin.r2.RemoteInvocationException) ExecutionException(java.util.concurrent.ExecutionException) FutureCallback(com.linkedin.common.callback.FutureCallback) Test(org.testng.annotations.Test)

Example 3 with Server

use of com.linkedin.r2.transport.common.Server in project rest.li by linkedin.

the class RestLiIntTestServer method createServer.

public static HttpServer createServer(final Engine engine, int port, boolean useAsyncServletApi, int asyncTimeOut, List<? extends Filter> filters, final FilterChain filterChain, final boolean forceUseRestServer) {
    RestLiConfig config = new RestLiConfig();
    config.addResourcePackageNames(RESOURCE_PACKAGE_NAMES);
    config.setServerNodeUri(URI.create("http://localhost:" + port));
    config.setDocumentationRequestHandler(new DefaultDocumentationRequestHandler());
    config.addDebugRequestHandlers(new ParseqTraceDebugRequestHandler());
    config.setFilters(filters);
    GroupMembershipMgr membershipMgr = new HashGroupMembershipMgr();
    GroupMgr groupMgr = new HashMapGroupMgr(membershipMgr);
    GroupsRestApplication app = new GroupsRestApplication(groupMgr, membershipMgr);
    SimpleBeanProvider beanProvider = new SimpleBeanProvider();
    beanProvider.add("GroupsRestApplication", app);
    //using InjectMockResourceFactory to keep examples spring-free
    ResourceFactory factory = new InjectMockResourceFactory(beanProvider);
    //Todo this will have to change further to accomodate streaming tests - this is temporary
    final TransportDispatcher dispatcher;
    if (forceUseRestServer) {
        dispatcher = new DelegatingTransportDispatcher(new RestLiServer(config, factory, engine));
    } else {
        final StreamRequestHandler streamRequestHandler = new RestLiServer(config, factory, engine);
        dispatcher = new TransportDispatcher() {

            @Override
            public void handleRestRequest(RestRequest req, Map<String, String> wireAttrs, RequestContext requestContext, TransportCallback<RestResponse> callback) {
                throw new UnsupportedOperationException("This server only accepts streaming");
            }

            @Override
            public void handleStreamRequest(StreamRequest req, Map<String, String> wireAttrs, RequestContext requestContext, TransportCallback<StreamResponse> callback) {
                try {
                    streamRequestHandler.handleRequest(req, requestContext, new TransportCallbackAdapter<>(callback));
                } catch (Exception e) {
                    final Exception ex = RestException.forError(RestStatus.INTERNAL_SERVER_ERROR, e);
                    callback.onResponse(TransportResponseImpl.<StreamResponse>error(ex));
                }
            }
        };
    }
    return new HttpServerFactory(filterChain).createServer(port, HttpServerFactory.DEFAULT_CONTEXT_PATH, HttpServerFactory.DEFAULT_THREAD_POOL_SIZE, dispatcher, useAsyncServletApi ? HttpJettyServer.ServletType.ASYNC_EVENT : HttpJettyServer.ServletType.RAP, asyncTimeOut, !forceUseRestServer);
}
Also used : HttpServerFactory(com.linkedin.r2.transport.http.server.HttpServerFactory) TransportCallbackAdapter(com.linkedin.r2.transport.common.bridge.server.TransportCallbackAdapter) DelegatingTransportDispatcher(com.linkedin.restli.server.DelegatingTransportDispatcher) DefaultDocumentationRequestHandler(com.linkedin.restli.docgen.DefaultDocumentationRequestHandler) DelegatingTransportDispatcher(com.linkedin.restli.server.DelegatingTransportDispatcher) TransportDispatcher(com.linkedin.r2.transport.common.bridge.server.TransportDispatcher) ParseqTraceDebugRequestHandler(com.linkedin.restli.server.ParseqTraceDebugRequestHandler) HashGroupMembershipMgr(com.linkedin.restli.examples.groups.server.impl.HashGroupMembershipMgr) GroupMembershipMgr(com.linkedin.restli.examples.groups.server.api.GroupMembershipMgr) HashMapGroupMgr(com.linkedin.restli.examples.groups.server.impl.HashMapGroupMgr) GroupsRestApplication(com.linkedin.restli.examples.groups.server.rest.impl.GroupsRestApplication) RequestContext(com.linkedin.r2.message.RequestContext) RestLiServer(com.linkedin.restli.server.RestLiServer) SimpleBeanProvider(com.linkedin.restli.server.mock.SimpleBeanProvider) RestResponse(com.linkedin.r2.message.rest.RestResponse) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) InjectMockResourceFactory(com.linkedin.restli.server.mock.InjectMockResourceFactory) ResourceFactory(com.linkedin.restli.server.resources.ResourceFactory) RestException(com.linkedin.r2.message.rest.RestException) IOException(java.io.IOException) StreamRequest(com.linkedin.r2.message.stream.StreamRequest) HashMapGroupMgr(com.linkedin.restli.examples.groups.server.impl.HashMapGroupMgr) GroupMgr(com.linkedin.restli.examples.groups.server.api.GroupMgr) StreamRequestHandler(com.linkedin.r2.transport.common.StreamRequestHandler) RestRequest(com.linkedin.r2.message.rest.RestRequest) InjectMockResourceFactory(com.linkedin.restli.server.mock.InjectMockResourceFactory) HashGroupMembershipMgr(com.linkedin.restli.examples.groups.server.impl.HashGroupMembershipMgr) RestLiConfig(com.linkedin.restli.server.RestLiConfig)

Example 4 with Server

use of com.linkedin.r2.transport.common.Server in project rest.li by linkedin.

the class TestServerTimeout method testServerTimeout.

@Test
public void testServerTimeout() throws Exception {
    final StreamRequest request = new StreamRequestBuilder(Bootstrap.createHttpURI(PORT, BUGGY_SERVER_URI)).build(EntityStreams.emptyStream());
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicInteger status = new AtomicInteger(-1);
    _client.streamRequest(request, new Callback<StreamResponse>() {

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

        @Override
        public void onSuccess(StreamResponse result) {
            status.set(result.getStatus());
            result.getEntityStream().setReader(new Reader() {

                private ReadHandle _rh;

                @Override
                public void onInit(ReadHandle rh) {
                    _rh = rh;
                    _rh.request(Integer.MAX_VALUE);
                }

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

                @Override
                public void onDone() {
                    // server would close the connection if TimeoutException, and netty would end the chunked transferring
                    // with an empty chunk
                    latch.countDown();
                }

                @Override
                public void onError(Throwable e) {
                    latch.countDown();
                }
            });
        }
    });
    // server should timeout so await should return true
    Assert.assertTrue(latch.await(SERVER_IOHANDLER_TIMEOUT * 2, TimeUnit.MILLISECONDS));
    Assert.assertEquals(status.get(), RestStatus.OK);
}
Also used : ReadHandle(com.linkedin.r2.message.stream.entitystream.ReadHandle) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ByteString(com.linkedin.data.ByteString) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) DrainReader(com.linkedin.r2.message.stream.entitystream.DrainReader) Reader(com.linkedin.r2.message.stream.entitystream.Reader) CountDownLatch(java.util.concurrent.CountDownLatch) StreamRequestBuilder(com.linkedin.r2.message.stream.StreamRequestBuilder) StreamRequest(com.linkedin.r2.message.stream.StreamRequest) Test(org.testng.annotations.Test)

Example 5 with Server

use of com.linkedin.r2.transport.common.Server in project rest.li by linkedin.

the class TestServerTimeout method testServerThrowButShouldNotTimeout.

@Test
public void testServerThrowButShouldNotTimeout() throws Exception {
    RestRequest request = new RestRequestBuilder(Bootstrap.createHttpURI(PORT, THROW_BUT_SHOULD_NOT_TIMEOUT_URI)).setEntity(new byte[10240]).build();
    _client.restRequest(request);
    Future<RestResponse> futureResponse = _client.restRequest(request);
    // if server times out, our second request would fail with TimeoutException because it's blocked by first one
    try {
        futureResponse.get(SERVER_IOHANDLER_TIMEOUT / 2, TimeUnit.MILLISECONDS);
        Assert.fail("Should fail with ExecutionException");
    } catch (ExecutionException ex) {
        Assert.assertTrue(ex.getCause() instanceof RestException);
        RestException restException = (RestException) ex.getCause();
        Assert.assertTrue(restException.getResponse().getEntity().asString("UTF8").contains("Server throw for test."));
    }
}
Also used : RestRequest(com.linkedin.r2.message.rest.RestRequest) RestResponse(com.linkedin.r2.message.rest.RestResponse) RestException(com.linkedin.r2.message.rest.RestException) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) ExecutionException(java.util.concurrent.ExecutionException) Test(org.testng.annotations.Test)

Aggregations

Test (org.testng.annotations.Test)82 RestRequest (com.linkedin.r2.message.rest.RestRequest)52 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)50 RequestContext (com.linkedin.r2.message.RequestContext)49 URI (java.net.URI)43 RestResponse (com.linkedin.r2.message.rest.RestResponse)41 StreamRequest (com.linkedin.r2.message.stream.StreamRequest)32 FutureCallback (com.linkedin.common.callback.FutureCallback)30 StreamResponse (com.linkedin.r2.message.stream.StreamResponse)30 CountDownLatch (java.util.concurrent.CountDownLatch)24 StreamRequestBuilder (com.linkedin.r2.message.stream.StreamRequestBuilder)23 RestException (com.linkedin.r2.message.rest.RestException)21 ExecutionException (java.util.concurrent.ExecutionException)21 None (com.linkedin.common.util.None)20 Server (org.eclipse.jetty.server.Server)20 ByteString (com.linkedin.data.ByteString)19 HttpServerBuilder (com.linkedin.r2.testutils.server.HttpServerBuilder)19 HashMap (java.util.HashMap)15 RemoteInvocationException (com.linkedin.r2.RemoteInvocationException)13 ArrayList (java.util.ArrayList)13