Search in sources :

Example 71 with Response

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

the class TestRequestCompression method testUpdate.

@Test(dataProvider = "requestData")
public void testUpdate(CompressionConfig requestCompressionConfig, String supportedEncodings, RestliRequestOptions restliRequestOptions, int messageLength, String testHelpHeader) throws RemoteInvocationException, CloneNotSupportedException, InterruptedException, ExecutionException, TimeoutException {
    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("R2 Netty Scheduler"));
    Map<String, CompressionConfig> requestCompressionConfigs = new HashMap<String, CompressionConfig>();
    if (requestCompressionConfig != null) {
        requestCompressionConfigs.put(SERVICE_NAME, requestCompressionConfig);
    }
    HttpClientFactory httpClientFactory = new HttpClientFactory(FilterChains.empty(), new NioEventLoopGroup(), true, executor, true, null, false, AbstractJmxManager.NULL_JMX_MANAGER, // The default compression threshold is between small and large.
    500, requestCompressionConfigs);
    Map<String, String> properties = new HashMap<String, String>();
    properties.put(HttpClientFactory.HTTP_REQUEST_CONTENT_ENCODINGS, supportedEncodings);
    properties.put(HttpClientFactory.HTTP_SERVICE_NAME, SERVICE_NAME);
    TransportClientAdapter clientAdapter1 = new TransportClientAdapter(httpClientFactory.getClient(properties));
    RestClient client = new RestClient(clientAdapter1, FILTERS_URI_PREFIX);
    RootBuilderWrapper<Long, Greeting> builders = new RootBuilderWrapper<Long, Greeting>(new GreetingsRequestBuilders(restliRequestOptions));
    // GET
    Request<Greeting> request = builders.get().id(1L).build();
    ResponseFuture<Greeting> future = client.sendRequest(request);
    Response<Greeting> greetingResponse = future.getResponse();
    String response1 = greetingResponse.getEntity().getMessage();
    Assert.assertNotNull(response1);
    // POST
    Greeting greeting = new Greeting(greetingResponse.getEntity().data().copy());
    char[] As = new char[messageLength];
    Arrays.fill(As, 'A');
    String message = new String(As);
    greeting.setMessage(message);
    Request<EmptyRecord> writeRequest = builders.update().id(1L).input(greeting).setHeader(TEST_HELP_HEADER, testHelpHeader).build();
    client.sendRequest(writeRequest).getResponse();
    // GET again, to verify that our POST worked.
    Request<Greeting> request2 = builders.get().id(1L).build();
    ResponseFuture<Greeting> future2 = client.sendRequest(request2);
    String response2 = future2.getResponse().getEntity().getMessage();
    Assert.assertEquals(response2, message);
    FutureCallback<None> callback1 = new FutureCallback<None>();
    client.shutdown(callback1);
    callback1.get(30, TimeUnit.SECONDS);
    FutureCallback<None> callback2 = new FutureCallback<None>();
    httpClientFactory.shutdown(callback2);
    callback2.get(30, TimeUnit.SECONDS);
}
Also used : Greeting(com.linkedin.restli.examples.greetings.api.Greeting) EmptyRecord(com.linkedin.restli.common.EmptyRecord) HashMap(java.util.HashMap) GreetingsRequestBuilders(com.linkedin.restli.examples.greetings.client.GreetingsRequestBuilders) TransportClientAdapter(com.linkedin.r2.transport.common.bridge.client.TransportClientAdapter) HttpClientFactory(com.linkedin.r2.transport.http.client.HttpClientFactory) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) FutureCallback(com.linkedin.common.callback.FutureCallback) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) NamedThreadFactory(com.linkedin.r2.util.NamedThreadFactory) RootBuilderWrapper(com.linkedin.restli.test.util.RootBuilderWrapper) RestClient(com.linkedin.restli.client.RestClient) None(com.linkedin.common.util.None) CompressionConfig(com.linkedin.r2.filter.CompressionConfig) Test(org.testng.annotations.Test)

Example 72 with Response

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

the class TestResponseCompression method requestData.

@DataProvider(name = "requestData")
private Object[][] requestData() {
    Integer zero = 0;
    Integer tiny = 100;
    Integer huge = 1000000;
    Integer max = Integer.MAX_VALUE;
    int largeIdCount = 100;
    int smallIdCount = 1;
    RestliRequestOptions forceOnOption = new RestliRequestOptionsBuilder().setProtocolVersionOption(ProtocolVersionOption.USE_LATEST_IF_AVAILABLE).setResponseCompressionOverride(CompressionOption.FORCE_ON).build();
    RestliRequestOptions forceOffOption = new RestliRequestOptionsBuilder().setProtocolVersionOption(ProtocolVersionOption.USE_LATEST_IF_AVAILABLE).setResponseCompressionOverride(CompressionOption.FORCE_OFF).build();
    return new Object[][] { // Large responses are compressed
    { true, null, RestliRequestOptions.DEFAULT_OPTIONS, largeIdCount, DEFAULT_ACCEPT_ENCODING, null, true }, { true, null, RestliRequestOptions.DEFAULT_OPTIONS, smallIdCount, DEFAULT_ACCEPT_ENCODING, null, false }, // Override the default threshold and cause small responses to be compressed
    { true, new CompressionConfig(tiny), RestliRequestOptions.DEFAULT_OPTIONS, largeIdCount, DEFAULT_ACCEPT_ENCODING, tiny.toString(), true }, { true, new CompressionConfig(tiny), RestliRequestOptions.DEFAULT_OPTIONS, smallIdCount, DEFAULT_ACCEPT_ENCODING, tiny.toString(), true }, // Override the default threshold and cause large responses to be NOT compressed
    { true, new CompressionConfig(huge), RestliRequestOptions.DEFAULT_OPTIONS, largeIdCount, DEFAULT_ACCEPT_ENCODING, huge.toString(), false }, { true, new CompressionConfig(huge), RestliRequestOptions.DEFAULT_OPTIONS, smallIdCount, DEFAULT_ACCEPT_ENCODING, huge.toString(), false }, // Force on/off using RestliRequestOptions
    { true, null, forceOnOption, largeIdCount, DEFAULT_ACCEPT_ENCODING, zero.toString(), true }, { true, null, forceOnOption, smallIdCount, DEFAULT_ACCEPT_ENCODING, zero.toString(), true }, { true, new CompressionConfig(huge), forceOnOption, smallIdCount, DEFAULT_ACCEPT_ENCODING, zero.toString(), true }, { true, null, forceOffOption, largeIdCount, NONE, null, false }, { true, null, forceOffOption, smallIdCount, NONE, null, false }, { true, new CompressionConfig(huge), forceOffOption, largeIdCount, NONE, null, false }, // Force on/off using ResponseCompressionConfig
    { true, new CompressionConfig(0), RestliRequestOptions.DEFAULT_OPTIONS, largeIdCount, DEFAULT_ACCEPT_ENCODING, zero.toString(), true }, { true, new CompressionConfig(0), RestliRequestOptions.DEFAULT_OPTIONS, smallIdCount, DEFAULT_ACCEPT_ENCODING, zero.toString(), true }, { true, new CompressionConfig(Integer.MAX_VALUE), RestliRequestOptions.DEFAULT_OPTIONS, largeIdCount, DEFAULT_ACCEPT_ENCODING, max.toString(), false }, { true, new CompressionConfig(Integer.MAX_VALUE), RestliRequestOptions.DEFAULT_OPTIONS, smallIdCount, DEFAULT_ACCEPT_ENCODING, max.toString(), false }, // RestliRequestOptions takes precedence over ResponseCompressionConfig
    { true, new CompressionConfig(0), forceOffOption, largeIdCount, NONE, null, false }, { true, new CompressionConfig(Integer.MAX_VALUE), forceOnOption, smallIdCount, DEFAULT_ACCEPT_ENCODING, zero.toString(), true }, // If http.useResponseCompression is false or null, Accept-Encoding header is not sent and response is not compressed
    { false, null, RestliRequestOptions.DEFAULT_OPTIONS, largeIdCount, NONE, null, false }, { false, new CompressionConfig(tiny), RestliRequestOptions.DEFAULT_OPTIONS, largeIdCount, NONE, null, false }, { false, null, forceOnOption, largeIdCount, NONE, null, false }, { null, new CompressionConfig(0), RestliRequestOptions.DEFAULT_OPTIONS, largeIdCount, NONE, null, false }, { null, new CompressionConfig(Integer.MAX_VALUE), forceOnOption, smallIdCount, NONE, null, false } };
}
Also used : RestliRequestOptions(com.linkedin.restli.client.RestliRequestOptions) RestliRequestOptionsBuilder(com.linkedin.restli.client.RestliRequestOptionsBuilder) CompressionConfig(com.linkedin.r2.filter.CompressionConfig) DataProvider(org.testng.annotations.DataProvider)

Example 73 with Response

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

the class TestStreamingGreetings method fullStreamTest.

@Test(dataProvider = com.linkedin.restli.internal.common.TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "requestBuilderDataProvider")
public void fullStreamTest(final RootBuilderWrapper<Long, Greeting> builders) throws RemoteInvocationException {
    //Perform a create to the server to store some bytes via an attachment.
    final byte[] clientSuppliedBytes = "ClientSupplied".getBytes();
    final RestLiTestAttachmentDataSource greetingAttachment = new RestLiTestAttachmentDataSource("1", ByteString.copy(clientSuppliedBytes));
    final RootBuilderWrapper.MethodBuilderWrapper<Long, Greeting, EmptyRecord> methodBuilderWrapper = builders.create();
    methodBuilderWrapper.appendSingleAttachment(greetingAttachment);
    //Provide a header to verify the server's ability to transform the first part into the RestRequest.
    methodBuilderWrapper.setHeader("createHeader", "createHeaderValue");
    final Greeting greeting = new Greeting().setMessage("A greeting with an attachment");
    final Request<EmptyRecord> createRequest = methodBuilderWrapper.input(greeting).build();
    try {
        final Response<EmptyRecord> createResponse = getClient().sendRequest(createRequest).getResponse();
        Assert.assertEquals(createResponse.getStatus(), 201);
        //Verify that headers propagate properly.
        Assert.assertEquals(createResponse.getHeader("createHeader"), "createHeaderValue");
    } catch (final RestLiResponseException responseException) {
        Assert.fail("We should not reach here!", responseException);
    }
    //Then perform a GET and verify the bytes are present
    try {
        final Request<Greeting> getRequest = builders.get().id(1l).setHeader("getHeader", "getHeaderValue").build();
        final Response<Greeting> getResponse = getClient().sendRequest(getRequest).getResponse();
        Assert.assertEquals(getResponse.getStatus(), 200);
        //Verify that headers propagate properly.
        Assert.assertEquals(getResponse.getHeader("getHeader"), "getHeaderValue");
        Assert.assertEquals(getResponse.getHeader(RestConstants.HEADER_CONTENT_TYPE), RestConstants.HEADER_VALUE_APPLICATION_JSON);
        Assert.assertEquals(getResponse.getEntity().getMessage(), "Your greeting has an attachment since you were kind and decided you wanted to read it!");
        Assert.assertTrue(getResponse.hasAttachments(), "We must have some response attachments");
        RestLiAttachmentReader attachmentReader = getResponse.getAttachmentReader();
        final CountDownLatch latch = new CountDownLatch(1);
        final GreetingBlobReaderCallback greetingBlobReaderCallback = new GreetingBlobReaderCallback(latch);
        attachmentReader.registerAttachmentReaderCallback(greetingBlobReaderCallback);
        try {
            latch.await(3000, TimeUnit.SECONDS);
            Assert.assertEquals(greetingBlobReaderCallback.getAttachmentList().size(), 1);
            Assert.assertEquals(greetingBlobReaderCallback.getAttachmentList().get(0), ByteString.copy(clientSuppliedBytes));
        } catch (Exception exception) {
            Assert.fail();
        }
    } catch (final RestLiResponseException responseException) {
        Assert.fail("We should not reach here!", responseException);
    }
}
Also used : Greeting(com.linkedin.restli.examples.greetings.api.Greeting) EmptyRecord(com.linkedin.restli.common.EmptyRecord) RootBuilderWrapper(com.linkedin.restli.test.util.RootBuilderWrapper) CountDownLatch(java.util.concurrent.CountDownLatch) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) RestLiResponseException(com.linkedin.restli.client.RestLiResponseException) RemoteInvocationException(com.linkedin.r2.RemoteInvocationException) RestLiResponseException(com.linkedin.restli.client.RestLiResponseException) RestLiTestAttachmentDataSource(com.linkedin.restli.internal.testutils.RestLiTestAttachmentDataSource) RestLiAttachmentReader(com.linkedin.restli.common.attachments.RestLiAttachmentReader) Test(org.testng.annotations.Test)

Example 74 with Response

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

the class RestLiServer method handleResourceRequest.

private void handleResourceRequest(final RestRequest request, final RequestContext requestContext, final RequestExecutionCallback<RestResponse> callback, final RestLiAttachmentReader attachmentReader, final boolean isDebugMode) {
    try {
        ensureRequestUsesValidRestliProtocol(request);
    } catch (RestLiServiceException e) {
        respondWithPreRoutingError(e, request, attachmentReader, callback);
        return;
    }
    final RoutingResult method;
    try {
        method = _router.process(request, requestContext, attachmentReader);
    } catch (Exception e) {
        respondWithPreRoutingError(e, request, attachmentReader, callback);
        return;
    }
    final RequestExecutionCallback<RestResponse> wrappedCallback = notifyInvokeAwares(method, callback);
    RequestExecutionReportBuilder requestExecutionReportBuilder = null;
    if (isDebugMode) {
        requestExecutionReportBuilder = new RequestExecutionReportBuilder();
    }
    final FilterRequestContextInternal filterContext = new FilterRequestContextInternalImpl((ServerResourceContext) method.getContext(), method.getResourceMethod());
    RestLiArgumentBuilder adapter;
    try {
        RestUtils.validateRequestHeadersAndUpdateResourceContext(request.getHeaders(), (ServerResourceContext) method.getContext());
        adapter = buildRestLiArgumentBuilder(method, _errorResponseBuilder);
        filterContext.setRequestData(adapter.extractRequestData(method, request));
    } catch (Exception e) {
        // would not trigger response filters because request filters haven't run yet
        wrappedCallback.onError(e, requestExecutionReportBuilder == null ? null : requestExecutionReportBuilder.build(), ((ServerResourceContext) method.getContext()).getRequestAttachmentReader(), null);
        return;
    }
    RestLiFilterResponseContextFactory<Object> filterResponseContextFactory = new RestLiFilterResponseContextFactory<Object>(request, method, _responseHandler);
    FilterChainCallback filterChainCallback = new FilterChainCallbackImpl(method, _methodInvoker, adapter, requestExecutionReportBuilder, attachmentReader, _responseHandler, wrappedCallback);
    RestLiFilterChain filterChain = new RestLiFilterChain(_filters, filterChainCallback);
    filterChain.onRequest(filterContext, filterResponseContextFactory);
}
Also used : FilterRequestContextInternalImpl(com.linkedin.restli.internal.server.filter.FilterRequestContextInternalImpl) RestResponse(com.linkedin.r2.message.rest.RestResponse) RestLiArgumentBuilder(com.linkedin.restli.internal.server.methods.arguments.RestLiArgumentBuilder) MultiPartIllegalFormatException(com.linkedin.multipart.exceptions.MultiPartIllegalFormatException) ParseException(javax.mail.internet.ParseException) RestException(com.linkedin.r2.message.rest.RestException) RestLiAttachmentReaderException(com.linkedin.restli.common.attachments.RestLiAttachmentReaderException) RestLiFilterChain(com.linkedin.restli.internal.server.filter.RestLiFilterChain) RoutingResult(com.linkedin.restli.internal.server.RoutingResult) FilterChainCallback(com.linkedin.restli.internal.server.filter.FilterChainCallback) RestLiFilterResponseContextFactory(com.linkedin.restli.internal.server.filter.RestLiFilterResponseContextFactory) FilterRequestContextInternal(com.linkedin.restli.internal.server.filter.FilterRequestContextInternal) ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext) FilterChainCallbackImpl(com.linkedin.restli.internal.server.filter.FilterChainCallbackImpl)

Example 75 with Response

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

the class TestRouteLookupClient method testRouteLookupClientCallback.

@Test
public void testRouteLookupClientCallback() throws InterruptedException, ExecutionException, TimeoutException {
    RouteLookup routeLookup = new SimpleTestRouteLookup();
    final D2Client d2Client = new D2ClientBuilder().setZkHosts("localhost:2121").build();
    d2Client.start(new FutureCallback<None>());
    RouteLookupClient routeLookupClient = new RouteLookupClient(d2Client, routeLookup, "WestCoast");
    RestRequest dummyRestRequest = new RestRequestBuilder(URI.create("d2://simple_uri")).build();
    FutureCallback<RestResponse> futureCallback = new FutureCallback<RestResponse>();
    routeLookupClient.restRequest(dummyRestRequest, futureCallback, "5555");
    try {
        RestResponse response = futureCallback.get(10, TimeUnit.SECONDS);
        Assert.fail("Unexpected success, request should have thrown a ServiceUnavailableException");
    } catch (Exception e) {
        String message = e.getMessage();
        if (!message.contains("_serviceName=simple_uriWestCoast5555Foo")) {
            Assert.fail("request was not rewritten to point at the d2 service simple_uriWestCoast5555Foo");
        }
    }
}
Also used : D2Client(com.linkedin.d2.balancer.D2Client) RestResponse(com.linkedin.r2.message.rest.RestResponse) D2ClientBuilder(com.linkedin.d2.balancer.D2ClientBuilder) TimeoutException(java.util.concurrent.TimeoutException) ExecutionException(java.util.concurrent.ExecutionException) RestRequest(com.linkedin.r2.message.rest.RestRequest) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) None(com.linkedin.common.util.None) FutureCallback(com.linkedin.common.callback.FutureCallback) Test(org.testng.annotations.Test)

Aggregations

RestResponse (com.linkedin.r2.message.rest.RestResponse)100 Test (org.testng.annotations.Test)95 RestRequest (com.linkedin.r2.message.rest.RestRequest)63 RequestContext (com.linkedin.r2.message.RequestContext)51 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)47 URI (java.net.URI)45 ByteString (com.linkedin.data.ByteString)42 StreamResponse (com.linkedin.r2.message.stream.StreamResponse)37 RestException (com.linkedin.r2.message.rest.RestException)32 HashMap (java.util.HashMap)29 FutureCallback (com.linkedin.common.callback.FutureCallback)25 StreamRequest (com.linkedin.r2.message.stream.StreamRequest)25 ExecutionException (java.util.concurrent.ExecutionException)25 RestResponseBuilder (com.linkedin.r2.message.rest.RestResponseBuilder)24 StreamRequestBuilder (com.linkedin.r2.message.stream.StreamRequestBuilder)22 CountDownLatch (java.util.concurrent.CountDownLatch)22 URISyntaxException (java.net.URISyntaxException)21 TransportCallback (com.linkedin.r2.transport.common.bridge.common.TransportCallback)18 IOException (java.io.IOException)18 Map (java.util.Map)17