Search in sources :

Example 71 with RestLiServiceException

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

the class TestRestLiResponseHandler method testSetResponseCookies.

@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "basicData")
public void testSetResponseCookies(AcceptTypeData acceptTypeData, ProtocolVersion protocolVersion, String errorResponseHeaderName) throws Exception {
    String testHeaderName = "XXX";
    String testHeaderValue = "head";
    ResourceModel resourceModel = buildResourceModel(StatusCollectionResource.class);
    ResourceMethodDescriptor methodDescriptor = resourceModel.findNamedMethod("search");
    ResourceContextImpl context = new ResourceContextImpl();
    context.setResponseHeader(testHeaderName, testHeaderValue);
    context.addResponseCookie(new HttpCookie("cook1", "value1"));
    context.addResponseCookie(new HttpCookie("cook2", "value2"));
    RestUtils.validateRequestHeadersAndUpdateResourceContext(acceptTypeData.acceptHeaders, context);
    RoutingResult routingResult = new RoutingResult(context, methodDescriptor);
    // this is a valid response
    RestResponse response = _responseHandler.buildResponse(buildRequest(acceptTypeData.acceptHeaders, protocolVersion), routingResult, buildStatusList(1));
    List<HttpCookie> cookies = Arrays.asList(new HttpCookie("cook1", "value1"), new HttpCookie("cook2", "value2"));
    Assert.assertEquals(CookieUtil.decodeSetCookies(response.getCookies()), cookies);
    response = _responseHandler.buildResponse(buildRequest(acceptTypeData.acceptHeaders, protocolVersion), routingResult, // this is an invalid response
    new RestLiServiceException(HttpStatus.S_404_NOT_FOUND));
    //but the cookie should still be valid
    Assert.assertEquals(CookieUtil.decodeSetCookies(response.getCookies()), cookies);
}
Also used : RoutingResult(com.linkedin.restli.internal.server.RoutingResult) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) RestResponse(com.linkedin.r2.message.rest.RestResponse) PartialRestResponse(com.linkedin.restli.internal.server.response.PartialRestResponse) ResourceMethodDescriptor(com.linkedin.restli.internal.server.model.ResourceMethodDescriptor) ResourceModel(com.linkedin.restli.internal.server.model.ResourceModel) RestLiTestHelper.buildResourceModel(com.linkedin.restli.server.test.RestLiTestHelper.buildResourceModel) ByteString(com.linkedin.data.ByteString) HttpCookie(java.net.HttpCookie) ResourceContextImpl(com.linkedin.restli.internal.server.ResourceContextImpl) Test(org.testng.annotations.Test)

Example 72 with RestLiServiceException

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

the class TestRestLiResponseHandler method testInvalidAcceptHeaders.

@Test
private void testInvalidAcceptHeaders() throws Exception {
    Map<String, String> badAcceptHeaders = Collections.singletonMap("Accept", "foo/bar");
    // check response with body (expect 406 error)
    try {
        invokeResponseHandler("/test", buildStatusRecord(), ResourceMethod.GET, badAcceptHeaders, AllProtocolVersions.LATEST_PROTOCOL_VERSION);
        Assert.fail();
    } catch (RestLiServiceException e) {
        Assert.assertEquals(e.getStatus().getCode(), 406);
    }
    // check response without body (expect 406 error)
    try {
        invokeResponseHandler("/test", new CreateResponse(HttpStatus.S_201_CREATED), ResourceMethod.CREATE, badAcceptHeaders, AllProtocolVersions.LATEST_PROTOCOL_VERSION);
        Assert.fail();
    } catch (RestLiServiceException e) {
        Assert.assertEquals(e.getStatus().getCode(), 406);
    }
}
Also used : RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) CreateResponse(com.linkedin.restli.server.CreateResponse) ByteString(com.linkedin.data.ByteString) Test(org.testng.annotations.Test)

Example 73 with RestLiServiceException

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

the class TestRestLiCallback method testOnErrorWithFiltersNotHandlingAppEx.

@SuppressWarnings("unchecked")
@Test
public void testOnErrorWithFiltersNotHandlingAppEx() 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 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();
    when(_requestExecutionReportBuilder.build()).thenReturn(executionReport);
    when(_responseHandler.buildExceptionResponseData(eq(_restRequest), 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.
            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 completedFutureWithError(responseContext.getResponseData().getServiceException());
        }
    }).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.
            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().getHeaders().putAll(headersFromFilter);
            return completedFutureWithError(responseContext.getResponseData().getServiceException());
        }
    }).when(_filter).onError(any(Throwable.class), eq(_filterRequestContext), any(FilterResponseContext.class));
    RestException restException = new RestException(new RestResponseBuilder().build());
    when(_responseHandler.buildRestException(any(RestLiServiceException.class), eq(partialResponse))).thenReturn(restException);
    // 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());
    assertNull(responseData.getRecordResponseEnvelope().getRecord());
    assertTrue(responseData.isErrorResponse());
    assertEquals(responseData.getServiceException().getErrorDetails(), appException.getErrorDetails());
    assertEquals(responseData.getServiceException().getOverridingFormat(), appException.getOverridingFormat());
    assertEquals(responseData.getServiceException().getServiceErrorCode(), appException.getServiceErrorCode());
    assertEquals(responseData.getServiceException().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(_restRequest), eq(_routingResult), exCapture.capture(), anyMap(), anyList());
    verify(_responseHandler).buildPartialResponse(_routingResult, responseData);
    verify(_responseHandler).buildRestException(exCapture.capture(), eq(partialResponse));
    verify(_callback).onError(restException, executionReport, _requestAttachmentReader, responseAttachments);
    verify(_restRequest, times(1)).getHeaders();
    verifyZeroInteractions(_routingResult);
    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());
    final RestLiServiceException restliEx2 = exCapture.getAllValues().get(1);
    assertNotNull(restliEx2);
    assertEquals(HttpStatus.S_403_FORBIDDEN, restliEx2.getStatus());
}
Also used : EmptyRecord(com.linkedin.restli.common.EmptyRecord) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) RestLiResponseAttachments(com.linkedin.restli.server.RestLiResponseAttachments) RequestExecutionReportBuilder(com.linkedin.restli.server.RequestExecutionReportBuilder) RestException(com.linkedin.r2.message.rest.RestException) 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) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Example 74 with RestLiServiceException

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

the class TestRestLiCallback method testOnErrorWithFiltersExceptionFromSecondFilter.

@SuppressWarnings("unchecked")
@Test
public void testOnErrorWithFiltersExceptionFromSecondFilter() 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();
    RestLiResponseDataImpl responseAppData = new RestLiResponseDataImpl(exFromApp, Collections.<String, String>emptyMap(), Collections.<HttpCookie>emptyList());
    responseAppData.setResponseEnvelope(new CreateResponseEnvelope(null, responseAppData));
    // Filter stuff.
    final Exception exFromSecondFilter = new RuntimeException("Runtime exception from second filter");
    RestLiServiceException exception = new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, exFromSecondFilter);
    RestLiResponseDataImpl responseFilterData = new RestLiResponseDataImpl(exception, Collections.<String, String>emptyMap(), Collections.<HttpCookie>emptyList());
    responseFilterData.setResponseEnvelope(new CreateResponseEnvelope(null, responseFilterData));
    PartialRestResponse partialResponse = new PartialRestResponse.Builder().build();
    RestException restException = new RestException(new RestResponseBuilder().build());
    // Setup.
    when(_requestExecutionReportBuilder.build()).thenReturn(executionReport);
    when(_responseHandler.buildExceptionResponseData(eq(_restRequest), eq(_routingResult), any(RestLiServiceException.class), anyMap(), anyList())).thenReturn(responseAppData).thenReturn(responseFilterData);
    when(_responseHandler.buildPartialResponse(_routingResult, responseAppData)).thenReturn(partialResponse);
    when(_restRequest.getHeaders()).thenReturn(null);
    when(_responseHandler.buildRestException(any(RestLiServiceException.class), eq(partialResponse))).thenReturn(restException);
    // Mock filter behavior.
    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];
            assertEquals(responseContext.getResponseData().getStatus(), HttpStatus.S_404_NOT_FOUND);
            assertNull(responseContext.getResponseData().getRecordResponseEnvelope().getRecord());
            assertTrue(responseContext.getResponseData().getHeaders().isEmpty());
            // Modify data.
            setStatus(responseContext, HttpStatus.S_402_PAYMENT_REQUIRED);
            return completedFutureWithError(t);
        }
    }).doThrow(exFromSecondFilter).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.
    ArgumentCaptor<RestLiServiceException> wrappedExCapture = ArgumentCaptor.forClass(RestLiServiceException.class);
    verify(_responseHandler).buildExceptionResponseData(eq(_restRequest), eq(_routingResult), wrappedExCapture.capture(), anyMap(), anyList());
    verify(_responseHandler).buildPartialResponse(_routingResult, responseAppData);
    verify(_responseHandler).buildRestException(wrappedExCapture.capture(), eq(partialResponse));
    verify(_callback).onError(restException, executionReport, _requestAttachmentReader, responseAttachments);
    verify(_restRequest).getHeaders();
    verifyZeroInteractions(_routingResult);
    verifyNoMoreInteractions(_restRequest, _responseHandler, _callback);
    assertNotNull(responseAppData);
    assertEquals(HttpStatus.S_500_INTERNAL_SERVER_ERROR, responseAppData.getStatus());
    assertNull(responseAppData.getRecordResponseEnvelope().getRecord());
    final RestLiServiceException restliEx1 = wrappedExCapture.getAllValues().get(0);
    assertEquals(exFromApp, restliEx1);
    final RestLiServiceException restliEx2 = wrappedExCapture.getAllValues().get(1);
    assertNotNull(restliEx2);
    assertEquals(HttpStatus.S_500_INTERNAL_SERVER_ERROR, restliEx2.getStatus());
    assertEquals(exFromSecondFilter.getMessage(), restliEx2.getMessage());
    assertEquals(exFromSecondFilter, restliEx2.getCause());
}
Also used : RequestExecutionReportBuilder(com.linkedin.restli.server.RequestExecutionReportBuilder) RestException(com.linkedin.r2.message.rest.RestException) 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) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) FilterResponseContext(com.linkedin.restli.server.filter.FilterResponseContext) InvocationOnMock(org.mockito.invocation.InvocationOnMock) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) RestLiResponseAttachments(com.linkedin.restli.server.RestLiResponseAttachments) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Example 75 with RestLiServiceException

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

the class TestRestLiCallback method testOnErrorOtherExceptionNoFilters.

@SuppressWarnings("unchecked")
@Test(dataProvider = "provideExceptions")
public void testOnErrorOtherExceptionNoFilters(Exception ex) throws Exception {
    ArgumentCaptor<RestLiServiceException> exCapture = ArgumentCaptor.forClass(RestLiServiceException.class);
    RequestExecutionReport executionReport = new RequestExecutionReportBuilder().build();
    RestLiResponseAttachments responseAttachments = new RestLiResponseAttachments.Builder().build();
    PartialRestResponse partialResponse = new PartialRestResponse.Builder().build();
    RestLiServiceException wrappedEx = new RestLiServiceException(HttpStatus.S_400_BAD_REQUEST, ex);
    RestLiResponseDataImpl responseData = new RestLiResponseDataImpl(wrappedEx, Collections.<String, String>emptyMap(), Collections.<HttpCookie>emptyList());
    responseData.setResponseEnvelope(new GetResponseEnvelope(new EmptyRecord(), responseData));
    RestException restException = new RestException(new RestResponseBuilder().build());
    Map<String, String> inputHeaders = Maps.newHashMap();
    inputHeaders.put(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, "2.0.0");
    // Set up.
    when(_requestExecutionReportBuilder.build()).thenReturn(executionReport);
    when(_restRequest.getHeaders()).thenReturn(inputHeaders);
    when(_responseHandler.buildExceptionResponseData(eq(_restRequest), eq(_routingResult), exCapture.capture(), anyMap(), anyList())).thenReturn(responseData);
    when(_responseHandler.buildPartialResponse(_routingResult, responseData)).thenReturn(partialResponse);
    when(_responseHandler.buildRestException(wrappedEx, partialResponse)).thenReturn(restException);
    // Invoke.
    _noFilterRestLiCallback.onError(ex, executionReport, _requestAttachmentReader, responseAttachments);
    // Verify.
    verify(_responseHandler).buildExceptionResponseData(eq(_restRequest), eq(_routingResult), exCapture.capture(), anyMap(), anyList());
    verify(_responseHandler).buildPartialResponse(_routingResult, responseData);
    verify(_responseHandler).buildRestException(wrappedEx, partialResponse);
    verify(_callback).onError(restException, executionReport, _requestAttachmentReader, responseAttachments);
    verify(_restRequest, times(1)).getHeaders();
    verifyZeroInteractions(_routingResult);
    verifyNoMoreInteractions(_restRequest, _responseHandler, _callback);
    RestLiServiceException restliEx = exCapture.getValue();
    assertNotNull(restliEx);
    if (ex instanceof RoutingException) {
        assertEquals(HttpStatus.fromCode(((RoutingException) ex).getStatus()), restliEx.getStatus());
    } else if (ex instanceof RestLiServiceException) {
        assertEquals(((RestLiServiceException) ex).getStatus(), restliEx.getStatus());
    } else {
        assertEquals(HttpStatus.S_500_INTERNAL_SERVER_ERROR, restliEx.getStatus());
    }
    assertEquals(ex.getMessage(), restliEx.getMessage());
    if (ex instanceof RestLiServiceException) {
        assertEquals(ex, restliEx);
    } else {
        assertEquals(ex, restliEx.getCause());
    }
}
Also used : EmptyRecord(com.linkedin.restli.common.EmptyRecord) RoutingException(com.linkedin.restli.server.RoutingException) RequestExecutionReportBuilder(com.linkedin.restli.server.RequestExecutionReportBuilder) RestException(com.linkedin.r2.message.rest.RestException) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) RequestExecutionReport(com.linkedin.restli.server.RequestExecutionReport) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) RestLiResponseAttachments(com.linkedin.restli.server.RestLiResponseAttachments) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Aggregations

RestLiServiceException (com.linkedin.restli.server.RestLiServiceException)93 Test (org.testng.annotations.Test)36 HashMap (java.util.HashMap)31 UpdateResponse (com.linkedin.restli.server.UpdateResponse)18 RestLiResponseAttachments (com.linkedin.restli.server.RestLiResponseAttachments)17 RoutingException (com.linkedin.restli.server.RoutingException)17 RestException (com.linkedin.r2.message.rest.RestException)16 ServerResourceContext (com.linkedin.restli.internal.server.ServerResourceContext)16 RequestExecutionReport (com.linkedin.restli.server.RequestExecutionReport)16 BeforeTest (org.testng.annotations.BeforeTest)16 DataMap (com.linkedin.data.DataMap)14 RequestExecutionReportBuilder (com.linkedin.restli.server.RequestExecutionReportBuilder)13 Map (java.util.Map)13 RestResponseBuilder (com.linkedin.r2.message.rest.RestResponseBuilder)12 EmptyRecord (com.linkedin.restli.common.EmptyRecord)12 RoutingResult (com.linkedin.restli.internal.server.RoutingResult)12 BatchUpdateResult (com.linkedin.restli.server.BatchUpdateResult)11 FilterRequestContext (com.linkedin.restli.server.filter.FilterRequestContext)11 FilterResponseContext (com.linkedin.restli.server.filter.FilterResponseContext)11 RecordTemplate (com.linkedin.data.template.RecordTemplate)10