Search in sources :

Example 56 with Server

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

the class TestRestLiServer method testHandleRequestWithRestLiResponseError.

@Test(dataProvider = "restOrStream")
public void testHandleRequestWithRestLiResponseError(final RestOrStream restOrStream) throws Exception {
    final StatusCollectionResource statusResource = getMockResource(StatusCollectionResource.class);
    EasyMock.expect(statusResource.get(eq(1L))).andReturn(null).once();
    replay(statusResource);
    Callback<RestLiResponse> restLiResponseCallback = new Callback<RestLiResponse>() {

        @Override
        public void onSuccess(RestLiResponse restLiResponse) {
            fail("We should not get a success here. The server should have returned a 404!");
        }

        @Override
        public void onError(Throwable e) {
            RestLiResponseException restLiResponseException = (RestLiResponseException) e;
            assertEquals(restLiResponseException.getRestLiResponse().getStatus(), HttpStatus.S_404_NOT_FOUND, "We should get a 404 back here!");
            EasyMock.verify(statusResource);
            EasyMock.reset(statusResource);
        }
    };
    if (restOrStream == RestOrStream.REST) {
        RestRequest request = new RestRequestBuilder(new URI("/statuses/1")).setHeader(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, AllProtocolVersions.BASELINE_PROTOCOL_VERSION.toString()).build();
        _server.handleRequestWithRestLiResponse(request, new RequestContext(), restLiResponseCallback);
    } else {
        StreamRequest streamRequest = new StreamRequestBuilder(new URI("/statuses/1")).setHeader(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, AllProtocolVersions.BASELINE_PROTOCOL_VERSION.toString()).build(EntityStreams.emptyStream());
        _server.handleRequestWithRestLiResponse(streamRequest, new RequestContext(), restLiResponseCallback);
    }
}
Also used : SinglePartMIMEFullReaderCallback(com.linkedin.multipart.utils.MIMETestUtils.SinglePartMIMEFullReaderCallback) Callback(com.linkedin.common.callback.Callback) MultiPartMIMEFullReaderCallback(com.linkedin.multipart.utils.MIMETestUtils.MultiPartMIMEFullReaderCallback) RestRequest(com.linkedin.r2.message.rest.RestRequest) RestLiResponse(com.linkedin.restli.internal.server.response.RestLiResponse) AsyncStatusCollectionResource(com.linkedin.restli.server.twitter.AsyncStatusCollectionResource) StatusCollectionResource(com.linkedin.restli.server.twitter.StatusCollectionResource) RestLiResponseException(com.linkedin.restli.internal.server.response.RestLiResponseException) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) RequestContext(com.linkedin.r2.message.RequestContext) URI(java.net.URI) StreamRequestBuilder(com.linkedin.r2.message.stream.StreamRequestBuilder) StreamRequest(com.linkedin.r2.message.stream.StreamRequest) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest)

Example 57 with Server

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

the class TestRestLiServer method testValidReactiveUnstructuredDataRequest.

@Test(dataProvider = "validClientProtocolVersionDataStreamOnly")
public void testValidReactiveUnstructuredDataRequest(RestLiServer server, ProtocolVersion clientProtocolVersion, String headerConstant) throws URISyntaxException, IOException {
    StreamRequest streamRequest = new StreamRequestBuilder(new URI("/reactiveFeedDownloads/1")).setHeader(headerConstant, clientProtocolVersion.toString()).build(EntityStreams.emptyStream());
    final FeedDownloadResourceReactive resource = getMockResource(FeedDownloadResourceReactive.class);
    resource.get(eq(1L), anyObject());
    EasyMock.expectLastCall().andDelegateTo(new FeedDownloadResourceReactive()).once();
    replay(resource);
    @SuppressWarnings("unchecked") Callback<StreamResponse> r2Callback = createMock(Callback.class);
    final Capture<StreamResponse> streamResponse = EasyMock.newCapture();
    r2Callback.onSuccess(capture(streamResponse));
    expectLastCall().once();
    replay(r2Callback);
    RequestContext requestContext = new RequestContext();
    server.handleRequest(streamRequest, requestContext, r2Callback);
    verify(resource);
    verify(r2Callback);
    assertNotNull(streamResponse);
    assertEquals(streamResponse.getValue().getHeader(RestConstants.HEADER_CONTENT_TYPE), FeedDownloadResourceReactive.CONTENT_TYPE);
    FullEntityReader fullEntityReader = new FullEntityReader(new Callback<ByteString>() {

        @Override
        public void onError(Throwable e) {
            fail("Error inside callback!! Failed to read response data from stream!", e);
        }

        @Override
        public void onSuccess(ByteString result) {
            assertEquals(result, FeedDownloadResourceReactive.CONTENT);
        }
    });
    streamResponse.getValue().getEntityStream().setReader(fullEntityReader);
}
Also used : ByteString(com.linkedin.data.ByteString) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) FeedDownloadResourceReactive(com.linkedin.restli.server.twitter.FeedDownloadResourceReactive) StreamRequestBuilder(com.linkedin.r2.message.stream.StreamRequestBuilder) URI(java.net.URI) StreamRequest(com.linkedin.r2.message.stream.StreamRequest) FullEntityReader(com.linkedin.r2.message.stream.entitystream.FullEntityReader) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) RequestContext(com.linkedin.r2.message.RequestContext) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest)

Example 58 with Server

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

the class TestInjectMockResourceFactory method testMockInjectionViaServer.

@Test
public void testMockInjectionViaServer() {
    final CounterBean counter = new CounterBean();
    InjectMockResourceFactory factory = new InjectMockResourceFactory(new SimpleBeanProvider().add("counterBean", counter).add("mySpecialBean", new SpecialBean()));
    RestLiConfig config = new RestLiConfig();
    config.addResourcePackageNames("com.linkedin.restli.server.mock");
    RestLiServer server = new RestLiServer(config, factory);
    server.handleRequest(new MockRequest(), new RequestContext(), new Callback<RestResponse>() {

        @Override
        public void onError(Throwable e) {
            Assert.fail("expected success response");
        }

        @Override
        public void onSuccess(RestResponse result) {
            Assert.assertEquals(counter._counter, 1);
        }
    });
}
Also used : RestLiServer(com.linkedin.restli.server.RestLiServer) RestResponse(com.linkedin.r2.message.rest.RestResponse) RequestContext(com.linkedin.r2.message.RequestContext) RestLiConfig(com.linkedin.restli.server.RestLiConfig) Test(org.testng.annotations.Test)

Example 59 with Server

use of com.linkedin.r2.transport.common.Server in project incubator-gobblin by apache.

the class ThrottlingClientTest method test.

@Test
public void test() throws Exception {
    ThrottlingPolicyFactory factory = new ThrottlingPolicyFactory();
    SharedLimiterKey res1key = new SharedLimiterKey("res1");
    Map<String, String> configMap = ImmutableMap.<String, String>builder().put(BrokerConfigurationKeyGenerator.generateKey(factory, res1key, null, ThrottlingPolicyFactory.POLICY_KEY), CountBasedPolicy.FACTORY_ALIAS).put(BrokerConfigurationKeyGenerator.generateKey(factory, res1key, null, CountBasedPolicy.COUNT_KEY), "50").put(BrokerConfigurationKeyGenerator.generateKey(factory, null, null, ThrottlingPolicyFactory.FAIL_ON_UNKNOWN_RESOURCE_ID), "true").build();
    ThrottlingGuiceServletConfig guiceServletConfig = new ThrottlingGuiceServletConfig();
    guiceServletConfig.initialize(ConfigFactory.parseMap(configMap));
    Injector injector = guiceServletConfig.getInjector();
    EmbeddedRestliServer server = EmbeddedRestliServer.builder().resources(Lists.<Class<? extends BaseResource>>newArrayList(LimiterServerResource.class)).injector(injector).build();
    try {
        server.startAsync();
        server.awaitRunning();
        final HttpClientFactory http = new HttpClientFactory();
        final Client r2Client = new TransportClientAdapter(http.getClient(Collections.<String, String>emptyMap()));
        RestClient restClient = new RestClient(r2Client, server.getURIPrefix());
        PermitsGetRequestBuilder getBuilder = new PermitsRequestBuilders().get();
        PermitRequest res1request = new PermitRequest();
        res1request.setPermits(20);
        res1request.setResource(res1key.getResourceLimitedPath());
        PermitAllocation allocation = getPermitAllocation(res1request, restClient, getBuilder);
        Assert.assertEquals(allocation.getPermits(), new Long(20));
        allocation = getPermitAllocation(res1request, restClient, getBuilder);
        Assert.assertEquals(allocation.getPermits(), new Long(20));
        // out of permits
        try {
            allocation = getPermitAllocation(res1request, restClient, getBuilder);
            Assert.fail();
        } catch (RestLiResponseException exc) {
            Assert.assertEquals(exc.getStatus(), HttpStatus.S_403_FORBIDDEN.getCode());
        }
        PermitRequest invalidRequest = new PermitRequest();
        invalidRequest.setPermits(20);
        invalidRequest.setResource("invalidkey");
        try {
            allocation = getPermitAllocation(invalidRequest, restClient, getBuilder);
            Assert.fail();
        } catch (RestLiResponseException exc) {
            Assert.assertEquals(exc.getStatus(), 422);
        }
    } finally {
        if (server.isRunning()) {
            server.stopAsync();
            server.awaitTerminated();
        }
    }
}
Also used : EmbeddedRestliServer(org.apache.gobblin.restli.EmbeddedRestliServer) RestClient(com.linkedin.restli.client.RestClient) Injector(com.google.inject.Injector) TransportClientAdapter(com.linkedin.r2.transport.common.bridge.client.TransportClientAdapter) RestLiResponseException(com.linkedin.restli.client.RestLiResponseException) SharedLimiterKey(org.apache.gobblin.util.limiter.broker.SharedLimiterKey) RestClient(com.linkedin.restli.client.RestClient) Client(com.linkedin.r2.transport.common.Client) HttpClientFactory(com.linkedin.r2.transport.http.client.HttpClientFactory) Test(org.testng.annotations.Test)

Example 60 with Server

use of com.linkedin.r2.transport.common.Server 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)

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