use of com.linkedin.restli.server.filter.FilterRequestContext in project rest.li by linkedin.
the class TestFilterRequestContextInternalImpl method testCustomContextData.
@Test
public void testCustomContextData() {
FilterRequestContext filterContext = new FilterRequestContextInternalImpl(context, resourceMethod, null);
filterContext.putCustomContextData("foo", "bar");
filterContext.getCustomContextData("foo");
filterContext.removeCustomContextData("foo");
verify(context, times(1)).putCustomContextData("foo", "bar");
verify(context, times(1)).getCustomContextData("foo");
verify(context, times(1)).removeCustomContextData("foo");
}
use of com.linkedin.restli.server.filter.FilterRequestContext in project rest.li by linkedin.
the class TestRestLiValidationFilter method testSkipRequestValidation.
/**
* Ensures that the validation filter skips request validation by feeding it with invalid data, and ensuring that it
* never throws an error.
*/
@Test(dataProvider = "invalidRequests")
@SuppressWarnings({ "unchecked" })
public void testSkipRequestValidation(ResourceModel resourceModel, ResourceMethod resourceMethod, RestLiRequestData restLiRequestData) {
when(filterRequestContext.getRequestData()).thenReturn(restLiRequestData);
when(filterRequestContext.getMethodType()).thenReturn(resourceMethod);
when(filterRequestContext.getFilterResourceModel()).thenReturn(new FilterResourceModelImpl(resourceModel));
when(filterRequestContext.getRestliProtocolVersion()).thenReturn(AllProtocolVersions.LATEST_PROTOCOL_VERSION);
RestLiValidationFilter validationFilter = new RestLiValidationFilter(Collections.emptyList(), new MockValidationErrorHandler()) {
@Override
protected boolean shouldValidateOnRequest(FilterRequestContext requestContext) {
return false;
}
};
try {
validationFilter.onRequest(filterRequestContext);
} catch (RestLiServiceException ex) {
Assert.fail("An unexpected exception was thrown on request in the validation filter.", ex);
}
}
use of com.linkedin.restli.server.filter.FilterRequestContext in project rest.li by linkedin.
the class TestRestLiCallback method testOnErrorWithFiltersSuccessfullyHandlingAppEx.
@SuppressWarnings("unchecked")
@Test
public void testOnErrorWithFiltersSuccessfullyHandlingAppEx() throws Exception {
Exception exFromApp = new RuntimeException("Runtime exception from app");
RestLiServiceException appException = new RestLiServiceException(HttpStatus.S_404_NOT_FOUND);
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");
RestLiResponseData<CreateResponseEnvelope> responseData = new RestLiResponseDataImpl<>(new CreateResponseEnvelope(appException, false), headersFromApp, Collections.emptyList());
RestLiResponse partialResponse = new RestLiResponse.Builder().build();
ArgumentCaptor<RestLiServiceException> exCapture = ArgumentCaptor.forClass(RestLiServiceException.class);
when(_responseHandler.buildExceptionResponseData(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.
RestLiResponseData<CreateResponseEnvelope> responseData = (RestLiResponseData<CreateResponseEnvelope>) responseContext.getResponseData();
assertEquals(HttpStatus.S_404_NOT_FOUND, responseData.getResponseEnvelope().getStatus());
assertEquals(headersFromApp, responseData.getHeaders());
assertNull(responseData.getResponseEnvelope().getRecord());
// Modify data in filter.
setStatus(responseContext, HttpStatus.S_400_BAD_REQUEST);
responseData.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.
RestLiResponseData<CreateResponseEnvelope> responseData = (RestLiResponseData<CreateResponseEnvelope>) responseContext.getResponseData();
assertEquals(HttpStatus.S_400_BAD_REQUEST, responseData.getResponseEnvelope().getStatus());
assertTrue(responseData.getHeaders().isEmpty());
assertNull(responseData.getResponseEnvelope().getRecord());
// Modify data in filter.
setStatus(responseContext, HttpStatus.S_403_FORBIDDEN);
responseData.getResponseEnvelope().setRecord(entityFromFilter, HttpStatus.S_403_FORBIDDEN);
responseData.getHeaders().putAll(headersFromFilter);
return CompletableFuture.completedFuture(null);
}
}).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.onError(exFromApp);
// Verify.
assertNotNull(responseData);
assertEquals(HttpStatus.S_403_FORBIDDEN, responseData.getResponseEnvelope().getStatus());
assertEquals(entityFromFilter, responseData.getResponseEnvelope().getRecord());
assertEquals(headersFromFilter, responseData.getHeaders());
verify(_responseHandler).buildExceptionResponseData(eq(_routingResult), exCapture.capture(), anyMap(), anyList());
verify(_responseHandler).buildPartialResponse(_routingResult, responseData);
verify(_callback).onSuccess(partialResponse);
verify(_restRequest, times(1)).getHeaders();
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.restli.server.filter.FilterRequestContext in project rest.li by linkedin.
the class TestRestLiCallback method testOnErrorWithFiltersNotHandlingAppEx.
@SuppressWarnings({ "unchecked", "deprecation" })
@Test
public void testOnErrorWithFiltersNotHandlingAppEx() throws Exception {
Exception exFromApp = new RuntimeException("Runtime exception from app");
RestLiServiceException appException = new RestLiServiceException(HttpStatus.S_404_NOT_FOUND);
final Map<String, String> headersFromApp = Maps.newHashMap();
headersFromApp.put("Key", "Input");
final Map<String, String> headersFromFilter = Maps.newHashMap();
headersFromFilter.put("Key", "Output");
RestLiResponseData<CreateResponseEnvelope> responseData = new RestLiResponseDataImpl<>(new CreateResponseEnvelope(appException, false), headersFromApp, Collections.emptyList());
RestLiResponse partialResponse = new RestLiResponse.Builder().build();
when(_responseHandler.buildExceptionResponseData(eq(_routingResult), any(RestLiServiceException.class), 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.
RestLiResponseData<CreateResponseEnvelope> responseData = (RestLiResponseData<CreateResponseEnvelope>) responseContext.getResponseData();
assertEquals(HttpStatus.S_404_NOT_FOUND, responseData.getResponseEnvelope().getStatus());
assertEquals(headersFromApp, responseData.getHeaders());
assertNull(responseData.getResponseEnvelope().getRecord());
// Modify data in filter.
setStatus(responseContext, HttpStatus.S_400_BAD_REQUEST);
responseData.getHeaders().clear();
return completedFutureWithError(responseData.getResponseEnvelope().getException());
}
}).doAnswer(new Answer<Object>() {
// Mock the behavior of the second filter.
@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.
RestLiResponseData<CreateResponseEnvelope> responseData = (RestLiResponseData<CreateResponseEnvelope>) responseContext.getResponseData();
assertEquals(HttpStatus.S_400_BAD_REQUEST, responseData.getResponseEnvelope().getStatus());
assertNull(responseData.getResponseEnvelope().getRecord());
// Modify data in filter.
setStatus(responseContext, HttpStatus.S_403_FORBIDDEN);
responseData.getHeaders().putAll(headersFromFilter);
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.
assertNotNull(responseData);
assertEquals(HttpStatus.S_403_FORBIDDEN, responseData.getResponseEnvelope().getStatus());
assertNull(responseData.getResponseEnvelope().getRecord());
assertTrue(responseData.getResponseEnvelope().isErrorResponse());
assertEquals(responseData.getResponseEnvelope().getException().getErrorDetails(), appException.getErrorDetails());
assertEquals(responseData.getResponseEnvelope().getException().getOverridingFormat(), appException.getOverridingFormat());
assertEquals(responseData.getResponseEnvelope().getException().getServiceErrorCode(), appException.getServiceErrorCode());
assertEquals(responseData.getResponseEnvelope().getException().getMessage(), appException.getMessage());
Map<String, String> expectedHeaders = buildErrorHeaders();
expectedHeaders.put("Key", "Output");
assertEquals(expectedHeaders, responseData.getHeaders());
ArgumentCaptor<RestLiServiceException> exCapture = ArgumentCaptor.forClass(RestLiServiceException.class);
verify(_responseHandler, times(1)).buildExceptionResponseData(eq(_routingResult), exCapture.capture(), anyMap(), anyList());
verify(_responseHandler).buildPartialResponse(_routingResult, responseData);
ArgumentCaptor<RestLiResponseException> partialRestResponseExceptionCaptor = ArgumentCaptor.forClass(RestLiResponseException.class);
verify(_callback).onError(partialRestResponseExceptionCaptor.capture());
verify(_restRequest, times(1)).getHeaders();
verifyNoMoreInteractions(_restRequest, _responseHandler, _callback);
final RestLiServiceException restliEx1 = exCapture.getAllValues().get(0);
assertNotNull(restliEx1);
assertEquals(HttpStatus.S_500_INTERNAL_SERVER_ERROR, restliEx1.getStatus());
assertEquals(exFromApp.getMessage(), restliEx1.getMessage());
assertEquals(exFromApp, restliEx1.getCause());
RestLiResponseException restLiResponseException = partialRestResponseExceptionCaptor.getValue();
assertEquals(restLiResponseException.getRestLiResponse(), partialResponse);
assertTrue(restLiResponseException.getCause() instanceof RestLiServiceException);
RestLiServiceException restliEx2 = (RestLiServiceException) restLiResponseException.getCause();
assertNotNull(restliEx2);
assertEquals(HttpStatus.S_403_FORBIDDEN, restliEx2.getStatus());
}
use of com.linkedin.restli.server.filter.FilterRequestContext in project rest.li by linkedin.
the class TestRestLiCallback method testOnErrorWithFiltersExceptionFromFirstFilterSecondFilterHandles.
@SuppressWarnings({ "unchecked", "deprecation" })
@Test(dataProvider = "provideResponseEntities")
public void testOnErrorWithFiltersExceptionFromFirstFilterSecondFilterHandles(final ResourceMethod resourceMethod, final RestLiResponseData<?> responseAppData, final Object entityFromFilter2) throws Exception {
// App stuff.
RestLiServiceException exFromApp = new RestLiServiceException(HttpStatus.S_404_NOT_FOUND, "App failure");
// Filter stuff.
final Exception exFromFirstFilter = new RuntimeException("Runtime exception from first filter");
final Map<String, String> headersFromFilter = Maps.newHashMap();
headersFromFilter.put(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, AllProtocolVersions.LATEST_PROTOCOL_VERSION.toString());
String errorResponseHeaderName = HeaderUtil.getErrorResponseHeaderName(AllProtocolVersions.LATEST_PROTOCOL_VERSION);
headersFromFilter.put(errorResponseHeaderName, RestConstants.HEADER_VALUE_ERROR);
RestLiResponse partialResponse = new RestLiResponse.Builder().build();
ArgumentCaptor<RestLiServiceException> wrappedExCapture = ArgumentCaptor.forClass(RestLiServiceException.class);
final String customHeader = "Custom-Header";
final String customHeaderValue = "CustomValue";
// Setup.
when(_responseHandler.buildExceptionResponseData(eq(_routingResult), wrappedExCapture.capture(), anyMap(), anyList())).thenReturn(responseAppData);
when(_responseHandler.buildPartialResponse(_routingResult, responseAppData)).thenReturn(partialResponse);
when(_restRequest.getHeaders()).thenReturn(null);
// Mock filter behavior.
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
FilterRequestContext requestContext = (FilterRequestContext) args[1];
FilterResponseContext responseContext = (FilterResponseContext) args[2];
responseContext.getResponseData().getHeaders().putAll(headersFromFilter);
return completedFutureWithError(exFromFirstFilter);
}
}).doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
FilterRequestContext requestContext = (FilterRequestContext) args[1];
FilterResponseContext responseContext = (FilterResponseContext) args[2];
// The second filter should be invoked with details of the exception thrown by the first
// filter. Verify incoming data.
assertEquals(responseContext.getResponseData().getStatus(), HttpStatus.S_500_INTERNAL_SERVER_ERROR);
switch(ResponseTypeUtil.fromMethodType(resourceMethod)) {
case SINGLE_ENTITY:
assertNull(responseContext.getResponseData().getRecordResponseEnvelope().getRecord());
break;
case GET_COLLECTION:
assertNull(responseContext.getResponseData().getCollectionResponseEnvelope().getCollectionResponse());
break;
case CREATE_COLLECTION:
assertNull(responseContext.getResponseData().getBatchCreateResponseEnvelope().getCreateResponses());
break;
case BATCH_ENTITIES:
assertNull(responseContext.getResponseData().getBatchResponseEnvelope().getBatchResponseMap());
break;
case STATUS_ONLY:
break;
}
assertEquals(responseContext.getResponseData().getHeaders(), headersFromFilter);
assertTrue(responseContext.getResponseData().isErrorResponse());
// Modify data.
responseContext.getResponseData().getHeaders().put(customHeader, customHeaderValue);
setStatus(responseContext, HttpStatus.S_402_PAYMENT_REQUIRED);
// filter.
if (entityFromFilter2 instanceof RecordTemplate) {
responseContext.getResponseData().getRecordResponseEnvelope().setRecord((RecordTemplate) entityFromFilter2, HttpStatus.S_402_PAYMENT_REQUIRED);
} else if (entityFromFilter2 instanceof List) {
responseContext.getResponseData().getCollectionResponseEnvelope().setCollectionResponse((List<? extends RecordTemplate>) entityFromFilter2, new CollectionMetadata(), null, HttpStatus.S_402_PAYMENT_REQUIRED);
} else {
Map<Object, BatchResponseEnvelope.BatchResponseEntry> responseMap = new HashMap<>();
for (Map.Entry<?, RecordTemplate> entry : ((Map<?, RecordTemplate>) entityFromFilter2).entrySet()) {
responseMap.put(entry.getKey(), new BatchResponseEnvelope.BatchResponseEntry(HttpStatus.S_200_OK, entry.getValue()));
}
responseContext.getResponseData().getBatchResponseEnvelope().setBatchResponseMap(responseMap, HttpStatus.S_402_PAYMENT_REQUIRED);
}
return CompletableFuture.completedFuture(null);
}
}).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.
verify(_responseHandler).buildExceptionResponseData(eq(_routingResult), wrappedExCapture.capture(), anyMap(), anyList());
verify(_responseHandler).buildPartialResponse(_routingResult, responseAppData);
verify(_callback).onSuccess(partialResponse);
verify(_restRequest).getHeaders();
verifyNoMoreInteractions(_restRequest, _responseHandler, _callback);
assertNotNull(responseAppData);
assertEquals(HttpStatus.S_402_PAYMENT_REQUIRED, responseAppData.getResponseEnvelope().getStatus());
// Only the error header should have been cleared.
assertFalse(responseAppData.getHeaders().containsKey(errorResponseHeaderName));
assertEquals(responseAppData.getHeaders().get(customHeader), customHeaderValue);
if (entityFromFilter2 instanceof RecordTemplate) {
assertTrue(responseAppData.getResponseType() == ResponseType.SINGLE_ENTITY);
assertEquals(responseAppData.getRecordResponseEnvelope().getRecord(), entityFromFilter2);
} else if (entityFromFilter2 instanceof List) {
if (responseAppData.getResponseType() == ResponseType.GET_COLLECTION) {
assertEquals(responseAppData.getCollectionResponseEnvelope().getCollectionResponse(), entityFromFilter2);
} else {
fail();
}
} else {
assertTrue(responseAppData.getResponseType() == ResponseType.BATCH_ENTITIES);
Map<Object, RecordTemplate> values = new HashMap<>();
for (Map.Entry<?, BatchResponseEnvelope.BatchResponseEntry> entry : responseAppData.getBatchResponseEnvelope().getBatchResponseMap().entrySet()) {
values.put(entry.getKey(), entry.getValue().getRecord());
}
assertEquals(values, entityFromFilter2);
}
assertFalse(responseAppData.getResponseEnvelope().isErrorResponse());
RestLiServiceException restliEx = wrappedExCapture.getAllValues().get(0);
assertNotNull(restliEx);
assertEquals(exFromApp.getStatus(), restliEx.getStatus());
assertEquals(exFromApp.getMessage(), restliEx.getMessage());
}
Aggregations