use of com.linkedin.r2.message.Request in project rest.li by linkedin.
the class TestParseqTraceDebugRequestHandler method testStaticContent.
/**
* Tests the static content retrieval from the parseq trace debug request handler. It enumerates through all
* files imported into the JAR containing the parseq trace debug request handler, skips the ones that should
* not be served and verifies the rest can be retrieved. This test makes sure all files we import are actually
* servicable by the parseq trace debug request handler.
* @throws IOException
*/
@Test
public void testStaticContent() throws IOException {
ClassLoader classLoader = ParseqTraceDebugRequestHandler.class.getClassLoader();
//Collect all files under tracevis folder in the jar containing the parseq trace debug request handler.
Enumeration<URL> resources = classLoader.getResources(ParseqTraceDebugRequestHandler.class.getName().replace('.', '/') + ".class");
List<String> files = new ArrayList<String>();
while (resources.hasMoreElements()) {
URL url = resources.nextElement();
URLConnection urlConnection = url.openConnection();
if (urlConnection instanceof JarURLConnection) {
JarURLConnection jarURLConnection = (JarURLConnection) urlConnection;
JarFile jar = jarURLConnection.getJarFile();
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry currentEntry = entries.nextElement();
if (!currentEntry.isDirectory()) {
String entry = currentEntry.getName();
if (entry.startsWith("tracevis/")) {
files.add(entry);
}
}
}
}
}
Assert.assertTrue(files.size() > 0);
// All other files should be retrievable from the parseq trace debug request handler.
for (String file : files) {
final String mimeType = determineMediaType(file);
final URI uri = URI.create("http://host/abc/12/__debug/parseqtrace/" + file.substring(file.indexOf('/') + 1));
executeRequestThroughParseqDebugHandler(uri, new RequestExecutionCallback<RestResponse>() {
@Override
public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
Assert.fail("Static content cannot be retrieved for " + uri.toString());
}
@Override
public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
Assert.assertEquals(result.getHeader(RestConstants.HEADER_CONTENT_TYPE), mimeType);
}
});
}
}
use of com.linkedin.r2.message.Request in project rest.li by linkedin.
the class TestParseqTraceDebugRequestHandler method executeRequestThroughParseqDebugHandler.
private void executeRequestThroughParseqDebugHandler(URI uri, RequestExecutionCallback<RestResponse> callback) {
ParseqTraceDebugRequestHandler requestHandler = new ParseqTraceDebugRequestHandler();
RestRequestBuilder requestBuilder = new RestRequestBuilder(uri);
RestRequest request = requestBuilder.build();
RequestContext requestContext = new RequestContext();
requestHandler.handleRequest(request, requestContext, new RestLiDebugRequestHandler.ResourceDebugRequestHandler() {
@Override
public void handleRequest(RestRequest request, RequestContext requestContext, RequestExecutionCallback<RestResponse> callback) {
RestResponse response = EasyMock.createMock(RestResponse.class);
RequestExecutionReportBuilder executionReportBuilder = new RequestExecutionReportBuilder();
JsonTraceCodec jsonTraceCodec = new JsonTraceCodec();
Trace t = null;
try {
t = jsonTraceCodec.decode(TEST_TRACE);
executionReportBuilder.setParseqTrace(t);
} catch (IOException exc) {
//test will fail later
}
callback.onSuccess(response, executionReportBuilder.build(), null);
}
}, null, callback);
}
use of com.linkedin.r2.message.Request in project rest.li by linkedin.
the class TestStreamingGreetings method testDeleteReturnAttachments.
//The delete and update tests here are simply to show that although not typical, it is possible to return
//attachments from DELETE, UPDATE, PARTIAL_UPDATE, BATCH_DELETE, BATCH_UPDATE, and BATCH_PARTIAL_UPDATE. For the sake of
//brevity DELETE and UPDATE are used as examples.
@Test(dataProvider = com.linkedin.restli.internal.common.TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "requestBuilderDataProvider")
public void testDeleteReturnAttachments(final RootBuilderWrapper<Long, Greeting> builders) throws RemoteInvocationException {
try {
//This will be echoed back in the form of an attachment.
final String headerAndAttachment = "someValue";
final Request<EmptyRecord> deleteRequest = builders.delete().id(1l).setHeader("getHeader", headerAndAttachment).build();
sendNonTypicalRequestAndVerifyAttachments(deleteRequest, headerAndAttachment);
} catch (Exception exception) {
Assert.fail();
}
}
use of com.linkedin.r2.message.Request in project rest.li by linkedin.
the class TestRestLiCallback method testOnErrorWithFiltersSuccessfulyHandlingAppEx.
@SuppressWarnings("unchecked")
@Test
public void testOnErrorWithFiltersSuccessfulyHandlingAppEx() throws Exception {
Exception exFromApp = new RuntimeException("Runtime exception from app");
RestLiServiceException appException = new RestLiServiceException(HttpStatus.S_404_NOT_FOUND);
RequestExecutionReport executionReport = new RequestExecutionReportBuilder().build();
RestLiResponseAttachments responseAttachments = new RestLiResponseAttachments.Builder().build();
final Map<String, String> headersFromApp = Maps.newHashMap();
headersFromApp.put("Key", "Input");
final RecordTemplate entityFromFilter = Foo.createFoo("Key", "Two");
final Map<String, String> headersFromFilter = Maps.newHashMap();
headersFromFilter.put("Key", "Output");
RestLiResponseDataImpl responseData = new RestLiResponseDataImpl(appException, headersFromApp, Collections.<HttpCookie>emptyList());
responseData.setResponseEnvelope(new CreateResponseEnvelope(new EmptyRecord(), responseData));
PartialRestResponse partialResponse = new PartialRestResponse.Builder().build();
ArgumentCaptor<RestLiServiceException> exCapture = ArgumentCaptor.forClass(RestLiServiceException.class);
when(_requestExecutionReportBuilder.build()).thenReturn(executionReport);
when(_responseHandler.buildExceptionResponseData(eq(_restRequest), eq(_routingResult), exCapture.capture(), anyMap(), anyList())).thenReturn(responseData);
when(_responseHandler.buildPartialResponse(_routingResult, responseData)).thenReturn(partialResponse);
// Mock the behavior of the first filter.
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
Throwable t = (Throwable) args[0];
FilterRequestContext requestContext = (FilterRequestContext) args[1];
FilterResponseContext responseContext = (FilterResponseContext) args[2];
// Verify incoming data.
assertEquals(HttpStatus.S_404_NOT_FOUND, responseContext.getResponseData().getStatus());
assertEquals(headersFromApp, responseContext.getResponseData().getHeaders());
assertNull(responseContext.getResponseData().getRecordResponseEnvelope().getRecord());
// Modify data in filter.
setStatus(responseContext, HttpStatus.S_400_BAD_REQUEST);
responseContext.getResponseData().getHeaders().clear();
return CompletableFuture.completedFuture(null);
}
}).when(_filter).onError(any(Throwable.class), eq(_filterRequestContext), any(FilterResponseContext.class));
doAnswer(new Answer<Object>() {
// Mock the behavior of the second filter.
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
FilterRequestContext requestContext = (FilterRequestContext) args[0];
FilterResponseContext responseContext = (FilterResponseContext) args[1];
// Verify incoming data.
assertEquals(HttpStatus.S_400_BAD_REQUEST, responseContext.getResponseData().getStatus());
assertTrue(responseContext.getResponseData().getHeaders().isEmpty());
assertNull(responseContext.getResponseData().getRecordResponseEnvelope().getRecord());
// Modify data in filter.
setStatus(responseContext, HttpStatus.S_403_FORBIDDEN);
responseContext.getResponseData().getRecordResponseEnvelope().setRecord(entityFromFilter, HttpStatus.S_403_FORBIDDEN);
responseContext.getResponseData().getHeaders().putAll(headersFromFilter);
return CompletableFuture.completedFuture(null);
}
}).when(_filter).onResponse(eq(_filterRequestContext), any(FilterResponseContext.class));
RestResponse restResponse = new RestResponseBuilder().build();
when(_responseHandler.buildResponse(_routingResult, partialResponse)).thenReturn(restResponse);
// invoke request filters so cursor is in correct place
when(_filter.onRequest(any(FilterRequestContext.class))).thenReturn(CompletableFuture.completedFuture(null));
_twoFilterChain.onRequest(_filterRequestContext, _filterResponseContextFactory);
// Invoke.
_twoFilterRestLiCallback.onError(exFromApp, executionReport, _requestAttachmentReader, responseAttachments);
// Verify.
assertNotNull(responseData);
assertEquals(HttpStatus.S_403_FORBIDDEN, responseData.getStatus());
assertEquals(entityFromFilter, responseData.getRecordResponseEnvelope().getRecord());
assertEquals(headersFromFilter, responseData.getHeaders());
verify(_responseHandler).buildExceptionResponseData(eq(_restRequest), eq(_routingResult), exCapture.capture(), anyMap(), anyList());
verify(_responseHandler).buildPartialResponse(_routingResult, responseData);
verify(_responseHandler).buildResponse(_routingResult, partialResponse);
verify(_callback).onSuccess(restResponse, executionReport, responseAttachments);
verify(_restRequest, times(1)).getHeaders();
verifyZeroInteractions(_routingResult);
verifyNoMoreInteractions(_restRequest, _responseHandler, _callback);
RestLiServiceException restliEx = exCapture.getValue();
assertNotNull(restliEx);
assertEquals(HttpStatus.S_500_INTERNAL_SERVER_ERROR, restliEx.getStatus());
assertEquals(exFromApp.getMessage(), restliEx.getMessage());
assertEquals(exFromApp, restliEx.getCause());
}
use of com.linkedin.r2.message.Request in project rest.li by linkedin.
the class TestRestLiCallback method testOnSuccessWithFilterThrowable.
@SuppressWarnings("unchecked")
@Test
public void testOnSuccessWithFilterThrowable() throws Exception {
// App stuff.
final RecordTemplate entityFromApp = Foo.createFoo("Key", "Two");
RequestExecutionReport executionReport = new RequestExecutionReportBuilder().build();
RestLiResponseAttachments responseAttachments = new RestLiResponseAttachments.Builder().build();
RestLiResponseDataImpl appResponseData = new RestLiResponseDataImpl(HttpStatus.S_200_OK, Collections.<String, String>emptyMap(), Collections.<HttpCookie>emptyList());
appResponseData.setResponseEnvelope(new CreateResponseEnvelope(entityFromApp, appResponseData));
// Filter stuff.
final Map<String, String> headersFromFilter = Maps.newHashMap();
headersFromFilter.put("Key", "Error from filter");
RestLiServiceException exception = new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR);
RestLiResponseDataImpl responseErrorData = new RestLiResponseDataImpl(exception, headersFromFilter, Collections.<HttpCookie>emptyList());
responseErrorData.setResponseEnvelope(new CreateResponseEnvelope(new EmptyRecord(), responseErrorData));
PartialRestResponse partialFilterErrorResponse = new PartialRestResponse.Builder().build();
final Throwable throwableFromFilter = new NoSuchMethodError("Method foo not found!");
// Common stuff.
RestException finalRestException = new RestException(new RestResponseBuilder().build());
// Setup.
when(_requestExecutionReportBuilder.build()).thenReturn(executionReport);
when(_responseHandler.buildRestLiResponseData(_restRequest, _routingResult, entityFromApp)).thenReturn(appResponseData);
when(_restRequest.getHeaders()).thenReturn(null);
when(_responseHandler.buildExceptionResponseData(eq(_restRequest), eq(_routingResult), any(RestLiServiceException.class), anyMap(), anyList())).thenReturn(responseErrorData);
when(_responseHandler.buildPartialResponse(_routingResult, responseErrorData)).thenReturn(partialFilterErrorResponse);
when(_responseHandler.buildRestException(any(RestLiServiceException.class), any(PartialRestResponse.class))).thenReturn(finalRestException);
// Mock filter behavior.
doThrow(throwableFromFilter).when(_filter).onResponse(eq(_filterRequestContext), any(FilterResponseContext.class));
// invoke request filters so cursor is in correct place
when(_filter.onRequest(any(FilterRequestContext.class))).thenReturn(CompletableFuture.completedFuture(null));
_oneFilterChain.onRequest(_filterRequestContext, _filterResponseContextFactory);
// Invoke.
_oneFilterRestLiCallback.onSuccess(entityFromApp, executionReport, responseAttachments);
// Verify.
verify(_responseHandler).buildRestLiResponseData(_restRequest, _routingResult, entityFromApp);
verify(_responseHandler).buildPartialResponse(_routingResult, appResponseData);
ArgumentCaptor<RestLiServiceException> exFromFilterCapture = ArgumentCaptor.forClass(RestLiServiceException.class);
verify(_responseHandler).buildRestException(exFromFilterCapture.capture(), any(PartialRestResponse.class));
verify(_callback).onError(finalRestException, executionReport, _requestAttachmentReader, responseAttachments);
verifyZeroInteractions(_routingResult);
verifyNoMoreInteractions(_responseHandler, _callback);
final RestLiServiceException restliEx1 = exFromFilterCapture.getAllValues().get(0);
assertNotNull(restliEx1);
assertEquals(HttpStatus.S_500_INTERNAL_SERVER_ERROR, restliEx1.getStatus());
assertEquals(throwableFromFilter.getMessage(), restliEx1.getMessage());
assertEquals(throwableFromFilter, restliEx1.getCause());
assertNotNull(responseErrorData);
assertEquals(HttpStatus.S_500_INTERNAL_SERVER_ERROR, responseErrorData.getStatus());
assertEquals(responseErrorData.getHeaders(), headersFromFilter);
assertNull(responseErrorData.getRecordResponseEnvelope().getRecord());
}
Aggregations