Search in sources :

Example 61 with ErrorResponse

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

the class BatchGetRequestUtil method unbatchKVResponse.

/**
 * Extract the get response for this resource out of an auto-batched batch response.
 * This is pure rest.li logic, and it complements the auto-batching logic in BatchGetRequestBuilder.
 * @throws com.linkedin.r2.RemoteInvocationException if the server returned an error response for this resource,
 * or if it returned neither a result nor an error.
 */
public static <K, V extends RecordTemplate> Response<V> unbatchKVResponse(Request<BatchKVResponse<K, V>> request, Response<BatchKVResponse<K, V>> batchResponse, K id) throws RemoteInvocationException {
    final BatchKVResponse<K, V> batchEntity = batchResponse.getEntity();
    final ErrorResponse errorResponse = batchEntity.getErrors().get(id);
    if (errorResponse != null) {
        throw new RestLiResponseException(errorResponse);
    }
    final V entityResult = batchEntity.getResults().get(id);
    if (entityResult == null) {
        throw new RestLiDecodingException("No result or error for base URI " + request.getBaseUriTemplate() + ", id " + id + ". Verify that the batchGet endpoint returns response keys that match batchGet request IDs.", null);
    }
    return new ResponseImpl<>(batchResponse, entityResult);
}
Also used : ResponseImpl(com.linkedin.restli.internal.client.ResponseImpl) ErrorResponse(com.linkedin.restli.common.ErrorResponse)

Example 62 with ErrorResponse

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

the class TestExceptionsResource method testBatchCreateIdErrors.

@SuppressWarnings("deprecation")
@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(), Long.valueOf(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());
    Assert.assertFalse(error.hasCode());
    Assert.assertFalse(error.hasDocUrl());
    Assert.assertFalse(error.hasRequestId());
    Assert.assertEquals(error.getErrorDetailType(), EmptyRecord.class.getCanonicalName());
}
Also used : Greeting(com.linkedin.restli.examples.greetings.api.Greeting) EmptyRecord(com.linkedin.restli.common.EmptyRecord) CreateIdStatus(com.linkedin.restli.common.CreateIdStatus) ErrorResponse(com.linkedin.restli.common.ErrorResponse) BatchCreateIdResponse(com.linkedin.restli.common.BatchCreateIdResponse) ExceptionsRequestBuilders(com.linkedin.restli.examples.greetings.client.ExceptionsRequestBuilders) Test(org.testng.annotations.Test)

Example 63 with ErrorResponse

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

the class TestExceptionsResource method testBatchCreateErrors.

@SuppressWarnings("deprecation")
@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(), Long.valueOf(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());
    Assert.assertFalse(error.hasCode());
    Assert.assertFalse(error.hasDocUrl());
    Assert.assertFalse(error.hasRequestId());
    Assert.assertEquals(error.getErrorDetailType(), EmptyRecord.class.getCanonicalName());
}
Also used : CreateStatus(com.linkedin.restli.common.CreateStatus) Greeting(com.linkedin.restli.examples.greetings.api.Greeting) EmptyRecord(com.linkedin.restli.common.EmptyRecord) 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 64 with ErrorResponse

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

the class TestAssociationsResource method testBatchFinder.

@Test(dataProvider = com.linkedin.restli.internal.common.TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "requestBuilderDataProvider")
public void testBatchFinder(RootBuilderWrapper<CompoundKey, Message> builders) throws RemoteInvocationException {
    MessageCriteria m1 = new MessageCriteria().setMessage("hello").setTone(Tone.FRIENDLY);
    MessageCriteria m2 = new MessageCriteria().setMessage("world").setTone(Tone.SINCERE);
    Request<BatchCollectionResponse<Message>> request = builders.batchFindBy("searchMessages").assocKey("src", "KEY1").setQueryParam("criteria", Arrays.asList(m1, m2)).build();
    ResponseFuture<BatchCollectionResponse<Message>> future = getClient().sendRequest(request);
    BatchCollectionResponse<Message> response = future.getResponse().getEntity();
    List<BatchFinderCriteriaResult<Message>> batchResult = response.getResults();
    // on success
    List<Message> messages = batchResult.get(0).getElements();
    Assert.assertTrue(messages.get(0).hasTone());
    Assert.assertTrue(messages.get(0).getTone().equals(Tone.FRIENDLY));
    // on error
    Assert.assertTrue(batchResult.get(1).isError());
    ErrorResponse error = batchResult.get(1).getError();
    Assert.assertEquals(error.getMessage(), "Failed to find message!");
}
Also used : BatchFinderCriteriaResult(com.linkedin.restli.common.BatchFinderCriteriaResult) BatchCollectionResponse(com.linkedin.restli.common.BatchCollectionResponse) Message(com.linkedin.restli.examples.greetings.api.Message) MessageCriteria(com.linkedin.restli.examples.greetings.api.MessageCriteria) ErrorResponse(com.linkedin.restli.common.ErrorResponse) Test(org.testng.annotations.Test)

Example 65 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();
    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, restResponse.getHeaders());
                // 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) RestLiResponseException(com.linkedin.restli.internal.server.response.RestLiResponseException) 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)

Aggregations

ErrorResponse (com.linkedin.restli.common.ErrorResponse)67 Test (org.testng.annotations.Test)35 DataMap (com.linkedin.data.DataMap)19 HashMap (java.util.HashMap)15 Greeting (com.linkedin.restli.examples.greetings.api.Greeting)14 RestResponse (com.linkedin.r2.message.rest.RestResponse)9 RestRequest (com.linkedin.r2.message.rest.RestRequest)8 EntityResponse (com.linkedin.restli.common.EntityResponse)8 ResponseImpl (com.linkedin.restli.internal.client.ResponseImpl)8 RestLiServiceException (com.linkedin.restli.server.RestLiServiceException)8 RestException (com.linkedin.r2.message.rest.RestException)7 TestRecord (com.linkedin.restli.client.test.TestRecord)7 Callback (com.linkedin.common.callback.Callback)6 BatchKVResponse (com.linkedin.restli.client.response.BatchKVResponse)6 BatchResponse (com.linkedin.restli.common.BatchResponse)6 EmptyRecord (com.linkedin.restli.common.EmptyRecord)6 IOException (java.io.IOException)6 RequestContext (com.linkedin.r2.message.RequestContext)5 BatchCollectionResponse (com.linkedin.restli.common.BatchCollectionResponse)5 BatchFinderCriteriaResult (com.linkedin.restli.common.BatchFinderCriteriaResult)5