Search in sources :

Example 36 with ErrorResponse

use of com.linkedin.restli.common.ErrorResponse in project rest.li by linkedin.

the class RestClientTest method mockClient.

private RestClient mockClient(String errKey, String errValue, String errMsg, int httpCode, int appCode, ProtocolVersion protocolVersion, String errorResponseHeaderName) {
    ErrorResponse er = new ErrorResponse();
    DataMap errMap = new DataMap();
    errMap.put(errKey, errValue);
    er.setErrorDetails(new ErrorDetails(errMap));
    er.setStatus(httpCode);
    er.setMessage(errMsg);
    er.setServiceErrorCode(appCode);
    byte[] mapBytes;
    try {
        mapBytes = new JacksonDataCodec().mapToBytes(er.data());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    Map<String, String> headers = new HashMap<String, String>();
    headers.put(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, protocolVersion.toString());
    headers.put(errorResponseHeaderName, RestConstants.HEADER_VALUE_ERROR);
    return new RestClient(new MyMockClient(httpCode, headers, mapBytes), "http://localhost");
}
Also used : JacksonDataCodec(com.linkedin.data.codec.JacksonDataCodec) HashMap(java.util.HashMap) ErrorDetails(com.linkedin.restli.common.ErrorDetails) IOException(java.io.IOException) ErrorResponse(com.linkedin.restli.common.ErrorResponse) DataMap(com.linkedin.data.DataMap)

Example 37 with ErrorResponse

use of com.linkedin.restli.common.ErrorResponse in project rest.li by linkedin.

the class TestExceptionsResource method testBatchCreateErrors.

@Test(dataProvider = com.linkedin.restli.internal.common.TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "requestOptionsDataProvider")
public void testBatchCreateErrors(RestliRequestOptions requestOptions) throws Exception {
    ExceptionsBuilders builders = new ExceptionsBuilders(requestOptions);
    Request<CollectionResponse<CreateStatus>> batchCreateRequest = builders.batchCreate().input(new Greeting().setId(10L).setMessage("Greetings.").setTone(Tone.SINCERE)).input(new Greeting().setId(11L).setMessage("@#$%@!$%").setTone(Tone.INSULTING)).build();
    Response<CollectionResponse<CreateStatus>> response = getClient().sendRequest(batchCreateRequest).getResponse();
    List<CreateStatus> createStatuses = response.getEntity().getElements();
    Assert.assertEquals(createStatuses.size(), 2);
    @SuppressWarnings("unchecked") CreateIdStatus<Long> status0 = (CreateIdStatus<Long>) createStatuses.get(0);
    Assert.assertEquals(status0.getStatus().intValue(), HttpStatus.S_201_CREATED.getCode());
    Assert.assertEquals(status0.getKey(), new Long(10));
    @SuppressWarnings("deprecation") String id = status0.getId();
    Assert.assertEquals(BatchResponse.keyToString(status0.getKey(), ProtocolVersionUtil.extractProtocolVersion(response.getHeaders())), id);
    Assert.assertFalse(status0.hasError());
    CreateStatus status1 = createStatuses.get(1);
    Assert.assertEquals(status1.getStatus().intValue(), HttpStatus.S_406_NOT_ACCEPTABLE.getCode());
    Assert.assertTrue(status1.hasError());
    ErrorResponse error = status1.getError();
    Assert.assertEquals(error.getStatus().intValue(), HttpStatus.S_406_NOT_ACCEPTABLE.getCode());
    Assert.assertEquals(error.getMessage(), "I will not tolerate your insolence!");
    Assert.assertEquals(error.getServiceErrorCode().intValue(), 999);
    Assert.assertEquals(error.getExceptionClass(), "com.linkedin.restli.server.RestLiServiceException");
    Assert.assertEquals(error.getErrorDetails().data().getString("reason"), "insultingGreeting");
    Assert.assertTrue(error.getStackTrace().startsWith("com.linkedin.restli.server.RestLiServiceException [HTTP Status:406, serviceErrorCode:999]: I will not tolerate your insolence!"), "stacktrace mismatch:" + error.getStackTrace());
}
Also used : CreateStatus(com.linkedin.restli.common.CreateStatus) Greeting(com.linkedin.restli.examples.greetings.api.Greeting) ExceptionsBuilders(com.linkedin.restli.examples.greetings.client.ExceptionsBuilders) CollectionResponse(com.linkedin.restli.common.CollectionResponse) CreateIdStatus(com.linkedin.restli.common.CreateIdStatus) ErrorResponse(com.linkedin.restli.common.ErrorResponse) Test(org.testng.annotations.Test)

Example 38 with ErrorResponse

use of com.linkedin.restli.common.ErrorResponse in project rest.li by linkedin.

the class TestExceptionsResource method testBatchCreateIdErrors.

@Test(dataProvider = com.linkedin.restli.internal.common.TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "requestOptionsDataProvider")
public void testBatchCreateIdErrors(RestliRequestOptions requestOptions) throws Exception {
    ExceptionsRequestBuilders builders = new ExceptionsRequestBuilders(requestOptions);
    BatchCreateIdRequest<Long, Greeting> batchCreateRequest = builders.batchCreate().input(new Greeting().setId(10L).setMessage("Greetings.").setTone(Tone.SINCERE)).input(new Greeting().setId(11L).setMessage("@#$%@!$%").setTone(Tone.INSULTING)).build();
    Response<BatchCreateIdResponse<Long>> response = getClient().sendRequest(batchCreateRequest).getResponse();
    List<CreateIdStatus<Long>> createStatuses = response.getEntity().getElements();
    Assert.assertEquals(createStatuses.size(), 2);
    @SuppressWarnings("unchecked") CreateIdStatus<Long> status0 = createStatuses.get(0);
    Assert.assertEquals(status0.getStatus().intValue(), HttpStatus.S_201_CREATED.getCode());
    Assert.assertEquals(status0.getKey(), new Long(10));
    @SuppressWarnings("deprecation") String id = status0.getId();
    Assert.assertEquals(BatchResponse.keyToString(status0.getKey(), ProtocolVersionUtil.extractProtocolVersion(response.getHeaders())), id);
    Assert.assertFalse(status0.hasError());
    CreateIdStatus<Long> status1 = createStatuses.get(1);
    Assert.assertEquals(status1.getStatus().intValue(), HttpStatus.S_406_NOT_ACCEPTABLE.getCode());
    Assert.assertTrue(status1.hasError());
    ErrorResponse error = status1.getError();
    Assert.assertEquals(error.getStatus().intValue(), HttpStatus.S_406_NOT_ACCEPTABLE.getCode());
    Assert.assertEquals(error.getMessage(), "I will not tolerate your insolence!");
    Assert.assertEquals(error.getServiceErrorCode().intValue(), 999);
    Assert.assertEquals(error.getExceptionClass(), "com.linkedin.restli.server.RestLiServiceException");
    Assert.assertEquals(error.getErrorDetails().data().getString("reason"), "insultingGreeting");
    Assert.assertTrue(error.getStackTrace().startsWith("com.linkedin.restli.server.RestLiServiceException [HTTP Status:406, serviceErrorCode:999]: I will not tolerate your insolence!"), "stacktrace mismatch:" + error.getStackTrace());
}
Also used : BatchCreateIdResponse(com.linkedin.restli.common.BatchCreateIdResponse) Greeting(com.linkedin.restli.examples.greetings.api.Greeting) ExceptionsRequestBuilders(com.linkedin.restli.examples.greetings.client.ExceptionsRequestBuilders) CreateIdStatus(com.linkedin.restli.common.CreateIdStatus) ErrorResponse(com.linkedin.restli.common.ErrorResponse) Test(org.testng.annotations.Test)

Example 39 with ErrorResponse

use of com.linkedin.restli.common.ErrorResponse in project rest.li by linkedin.

the class TestRestLiServer method testMessageAndDetailsErrorFormat.

@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "protocolVersions")
public void testMessageAndDetailsErrorFormat(final ProtocolVersion protocolVersion, final String errorResponseHeaderName, final RestOrStream restOrStream) throws Exception {
    final StatusCollectionResource statusResource = getMockResource(StatusCollectionResource.class);
    final DataMap details = new DataMap();
    details.put("errorKey", "errorDetail");
    EasyMock.expect(statusResource.get(eq(1L))).andThrow(new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR, "Mock Exception").setErrorDetails(details)).once();
    EasyMock.replay(statusResource);
    Callback<RestResponse> restResponseCallback = new Callback<RestResponse>() {

        @Override
        public void onSuccess(RestResponse restResponse) {
            fail();
        }

        @Override
        public void onError(Throwable e) {
            assertTrue(e instanceof RestException);
            RestException restException = (RestException) e;
            RestResponse restResponse = restException.getResponse();
            try {
                assertEquals(restResponse.getStatus(), 500);
                assertTrue(restResponse.getEntity().length() > 0);
                assertEquals(restResponse.getHeader(errorResponseHeaderName), RestConstants.HEADER_VALUE_ERROR);
                ErrorResponse responseBody = DataMapUtils.read(restResponse.getEntity().asInputStream(), ErrorResponse.class);
                // in this test, we're using the _serverWithCustomErrorResponseConfig (see below), which has been configure to use the
                // MESSAGE_AND_DETAILS ErrorResponseFormat, so stack trace and other error response parts should be absent
                assertEquals(responseBody.getMessage(), "Mock Exception");
                assertEquals(responseBody.getErrorDetails().data().getString("errorKey"), "errorDetail");
                assertFalse(responseBody.hasExceptionClass());
                assertFalse(responseBody.hasStackTrace());
                assertFalse(responseBody.hasStatus());
                EasyMock.verify(statusResource);
                EasyMock.reset(statusResource);
            } catch (Exception e2) {
                fail(e2.toString());
            }
        }
    };
    if (restOrStream == RestOrStream.REST) {
        RestRequest request = new RestRequestBuilder(new URI("/statuses/1")).setHeader(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, protocolVersion.toString()).build();
        _serverWithCustomErrorResponseConfig.handleRequest(request, new RequestContext(), restResponseCallback);
    } else {
        StreamRequest streamRequest = new StreamRequestBuilder(new URI("/statuses/1")).setHeader(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, protocolVersion.toString()).build(EntityStreams.emptyStream());
        Callback<StreamResponse> callback = new Callback<StreamResponse>() {

            @Override
            public void onSuccess(StreamResponse streamResponse) {
                fail();
            }

            @Override
            public void onError(Throwable e) {
                Messages.toRestException((StreamException) e, new Callback<RestException>() {

                    @Override
                    public void onError(Throwable e) {
                        Assert.fail();
                    }

                    @Override
                    public void onSuccess(RestException result) {
                        restResponseCallback.onError(result);
                    }
                });
            }
        };
        _serverWithCustomErrorResponseConfig.handleRequest(streamRequest, new RequestContext(), callback);
    }
}
Also used : RestResponse(com.linkedin.r2.message.rest.RestResponse) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) RestException(com.linkedin.r2.message.rest.RestException) URI(java.net.URI) StreamRequestBuilder(com.linkedin.r2.message.stream.StreamRequestBuilder) URISyntaxException(java.net.URISyntaxException) StreamException(com.linkedin.r2.message.stream.StreamException) ParseException(javax.mail.internet.ParseException) RestException(com.linkedin.r2.message.rest.RestException) IOException(java.io.IOException) DataMap(com.linkedin.data.DataMap) ErrorResponse(com.linkedin.restli.common.ErrorResponse) StreamRequest(com.linkedin.r2.message.stream.StreamRequest) SinglePartMIMEFullReaderCallback(com.linkedin.multipart.utils.MIMETestUtils.SinglePartMIMEFullReaderCallback) Callback(com.linkedin.common.callback.Callback) MultiPartMIMEFullReaderCallback(com.linkedin.multipart.utils.MIMETestUtils.MultiPartMIMEFullReaderCallback) RestRequest(com.linkedin.r2.message.rest.RestRequest) AsyncStatusCollectionResource(com.linkedin.restli.server.twitter.AsyncStatusCollectionResource) StatusCollectionResource(com.linkedin.restli.server.twitter.StatusCollectionResource) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) RequestContext(com.linkedin.r2.message.RequestContext) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest)

Example 40 with ErrorResponse

use of com.linkedin.restli.common.ErrorResponse in project rest.li by linkedin.

the class TestBatchUpdateResponseBuilder method testBuilder.

@Test(dataProvider = "testData")
@SuppressWarnings("unchecked")
public void testBuilder(Object results, ProtocolVersion protocolVersion, String altKeyName, Map<String, AlternativeKey<?, ?>> alternativeKeyMap, Map<String, UpdateStatus> expectedResults, Map<String, ErrorResponse> expectedErrors) {
    ResourceContext mockContext = getMockResourceContext(protocolVersion, altKeyName);
    ResourceMethodDescriptor mockDescriptor = getMockResourceMethodDescriptor(alternativeKeyMap);
    RoutingResult routingResult = new RoutingResult(mockContext, mockDescriptor);
    Map<String, String> headers = ResponseBuilderUtil.getHeaders();
    BatchUpdateResponseBuilder batchUpdateResponseBuilder = new BatchUpdateResponseBuilder(new ErrorResponseBuilder());
    RestLiResponseData responseData = batchUpdateResponseBuilder.buildRestLiResponseData(null, routingResult, results, headers, Collections.<HttpCookie>emptyList());
    PartialRestResponse restResponse = batchUpdateResponseBuilder.buildResponse(routingResult, responseData);
    BatchResponse<UpdateStatus> batchResponse = (BatchResponse<UpdateStatus>) restResponse.getEntity();
    EasyMock.verify(mockContext, mockDescriptor);
    ResponseBuilderUtil.validateHeaders(restResponse, headers);
    Assert.assertEquals(batchResponse.getResults(), expectedResults);
    Assert.assertEquals(batchResponse.getErrors().size(), expectedErrors.size());
    for (Map.Entry<String, ErrorResponse> entry : batchResponse.getErrors().entrySet()) {
        String key = entry.getKey();
        ErrorResponse value = entry.getValue();
        Assert.assertEquals(value.getStatus(), expectedErrors.get(key).getStatus());
    }
}
Also used : ResourceContext(com.linkedin.restli.server.ResourceContext) ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext) UpdateStatus(com.linkedin.restli.common.UpdateStatus) BatchResponse(com.linkedin.restli.common.BatchResponse) ResourceMethodDescriptor(com.linkedin.restli.internal.server.model.ResourceMethodDescriptor) RestLiResponseData(com.linkedin.restli.server.RestLiResponseData) ErrorResponse(com.linkedin.restli.common.ErrorResponse) RoutingResult(com.linkedin.restli.internal.server.RoutingResult) HashMap(java.util.HashMap) DataMap(com.linkedin.data.DataMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Test(org.testng.annotations.Test)

Aggregations

ErrorResponse (com.linkedin.restli.common.ErrorResponse)41 Test (org.testng.annotations.Test)20 DataMap (com.linkedin.data.DataMap)12 HashMap (java.util.HashMap)12 RestResponse (com.linkedin.r2.message.rest.RestResponse)8 Greeting (com.linkedin.restli.examples.greetings.api.Greeting)8 RestException (com.linkedin.r2.message.rest.RestException)6 RestRequest (com.linkedin.r2.message.rest.RestRequest)6 IOException (java.io.IOException)6 CompoundKey (com.linkedin.restli.common.CompoundKey)5 Map (java.util.Map)5 Callback (com.linkedin.common.callback.Callback)4 MultiPartMIMEFullReaderCallback (com.linkedin.multipart.utils.MIMETestUtils.MultiPartMIMEFullReaderCallback)4 SinglePartMIMEFullReaderCallback (com.linkedin.multipart.utils.MIMETestUtils.SinglePartMIMEFullReaderCallback)4 RequestContext (com.linkedin.r2.message.RequestContext)4 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)4 StreamException (com.linkedin.r2.message.stream.StreamException)4 StreamRequest (com.linkedin.r2.message.stream.StreamRequest)4 StreamRequestBuilder (com.linkedin.r2.message.stream.StreamRequestBuilder)4 StreamResponse (com.linkedin.r2.message.stream.StreamResponse)4