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);
}
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 } };
}
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);
}
}
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);
}
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");
}
}
}
Aggregations