Search in sources :

Example 1 with RestLiServer

use of com.linkedin.restli.server.RestLiServer 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 2 with RestLiServer

use of com.linkedin.restli.server.RestLiServer in project incubator-gobblin by apache.

the class EmbeddedRestliServer method startUp.

@Override
protected void startUp() throws Exception {
    RestLiConfig config = new RestLiConfig();
    Set<String> resourceClassNames = Sets.newHashSet();
    for (Class<? extends BaseResource> resClass : this.resources) {
        resourceClassNames.add(resClass.getName());
    }
    config.addResourceClassNames(resourceClassNames);
    config.setServerNodeUri(this.serverUri);
    config.setDocumentationRequestHandler(new DefaultDocumentationRequestHandler());
    config.addFilter(new RestLiValidationFilter());
    ResourceFactory factory = new GuiceInjectResourceFactory(this.injector);
    TransportDispatcher dispatcher = new DelegatingTransportDispatcher(new RestLiServer(config, factory));
    String acceptedFilters = EncodingType.SNAPPY.getHttpName() + "," + EncodingType.GZIP.getHttpName();
    FilterChain filterChain = FilterChains.createRestChain(new ServerCompressionFilter(acceptedFilters));
    this.httpServer = Optional.of(new HttpNettyServerFactory(filterChain).createServer(this.port, dispatcher));
    this.log.info("Starting the {} embedded server at port {}.", this.name, this.port);
    this.httpServer.get().start();
}
Also used : RestLiValidationFilter(com.linkedin.restli.server.validation.RestLiValidationFilter) RestLiServer(com.linkedin.restli.server.RestLiServer) DelegatingTransportDispatcher(com.linkedin.restli.server.DelegatingTransportDispatcher) HttpNettyServerFactory(com.linkedin.r2.transport.http.server.HttpNettyServerFactory) ServerCompressionFilter(com.linkedin.r2.filter.compression.ServerCompressionFilter) DefaultDocumentationRequestHandler(com.linkedin.restli.docgen.DefaultDocumentationRequestHandler) FilterChain(com.linkedin.r2.filter.FilterChain) GuiceInjectResourceFactory(com.linkedin.restli.server.guice.GuiceInjectResourceFactory) ResourceFactory(com.linkedin.restli.server.resources.ResourceFactory) DelegatingTransportDispatcher(com.linkedin.restli.server.DelegatingTransportDispatcher) TransportDispatcher(com.linkedin.r2.transport.common.bridge.server.TransportDispatcher) RestLiConfig(com.linkedin.restli.server.RestLiConfig) GuiceInjectResourceFactory(com.linkedin.restli.server.guice.GuiceInjectResourceFactory)

Example 3 with RestLiServer

use of com.linkedin.restli.server.RestLiServer in project rest.li by linkedin.

the class MockHttpServerFactory method create.

/**
 * Creates a {@link HttpServer} that contains a {@link RestLiServer} to be used for testing a set of Rest.li
 * resources.
 *
 * The {@link HttpServer} uses an empty {@link FilterChain} and uses "/" as the context path.
 *
 * If the server is run in async mode (by calling this function with the last parameter {@code true}), the
 * timeout used is {@link #ASYNC_TIMEOUT}.
 *
 * Both the async and sync servers will use {@link #NUM_THREADS} threads.
 *
 * @param port the port the server will run on on localhost
 * @param config the {@link RestLiConfig} to be used by the {@link RestLiServer}
 * @param beans beans you want to inject into your Rest.li resource.
 * @param enableAsync true if the server should be async, false otherwise
 */
private static HttpServer create(int port, RestLiConfig config, Map<String, ?> beans, boolean enableAsync) {
    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(NUM_THREADS);
    final ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS);
    EngineBuilder engineBuilder = new EngineBuilder().setTaskExecutor(scheduler).setTimerScheduler(scheduler);
    com.linkedin.parseq.AsyncCallableTask.register(engineBuilder, executor);
    final Engine engine = engineBuilder.build();
    ResourceFactory resourceFactory = createResourceFactory(beans);
    TransportDispatcher dispatcher = new DelegatingTransportDispatcher(new RestLiServer(config, resourceFactory, engine));
    final FilterChain fc = FilterChains.empty().addLastRest(new SimpleLoggingFilter());
    final HttpServer server = new HttpServerFactory(fc).createServer(port, HttpServerFactory.DEFAULT_CONTEXT_PATH, NUM_THREADS, dispatcher, enableAsync ? HttpJettyServer.ServletType.ASYNC_EVENT : HttpJettyServer.ServletType.RAP, enableAsync ? ASYNC_TIMEOUT : -1);
    return new HttpServer() {

        @Override
        public void start() throws IOException {
            server.start();
        }

        @Override
        public void stop() throws IOException {
            server.stop();
            engine.shutdown();
            executor.shutdown();
            scheduler.shutdown();
        }

        @Override
        public void waitForStop() throws InterruptedException {
            server.waitForStop();
        }
    };
}
Also used : HttpServerFactory(com.linkedin.r2.transport.http.server.HttpServerFactory) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) RestLiServer(com.linkedin.restli.server.RestLiServer) DelegatingTransportDispatcher(com.linkedin.restli.server.DelegatingTransportDispatcher) FilterChain(com.linkedin.r2.filter.FilterChain) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutorService(java.util.concurrent.ExecutorService) HttpServer(com.linkedin.r2.transport.http.server.HttpServer) ResourceFactory(com.linkedin.restli.server.resources.ResourceFactory) InjectMockResourceFactory(com.linkedin.restli.server.mock.InjectMockResourceFactory) DelegatingTransportDispatcher(com.linkedin.restli.server.DelegatingTransportDispatcher) TransportDispatcher(com.linkedin.r2.transport.common.bridge.server.TransportDispatcher) EngineBuilder(com.linkedin.parseq.EngineBuilder) SimpleLoggingFilter(com.linkedin.r2.filter.logging.SimpleLoggingFilter) Engine(com.linkedin.parseq.Engine)

Example 4 with RestLiServer

use of com.linkedin.restli.server.RestLiServer in project rest.li by linkedin.

the class TestAsyncMethodInvocationPlanClass method testMultiplexedAsyncGet.

@Test(dataProvider = "multiplexerConfigurations")
public void testMultiplexedAsyncGet(MultiplexerRunMode multiplexerRunMode) throws URISyntaxException, IOException, InterruptedException {
    RestLiConfig config = new RestLiConfig();
    config.addResourcePackageNames("com.linkedin.restli.server.multiplexer.resources");
    config.setMultiplexerRunMode(multiplexerRunMode);
    SettablePromise<Trace> traceHolder = Promises.settable();
    Engine engine = engine(traceHolder);
    RestLiServer server = new RestLiServer(config, resourceFactory(), engine);
    IndividualRequest r0 = individualRequest("/users/0", null, Collections.<String, IndividualRequest>emptyMap());
    IndividualRequest r1 = individualRequest("/users/1", null, Collections.<String, IndividualRequest>emptyMap());
    IndividualRequest r2 = individualRequest("/users/2", null, ImmutableMap.of("0", r0, "1", r1));
    // request is seq(par(r0, r1), r2)
    RestRequest request = muxRestRequest(ImmutableMap.of("2", r2));
    CountDownLatch latch = new CountDownLatch(1);
    server.handleRequest(request, new RequestContext(), callback(latch));
    assertTrue(latch.await(5, TimeUnit.SECONDS));
    assertTrue(traceHolder.await(5, TimeUnit.SECONDS));
    if (multiplexerRunMode == MultiplexerRunMode.SINGLE_PLAN) {
        // For multiplexed requests in SINGLE_PLAN mode there is only one plan with class "mux"
        assertEquals(traceHolder.get().getPlanClass(), "mux");
    } else {
        // For multiplexed requests in MULTIPLE_PLANS mode there are multiple plans, first one is with class "mux",
        // following 3 are with class "resource=users,method=get", last one will have class "resource=users,method=get"
        assertEquals(traceHolder.get().getPlanClass(), "resource=users,method=get");
    }
}
Also used : Trace(com.linkedin.parseq.trace.Trace) IndividualRequest(com.linkedin.restli.common.multiplexer.IndividualRequest) RestRequest(com.linkedin.r2.message.rest.RestRequest) RestLiServer(com.linkedin.restli.server.RestLiServer) RequestContext(com.linkedin.r2.message.RequestContext) CountDownLatch(java.util.concurrent.CountDownLatch) RestLiConfig(com.linkedin.restli.server.RestLiConfig) Engine(com.linkedin.parseq.Engine) Test(org.testng.annotations.Test)

Example 5 with RestLiServer

use of com.linkedin.restli.server.RestLiServer in project rest.li by linkedin.

the class TestAsyncMethodInvocationPlanClass method testAsyncGet.

@Test(dataProvider = "requestData")
public void testAsyncGet(String uri, String method, String expectedPlanClass) throws URISyntaxException, IOException, InterruptedException {
    RestLiConfig config = new RestLiConfig();
    config.addResourcePackageNames("com.linkedin.restli.server.multiplexer.resources");
    SettablePromise<Trace> traceHolder = Promises.settable();
    Engine engine = engine(traceHolder);
    RestLiServer server = new RestLiServer(config, resourceFactory(), engine);
    RestRequest request = new RestRequestBuilder(new URI(uri)).setMethod(method).setHeader(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, AllProtocolVersions.BASELINE_PROTOCOL_VERSION.toString()).build();
    CountDownLatch latch = new CountDownLatch(1);
    server.handleRequest(request, new RequestContext(), callback(latch));
    assertTrue(latch.await(5, TimeUnit.SECONDS));
    assertTrue(traceHolder.await(5, TimeUnit.SECONDS));
    assertTrue(latch.await(5, TimeUnit.SECONDS));
    assertTrue(traceHolder.await(5, TimeUnit.SECONDS));
    assertEquals(traceHolder.get().getPlanClass(), expectedPlanClass);
}
Also used : Trace(com.linkedin.parseq.trace.Trace) RestRequest(com.linkedin.r2.message.rest.RestRequest) RestLiServer(com.linkedin.restli.server.RestLiServer) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) RequestContext(com.linkedin.r2.message.RequestContext) CountDownLatch(java.util.concurrent.CountDownLatch) URI(java.net.URI) RestLiConfig(com.linkedin.restli.server.RestLiConfig) Engine(com.linkedin.parseq.Engine) Test(org.testng.annotations.Test)

Aggregations

RestLiServer (com.linkedin.restli.server.RestLiServer)12 RestLiConfig (com.linkedin.restli.server.RestLiConfig)10 RequestContext (com.linkedin.r2.message.RequestContext)7 RestRequest (com.linkedin.r2.message.rest.RestRequest)6 TransportDispatcher (com.linkedin.r2.transport.common.bridge.server.TransportDispatcher)6 DelegatingTransportDispatcher (com.linkedin.restli.server.DelegatingTransportDispatcher)6 ResourceFactory (com.linkedin.restli.server.resources.ResourceFactory)6 Test (org.testng.annotations.Test)6 DefaultDocumentationRequestHandler (com.linkedin.restli.docgen.DefaultDocumentationRequestHandler)5 InjectMockResourceFactory (com.linkedin.restli.server.mock.InjectMockResourceFactory)5 RestResponse (com.linkedin.r2.message.rest.RestResponse)4 HttpServerFactory (com.linkedin.r2.transport.http.server.HttpServerFactory)4 SimpleBeanProvider (com.linkedin.restli.server.mock.SimpleBeanProvider)4 Engine (com.linkedin.parseq.Engine)3 FilterChain (com.linkedin.r2.filter.FilterChain)3 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)3 IOException (java.io.IOException)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 DataMap (com.linkedin.data.DataMap)2 Trace (com.linkedin.parseq.trace.Trace)2