use of com.linkedin.restli.server.RestLiResponseData in project rest.li by linkedin.
the class TestRestLiCallback method testOnErrorWithFiltersExceptionFromFirstFilterSecondFilterDoesNotHandle.
@SuppressWarnings("unchecked")
@Test
public void testOnErrorWithFiltersExceptionFromFirstFilterSecondFilterDoesNotHandle() throws Exception {
// App stuff.
RestLiServiceException exFromApp = new RestLiServiceException(HttpStatus.S_404_NOT_FOUND, "App failure");
RestLiResponseData<CreateResponseEnvelope> responseAppData = ResponseDataBuilderUtil.buildCreateResponseData(exFromApp);
// Filter stuff.
final Exception exFromFirstFilter = new RuntimeException("Runtime exception from first filter");
RestLiResponse partialResponse = new RestLiResponse.Builder().build();
// Setup.
when(_responseHandler.buildExceptionResponseData(eq(_routingResult), any(RestLiServiceException.class), anyMap(), anyList())).thenReturn(responseAppData);
when(_responseHandler.buildPartialResponse(_routingResult, responseAppData)).thenReturn(partialResponse);
when(_restRequest.getHeaders()).thenReturn(null);
Map<String, String> errorHeaders = buildErrorHeaders();
// Mock filter behavior.
doThrow(exFromFirstFilter).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];
// The second filter should be invoked with original exception
RestLiResponseData<CreateResponseEnvelope> responseData = (RestLiResponseData<CreateResponseEnvelope>) responseContext.getResponseData();
assertEquals(responseData.getResponseEnvelope().getStatus(), HttpStatus.S_500_INTERNAL_SERVER_ERROR);
assertNull(responseData.getResponseEnvelope().getRecord());
assertEquals(responseData.getHeaders(), errorHeaders);
assertTrue(responseData.getResponseEnvelope().isErrorResponse());
// Modify data.
setStatus(responseContext, HttpStatus.S_402_PAYMENT_REQUIRED);
// filter.
return completedFutureWithError(responseData.getResponseEnvelope().getException());
}
}).when(_filter).onError(any(Throwable.class), eq(_filterRequestContext), any(FilterResponseContext.class));
// 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);
// Verify.
ArgumentCaptor<RestLiServiceException> exCapture = ArgumentCaptor.forClass(RestLiServiceException.class);
verify(_responseHandler).buildExceptionResponseData(eq(_routingResult), exCapture.capture(), anyMap(), anyList());
verify(_responseHandler).buildPartialResponse(_routingResult, responseAppData);
ArgumentCaptor<RestLiResponseException> partialRestResponseExceptionCaptor = ArgumentCaptor.forClass(RestLiResponseException.class);
verify(_callback).onError(partialRestResponseExceptionCaptor.capture());
verify(_restRequest).getHeaders();
verifyNoMoreInteractions(_restRequest, _responseHandler, _callback);
assertNotNull(responseAppData);
assertEquals(HttpStatus.S_402_PAYMENT_REQUIRED, responseAppData.getResponseEnvelope().getStatus());
assertEquals(responseAppData.getHeaders(), errorHeaders);
assertNull(responseAppData.getResponseEnvelope().getRecord());
RestLiServiceException restliEx = exCapture.getAllValues().get(0);
assertNotNull(restliEx);
assertEquals(exFromApp.getStatus(), restliEx.getStatus());
assertEquals(exFromApp.getMessage(), restliEx.getMessage());
RestLiResponseException restLiResponseException = partialRestResponseExceptionCaptor.getValue();
assertEquals(restLiResponseException.getRestLiResponse(), partialResponse);
assertTrue(restLiResponseException.getCause() instanceof RestLiServiceException);
restliEx = (RestLiServiceException) restLiResponseException.getCause();
assertEquals(HttpStatus.S_402_PAYMENT_REQUIRED, restliEx.getStatus());
}
use of com.linkedin.restli.server.RestLiResponseData 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");
RestLiResponseData<CreateResponseEnvelope> appResponseData = ResponseDataBuilderUtil.buildCreateResponseData(HttpStatus.S_200_OK, entityFromApp);
// 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);
RestLiResponseData<CreateResponseEnvelope> responseErrorData = new RestLiResponseDataImpl<>(new CreateResponseEnvelope(exception, false), headersFromFilter, Collections.emptyList());
RestLiResponse partialFilterErrorResponse = new RestLiResponse.Builder().build();
final Throwable throwableFromFilter = new NoSuchMethodError("Method foo not found!");
// Common stuff.
RestException finalRestException = new RestException(new RestResponseBuilder().build());
// Setup.
when((RestLiResponseData<CreateResponseEnvelope>) _responseHandler.buildRestLiResponseData(_restRequest, _routingResult, entityFromApp)).thenReturn(appResponseData);
when(_restRequest.getHeaders()).thenReturn(null);
when(_responseHandler.buildExceptionResponseData(eq(_routingResult), any(RestLiServiceException.class), anyMap(), anyList())).thenReturn(responseErrorData);
when(_responseHandler.buildPartialResponse(_routingResult, responseErrorData)).thenReturn(partialFilterErrorResponse);
// 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);
// Verify.
verify(_responseHandler).buildRestLiResponseData(_restRequest, _routingResult, entityFromApp);
verify(_responseHandler).buildPartialResponse(_routingResult, appResponseData);
ArgumentCaptor<RestLiResponseException> partialRestResponseExceptionCaptor = ArgumentCaptor.forClass(RestLiResponseException.class);
verify(_callback).onError(partialRestResponseExceptionCaptor.capture());
verifyNoMoreInteractions(_responseHandler, _callback);
RestLiResponseException restLiResponseException = partialRestResponseExceptionCaptor.getValue();
assertTrue(restLiResponseException.getCause() instanceof RestLiServiceException);
RestLiServiceException restliEx1 = (RestLiServiceException) restLiResponseException.getCause();
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.getResponseEnvelope().getStatus());
assertEquals(responseErrorData.getHeaders(), headersFromFilter);
assertNull(responseErrorData.getResponseEnvelope().getRecord());
}
use of com.linkedin.restli.server.RestLiResponseData in project rest.li by linkedin.
the class TestRestLiCallback method testOnSuccessWithFiltersExceptionFromSecondFilter.
@SuppressWarnings("unchecked")
@Test
public void testOnSuccessWithFiltersExceptionFromSecondFilter() throws Exception {
// App stuff.
String result = "foo";
RestLiResponseData<GetResponseEnvelope> appResponseData = ResponseDataBuilderUtil.buildGetResponseData(HttpStatus.S_200_OK, null);
// Filter stuff.
ArgumentCaptor<RestLiServiceException> exFromFilterCapture = ArgumentCaptor.forClass(RestLiServiceException.class);
final Map<String, String> headersFromFilter = Maps.newHashMap();
headersFromFilter.put("Key", "Error from filter");
RestLiServiceException exception = new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR);
RestLiResponseData<?> filterResponseData = new RestLiResponseDataImpl<>(new GetResponseEnvelope(exception), headersFromFilter, Collections.emptyList());
RestLiResponse partialFilterErrorResponse = new RestLiResponse.Builder().build();
final Exception exFromFilter = new RuntimeException("Exception From Filter");
// Common stuff.
RestException finalRestException = new RestException(new RestResponseBuilder().build());
// Setup.
when((RestLiResponseData<GetResponseEnvelope>) _responseHandler.buildRestLiResponseData(_restRequest, _routingResult, result)).thenReturn(appResponseData);
when(_restRequest.getHeaders()).thenReturn(null);
when(_responseHandler.buildExceptionResponseData(eq(_routingResult), exFromFilterCapture.capture(), anyMap(), anyList())).thenReturn(filterResponseData);
when(_responseHandler.buildPartialResponse(_routingResult, appResponseData)).thenReturn(partialFilterErrorResponse);
// Mock filter behavior.
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
FilterRequestContext requestContext = (FilterRequestContext) args[0];
FilterResponseContext responseContext = (FilterResponseContext) args[1];
RestLiResponseData<GetResponseEnvelope> responseData = (RestLiResponseData<GetResponseEnvelope>) responseContext.getResponseData();
// The second filter should be invoked with details of the exception thrown by the first
// filter. Verify incoming data.
assertEquals(responseData.getResponseEnvelope().getStatus(), HttpStatus.S_200_OK);
assertNull(responseData.getResponseEnvelope().getRecord());
assertTrue(responseData.getHeaders().isEmpty());
// Modify data.
setStatus(responseContext, HttpStatus.S_402_PAYMENT_REQUIRED);
responseData.getHeaders().put("first-filter", "success");
return CompletableFuture.completedFuture(null);
}
}).doThrow(exFromFilter).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));
_twoFilterChain.onRequest(_filterRequestContext, _filterResponseContextFactory);
// Invoke.
_twoFilterRestLiCallback.onSuccess(result);
// Verify.
verify(_responseHandler).buildPartialResponse(_routingResult, appResponseData);
verify(_responseHandler).buildRestLiResponseData(_restRequest, _routingResult, result);
verify(_responseHandler).buildPartialResponse(_routingResult, appResponseData);
ArgumentCaptor<RestLiResponseException> partialRestResponseExceptionCaptor = ArgumentCaptor.forClass(RestLiResponseException.class);
verify(_callback).onError(partialRestResponseExceptionCaptor.capture());
verifyNoMoreInteractions(_responseHandler, _callback);
RestLiResponseException restLiResponseException = partialRestResponseExceptionCaptor.getValue();
assertTrue(restLiResponseException.getCause() instanceof RestLiServiceException);
RestLiServiceException restliEx1 = (RestLiServiceException) restLiResponseException.getCause();
assertNotNull(restliEx1);
assertEquals(HttpStatus.S_500_INTERNAL_SERVER_ERROR, restliEx1.getStatus());
assertEquals(exFromFilter.getMessage(), restliEx1.getMessage());
assertEquals(exFromFilter, restliEx1.getCause());
Map<String, String> expectedHeaders = buildErrorHeaders();
expectedHeaders.put("first-filter", "success");
assertNotNull(appResponseData);
assertEquals(HttpStatus.S_500_INTERNAL_SERVER_ERROR, appResponseData.getResponseEnvelope().getStatus());
assertEquals(appResponseData.getHeaders(), expectedHeaders);
assertNull(appResponseData.getResponseEnvelope().getRecord());
}
use of com.linkedin.restli.server.RestLiResponseData in project rest.li by linkedin.
the class TestRestLiFilterResponseContextFactory method testFromResult.
@Test
@SuppressWarnings("unchecked")
public void testFromResult() throws Exception {
DataMap dataMap = new DataMap();
dataMap.put("foo", "bar");
Map<String, String> headers = Maps.newHashMap();
headers.put("x", "y");
RecordTemplate entity1 = new Foo(dataMap);
RestLiResponseData<GetResponseEnvelope> responseData = new RestLiResponseDataImpl<>(new GetResponseEnvelope(HttpStatus.S_200_OK, entity1), headers, Collections.emptyList());
when((RestLiResponseData<GetResponseEnvelope>) _responseHandler.buildRestLiResponseData(_restRequest, _routingResult, entity1)).thenReturn(responseData);
FilterResponseContext responseContext = _filterResponseContextFactory.fromResult(entity1);
assertEquals(responseContext.getResponseData(), responseData);
verify(_responseHandler).buildRestLiResponseData(_restRequest, _routingResult, entity1);
}
use of com.linkedin.restli.server.RestLiResponseData in project rest.li by linkedin.
the class TestRestLiMethodInvocation method testInvokerWithFilters.
@Test(dataProvider = "provideFilterConfig")
public void testInvokerWithFilters(final boolean throwExceptionFromFirstFilter) throws Exception {
RestLiArgumentBuilder mockArgumentBuilder = createMock(RestLiArgumentBuilder.class);
Filter mockFilter = createMock(Filter.class);
@SuppressWarnings("unchecked") Callback<Object> mockCallback = createMock(Callback.class);
FilterRequestContext mockFilterContext = createMock(FilterRequestContext.class);
RestLiRequestData requestData = new RestLiRequestDataImpl.Builder().key("Key").build();
RestLiMethodInvoker invokerWithFilters = new RestLiMethodInvoker(_resourceFactory, _engine, ErrorResponseBuilder.DEFAULT_INTERNAL_ERROR_MESSAGE);
Map<String, ResourceModel> resourceModelMap = buildResourceModels(StatusCollectionResource.class, LocationResource.class, DiscoveredItemsResource.class);
ResourceModel statusResourceModel = resourceModelMap.get("/statuses");
ResourceMethodDescriptor resourceMethodDescriptor = statusResourceModel.findMethod(ResourceMethod.GET);
final StatusCollectionResource resource = getMockResource(StatusCollectionResource.class);
RestRequestBuilder builder = new RestRequestBuilder(new URI("/statuses/1")).setMethod("GET").addHeaderValue("Accept", "application/json").setHeader(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, AllProtocolVersions.LATEST_PROTOCOL_VERSION.toString());
RestRequest request = builder.build();
RoutingResult routingResult = new RoutingResult(new ResourceContextImpl(buildPathKeys("statusID", 1L), request, new RequestContext()), resourceMethodDescriptor);
expectLastCall();
FilterChainDispatcher filterChainDispatcher = new FilterChainDispatcher() {
@Override
public void onRequestSuccess(RestLiRequestData requestData, RestLiCallback restLiCallback) {
// only invoke if filter chain's requests were successful
invokerWithFilters.invoke(requestData, routingResult, mockArgumentBuilder, restLiCallback);
}
};
FilterChainCallback filterChainCallback = new FilterChainCallback() {
@Override
public void onResponseSuccess(RestLiResponseData<?> responseData) {
// unused
}
@Override
public void onError(Throwable th, RestLiResponseData<?> responseData) {
// unused
}
};
final Exception exFromFilter = new RuntimeException("Exception from filter!");
if (throwExceptionFromFirstFilter) {
mockFilter.onRequest(eq(mockFilterContext));
expectLastCall().andThrow(exFromFilter);
mockCallback.onError(eq(exFromFilter));
} else {
expect(mockFilterContext.getRequestData()).andReturn(requestData).times(3);
mockFilter.onRequest(eq(mockFilterContext));
expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
FilterRequestContext filterContext = (FilterRequestContext) getCurrentArguments()[0];
RestLiRequestData data = filterContext.getRequestData();
// Verify incoming data.
assertEquals(data.getKey(), "Key");
// Update data.
data.setKey("Key-Filter1");
return CompletableFuture.completedFuture(null);
}
}).andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
FilterRequestContext filterContext = (FilterRequestContext) getCurrentArguments()[0];
RestLiRequestData data = filterContext.getRequestData();
// Verify incoming data.
assertEquals(data.getKey(), "Key-Filter1");
// Update data.
data.setKey("Key-Filter2");
return CompletableFuture.completedFuture(null);
}
});
Long[] argsArray = { 1L };
expect(mockArgumentBuilder.buildArguments(requestData, routingResult)).andReturn(argsArray);
expect(resource.get(eq(1L))).andReturn(null).once();
mockCallback.onSuccess(eq(null));
}
replay(resource, mockArgumentBuilder, mockFilterContext, mockFilter, mockCallback);
RestUtils.validateRequestHeadersAndUpdateResourceContext(request.getHeaders(), Collections.emptySet(), routingResult.getContext());
RestLiFilterChain filterChain = new RestLiFilterChain(Arrays.asList(mockFilter, mockFilter), filterChainDispatcher, filterChainCallback);
filterChain.onRequest(mockFilterContext, new RestLiFilterResponseContextFactory(request, routingResult, new RestLiResponseHandler(_methodAdapterProvider, _errorResponseBuilder)));
verifyRecording(mockArgumentBuilder, mockFilterContext, mockFilter);
if (throwExceptionFromFirstFilter) {
assertEquals(requestData.getKey(), "Key");
} else {
assertEquals(requestData.getKey(), "Key-Filter2");
verify(resource);
}
EasyMock.reset(resource);
EasyMock.makeThreadSafe(resource, true);
}
Aggregations