Search in sources :

Example 1 with FilterResponseContext

use of com.linkedin.restli.server.filter.FilterResponseContext in project rest.li by linkedin.

the class RestLiCallback method onError.

@Override
public void onError(final Throwable e, final RequestExecutionReport executionReport, final RestLiAttachmentReader requestAttachmentReader, final RestLiResponseAttachments responseAttachments) {
    final FilterResponseContext responseContext = _filterResponseContextFactory.fromThrowable(e);
    // Now kick off the response filters with error
    _filterChain.onError(e, _filterRequestContext, responseContext, responseAttachments);
}
Also used : FilterResponseContext(com.linkedin.restli.server.filter.FilterResponseContext)

Example 2 with FilterResponseContext

use of com.linkedin.restli.server.filter.FilterResponseContext 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());
}
Also used : EmptyRecord(com.linkedin.restli.common.EmptyRecord) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) RecordTemplate(com.linkedin.data.template.RecordTemplate) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) RestLiResponseAttachments(com.linkedin.restli.server.RestLiResponseAttachments) RequestExecutionReportBuilder(com.linkedin.restli.server.RequestExecutionReportBuilder) RestResponse(com.linkedin.r2.message.rest.RestResponse) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) RequestExecutionReport(com.linkedin.restli.server.RequestExecutionReport) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) RoutingException(com.linkedin.restli.server.RoutingException) RestException(com.linkedin.r2.message.rest.RestException) FilterResponseContext(com.linkedin.restli.server.filter.FilterResponseContext) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Example 3 with FilterResponseContext

use of com.linkedin.restli.server.filter.FilterResponseContext in project rest.li by linkedin.

the class TestRestLiCallback method testOnErrorWithFiltersExceptionFromFirstFilterSecondFilterHandles.

@SuppressWarnings("unchecked")
@Test(dataProvider = "provideResponseEntities")
public void testOnErrorWithFiltersExceptionFromFirstFilterSecondFilterHandles(final ResourceMethod resourceMethod, final Object entityFromFilter2) throws Exception {
    // App stuff.
    RestLiServiceException exFromApp = new RestLiServiceException(HttpStatus.S_404_NOT_FOUND, "App failure");
    RequestExecutionReport executionReport = new RequestExecutionReportBuilder().build();
    RestLiResponseAttachments responseAttachments = new RestLiResponseAttachments.Builder().build();
    RestLiServiceException appException = new RestLiServiceException(HttpStatus.S_404_NOT_FOUND);
    RestLiResponseDataImpl responseAppData = new RestLiResponseDataImpl(appException, Collections.<String, String>emptyMap(), Collections.<HttpCookie>emptyList());
    RestLiResponseEnvelope responseAppEnvelope = EnvelopeBuilderUtil.buildBlankResponseEnvelope(resourceMethod, responseAppData);
    responseAppData.setResponseEnvelope(responseAppEnvelope);
    // Filter stuff.
    final Exception exFromFirstFilter = new RuntimeException("Runtime exception from first filter");
    RestLiServiceException filterException = new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR);
    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);
    RestLiResponseDataImpl responseFilterData = new RestLiResponseDataImpl(filterException, headersFromFilter, Collections.<HttpCookie>emptyList());
    RestLiResponseEnvelope responseFilterEnvelope = EnvelopeBuilderUtil.buildBlankResponseEnvelope(resourceMethod, responseFilterData);
    responseFilterData.setResponseEnvelope(responseFilterEnvelope);
    PartialRestResponse partialResponse = new PartialRestResponse.Builder().build();
    ArgumentCaptor<RestLiServiceException> wrappedExCapture = ArgumentCaptor.forClass(RestLiServiceException.class);
    RestResponse restResponse = new RestResponseBuilder().build();
    final String customHeader = "Custom-Header";
    final String customHeaderValue = "CustomValue";
    // Setup.
    when(_requestExecutionReportBuilder.build()).thenReturn(executionReport);
    when(_responseHandler.buildExceptionResponseData(eq(_restRequest), eq(_routingResult), wrappedExCapture.capture(), anyMap(), anyList())).thenReturn(responseAppData);
    when(_responseHandler.buildPartialResponse(_routingResult, responseAppData)).thenReturn(partialResponse);
    when(_responseHandler.buildResponse(_routingResult, partialResponse)).thenReturn(restResponse);
    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];
            ((RestLiResponseDataImpl) responseContext.getResponseData()).setException(exFromFirstFilter);
            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(ResponseType.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<Object, BatchResponseEnvelope.BatchResponseEntry>();
                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, executionReport, _requestAttachmentReader, responseAttachments);
    // Verify.
    verify(_responseHandler).buildExceptionResponseData(eq(_restRequest), eq(_routingResult), wrappedExCapture.capture(), anyMap(), anyList());
    verify(_responseHandler).buildPartialResponse(_routingResult, responseAppData);
    verify(_responseHandler).buildResponse(_routingResult, partialResponse);
    verify(_callback).onSuccess(restResponse, executionReport, responseAttachments);
    verify(_restRequest).getHeaders();
    verifyZeroInteractions(_routingResult);
    verifyNoMoreInteractions(_restRequest, _responseHandler, _callback);
    assertNotNull(responseAppData);
    assertEquals(HttpStatus.S_402_PAYMENT_REQUIRED, responseAppData.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<Object, RecordTemplate>();
        for (Map.Entry<?, BatchResponseEnvelope.BatchResponseEntry> entry : responseAppData.getBatchResponseEnvelope().getBatchResponseMap().entrySet()) {
            values.put(entry.getKey(), entry.getValue().getRecord());
        }
        assertEquals(values, entityFromFilter2);
    }
    assertFalse(responseAppData.isErrorResponse());
    RestLiServiceException restliEx = wrappedExCapture.getAllValues().get(0);
    assertNotNull(restliEx);
    assertEquals(exFromApp.getStatus(), restliEx.getStatus());
    assertEquals(exFromApp.getMessage(), restliEx.getMessage());
}
Also used : HashMap(java.util.HashMap) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) RecordTemplate(com.linkedin.data.template.RecordTemplate) List(java.util.List) ArrayList(java.util.ArrayList) Matchers.anyList(org.mockito.Matchers.anyList) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) RestLiResponseAttachments(com.linkedin.restli.server.RestLiResponseAttachments) RequestExecutionReportBuilder(com.linkedin.restli.server.RequestExecutionReportBuilder) CollectionMetadata(com.linkedin.restli.common.CollectionMetadata) RestResponse(com.linkedin.r2.message.rest.RestResponse) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) RequestExecutionReport(com.linkedin.restli.server.RequestExecutionReport) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) RoutingException(com.linkedin.restli.server.RoutingException) RestException(com.linkedin.r2.message.rest.RestException) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Answer(org.mockito.stubbing.Answer) FilterResponseContext(com.linkedin.restli.server.filter.FilterResponseContext) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Map(java.util.Map) Matchers.anyMap(org.mockito.Matchers.anyMap) HashMap(java.util.HashMap) DataMap(com.linkedin.data.DataMap) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Example 4 with FilterResponseContext

use of com.linkedin.restli.server.filter.FilterResponseContext in project rest.li by linkedin.

the class ErrorResponseValidationFilter method onError.

@Override
public CompletableFuture<Void> onError(Throwable throwable, final FilterRequestContext requestContext, final FilterResponseContext responseContext) {
    CompletableFuture<Void> future = new CompletableFuture<>();
    if (throwable instanceof RestLiServiceException) {
        RestLiServiceException restLiServiceException = (RestLiServiceException) throwable;
        // do the validation only if the 'code' field is set on RestLiServiceException.
        if (restLiServiceException.hasCode()) {
            List<ServiceError> methodServiceErrors = requestContext.getMethodServiceErrors();
            List<ServiceError> resourceServiceErrors = requestContext.getFilterResourceModel().getServiceErrors();
            // nor on the method level skip the validation.
            if (methodServiceErrors == null && resourceServiceErrors == null) {
                // error details should not be set on RestLiServiceException object.
                if (restLiServiceException.getErrorDetailsRecord() != null) {
                    return completeExceptionallyWithHttp500(future, restLiServiceException);
                }
                future.completeExceptionally(restLiServiceException);
                return future;
            }
            Set<ServiceError> serviceErrors = new HashSet<>();
            if (methodServiceErrors != null) {
                serviceErrors.addAll(methodServiceErrors);
            }
            if (resourceServiceErrors != null) {
                serviceErrors.addAll(resourceServiceErrors);
            }
            // An empty list of codes means that any service error code will result in a Http 500 error response.
            if (serviceErrors.isEmpty()) {
                return completeExceptionallyWithHttp500(future, restLiServiceException);
            }
            String errorCode = restLiServiceException.getCode();
            Optional<ServiceError> maybeServiceError = serviceErrors.stream().filter(serviceError -> serviceError.code().equals(errorCode)).findFirst();
            // convert given throwable to 500_INTERNAL_SERVER_ERROR exception.
            if (!maybeServiceError.isPresent()) {
                return completeExceptionallyWithHttp500(future, restLiServiceException);
            }
            ServiceError definedServiceError = maybeServiceError.get();
            // Check that the error detail type is valid.
            if (restLiServiceException.hasErrorDetails()) {
                Class<?> errorResponseErrorDetailType = restLiServiceException.getErrorDetailsRecord().getClass();
                Class<?> definedErrorDetailType = definedServiceError.errorDetailType();
                if (!errorResponseErrorDetailType.equals(definedErrorDetailType)) {
                    return completeExceptionallyWithHttp500(future, restLiServiceException);
                }
            }
            // convert given throwable to 500_INTERNAL_SERVER_ERROR exception.
            if (definedServiceError.httpStatus() != restLiServiceException.getStatus()) {
                return completeExceptionallyWithHttp500(future, restLiServiceException);
            }
        // TODO: validate error message. What if the defined message in service error has placeholders, which gets filled based on some business logic in the code.
        }
    }
    future.completeExceptionally(throwable);
    return future;
}
Also used : ServiceError(com.linkedin.restli.server.errors.ServiceError) HashSet(java.util.HashSet) List(java.util.List) Future(java.util.concurrent.Future) HttpStatus(com.linkedin.restli.common.HttpStatus) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) Optional(java.util.Optional) Set(java.util.Set) Filter(com.linkedin.restli.server.filter.Filter) FilterResponseContext(com.linkedin.restli.server.filter.FilterResponseContext) CompletableFuture(java.util.concurrent.CompletableFuture) ServiceError(com.linkedin.restli.server.errors.ServiceError) CompletableFuture(java.util.concurrent.CompletableFuture) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) HashSet(java.util.HashSet)

Example 5 with FilterResponseContext

use of com.linkedin.restli.server.filter.FilterResponseContext in project rest.li by linkedin.

the class TestRestLiCallback method testOnSuccessWithFiltersExceptionFromFirstFilterSecondFilterHandlesEx.

@SuppressWarnings("unchecked")
@Test
public void testOnSuccessWithFiltersExceptionFromFirstFilterSecondFilterHandlesEx() throws Exception {
    // App stuff.
    final RecordTemplate entityFromApp = Foo.createFoo("Key", "One");
    RestLiResponseData<CreateResponseEnvelope> appResponseData = ResponseDataBuilderUtil.buildCreateResponseData(HttpStatus.S_200_OK, entityFromApp);
    // Filter stuff.
    final Map<String, String> errorHeaders = buildErrorHeaders();
    final RecordTemplate entityFromFilter = Foo.createFoo("Key", "Two");
    RestLiResponse partialFilterErrorResponse = new RestLiResponse.Builder().build();
    final Exception exFromFilter = new RuntimeException("Exception From Filter");
    // Setup.
    when((RestLiResponseData<CreateResponseEnvelope>) _responseHandler.buildRestLiResponseData(_restRequest, _routingResult, entityFromApp)).thenReturn(appResponseData);
    when(_restRequest.getHeaders()).thenReturn(null);
    when(_responseHandler.buildPartialResponse(_routingResult, appResponseData)).thenReturn(partialFilterErrorResponse);
    // Mock filter behavior.
    doThrow(exFromFilter).when(_filter).onResponse(eq(_filterRequestContext), any(FilterResponseContext.class));
    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 details of the exception thrown by the first
            // filter.
            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);
            assertEquals(responseData.getResponseEnvelope().getException().getStatus(), HttpStatus.S_500_INTERNAL_SERVER_ERROR);
            // Modify data.
            setStatus(responseContext, HttpStatus.S_402_PAYMENT_REQUIRED);
            // The second filter handles the exception thrown by the first filter (i.e.) sets an entity
            // response in the response data.
            responseData.getResponseEnvelope().setRecord(entityFromFilter, HttpStatus.S_402_PAYMENT_REQUIRED);
            responseData.getHeaders().put("error-fixed", "second-filter");
            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.onSuccess(entityFromApp);
    // Verify.
    verify(_responseHandler).buildRestLiResponseData(_restRequest, _routingResult, entityFromApp);
    verify(_responseHandler).buildPartialResponse(_routingResult, appResponseData);
    verify(_callback).onSuccess(any(RestLiResponse.class));
    Map<String, String> expectedHeaders = Maps.newHashMap();
    expectedHeaders.put("X-RestLi-Protocol-Version", "1.0.0");
    expectedHeaders.put("error-fixed", "second-filter");
    verifyNoMoreInteractions(_responseHandler, _callback);
    assertFalse(appResponseData.getResponseEnvelope().isErrorResponse());
    assertEquals(appResponseData.getResponseEnvelope().getRecord(), entityFromFilter);
    assertNotNull(appResponseData);
    assertEquals(HttpStatus.S_402_PAYMENT_REQUIRED, appResponseData.getResponseEnvelope().getStatus());
    assertEquals(appResponseData.getHeaders(), expectedHeaders);
    assertNull(appResponseData.getResponseEnvelope().getException());
}
Also used : RestLiResponseData(com.linkedin.restli.server.RestLiResponseData) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) RoutingException(com.linkedin.restli.server.RoutingException) RestException(com.linkedin.r2.message.rest.RestException) FilterResponseContext(com.linkedin.restli.server.filter.FilterResponseContext) RecordTemplate(com.linkedin.data.template.RecordTemplate) InvocationOnMock(org.mockito.invocation.InvocationOnMock) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Aggregations

FilterResponseContext (com.linkedin.restli.server.filter.FilterResponseContext)19 RestLiServiceException (com.linkedin.restli.server.RestLiServiceException)13 BeforeTest (org.testng.annotations.BeforeTest)13 Test (org.testng.annotations.Test)13 FilterRequestContext (com.linkedin.restli.server.filter.FilterRequestContext)12 RoutingException (com.linkedin.restli.server.RoutingException)11 InvocationOnMock (org.mockito.invocation.InvocationOnMock)11 RestException (com.linkedin.r2.message.rest.RestException)10 RestLiResponseData (com.linkedin.restli.server.RestLiResponseData)10 RecordTemplate (com.linkedin.data.template.RecordTemplate)8 Answer (org.mockito.stubbing.Answer)6 RestResponseBuilder (com.linkedin.r2.message.rest.RestResponseBuilder)4 DataMap (com.linkedin.data.DataMap)3 RestLiResponseAttachments (com.linkedin.restli.server.RestLiResponseAttachments)3 List (java.util.List)3 RestResponse (com.linkedin.r2.message.rest.RestResponse)2 CollectionMetadata (com.linkedin.restli.common.CollectionMetadata)2 RequestExecutionReport (com.linkedin.restli.server.RequestExecutionReport)2 RequestExecutionReportBuilder (com.linkedin.restli.server.RequestExecutionReportBuilder)2 ArrayList (java.util.ArrayList)2