Search in sources :

Example 66 with RestResponse

use of com.linkedin.r2.message.rest.RestResponse in project rest.li by linkedin.

the class TestRestLiMethodInvocation method testExecutionReport.

@Test
public void testExecutionReport() throws RestLiSyntaxException, URISyntaxException {
    Map<String, ResourceModel> resourceModelMap = buildResourceModels(StatusCollectionResource.class, AsyncStatusCollectionResource.class, PromiseStatusCollectionResource.class, TaskStatusCollectionResource.class);
    ResourceModel statusResourceModel = resourceModelMap.get("/statuses");
    ResourceModel asyncStatusResourceModel = resourceModelMap.get("/asyncstatuses");
    ResourceModel promiseStatusResourceModel = resourceModelMap.get("/promisestatuses");
    ResourceModel taskStatusResourceModel = resourceModelMap.get("/taskstatuses");
    ResourceMethodDescriptor methodDescriptor;
    StatusCollectionResource statusResource;
    AsyncStatusCollectionResource asyncStatusResource;
    PromiseStatusCollectionResource promiseStatusResource;
    TaskStatusCollectionResource taskStatusResource;
    // #1: Sync Method Execution
    methodDescriptor = statusResourceModel.findMethod(ResourceMethod.GET);
    statusResource = getMockResource(StatusCollectionResource.class);
    EasyMock.expect(statusResource.get(eq(1L))).andReturn(null).once();
    checkInvocation(statusResource, methodDescriptor, "GET", version, "/statuses/1", null, buildPathKeys("statusID", 1L), new RequestExecutionCallback<RestResponse>() {

        //A 404 is considered an error by rest.li
        @Override
        public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
            Assert.assertNull(executionReport.getParseqTrace(), "There should be no parseq trace!");
        }

        @Override
        public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
            Assert.fail("Request failed unexpectedly.");
        }
    }, true, false);
    // #2: Callback based Async Method Execution
    Capture<RequestExecutionReport> requestExecutionReportCapture = new Capture<RequestExecutionReport>();
    RestLiCallback<?> callback = getCallback(requestExecutionReportCapture);
    methodDescriptor = asyncStatusResourceModel.findMethod(ResourceMethod.GET);
    asyncStatusResource = getMockResource(AsyncStatusCollectionResource.class);
    asyncStatusResource.get(eq(1L), EasyMock.<Callback<Status>>anyObject());
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {

        @Override
        public Object answer() throws Throwable {
            @SuppressWarnings("unchecked") Callback<Status> callback = (Callback<Status>) EasyMock.getCurrentArguments()[1];
            callback.onSuccess(null);
            return null;
        }
    });
    EasyMock.replay(asyncStatusResource);
    checkAsyncInvocation(asyncStatusResource, callback, methodDescriptor, "GET", version, "/asyncstatuses/1", null, buildPathKeys("statusID", 1L), true);
    Assert.assertNull(requestExecutionReportCapture.getValue().getParseqTrace());
    // #3: Promise based Async Method Execution
    methodDescriptor = promiseStatusResourceModel.findMethod(ResourceMethod.GET);
    promiseStatusResource = getMockResource(PromiseStatusCollectionResource.class);
    EasyMock.expect(promiseStatusResource.get(eq(1L))).andReturn(Promises.<Status>value(null)).once();
    checkInvocation(promiseStatusResource, methodDescriptor, "GET", version, "/promisestatuses/1", null, buildPathKeys("statusID", 1L), new RequestExecutionCallback<RestResponse>() {

        //A 404 is considered an error by rest.li
        @Override
        public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
            Assert.assertNotNull(executionReport.getParseqTrace(), "There should be a valid parseq trace!");
        }

        @Override
        public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
            Assert.fail("Request failed unexpectedly.");
        }
    }, true, false);
    // #4: Task based Async Method Execution
    methodDescriptor = taskStatusResourceModel.findMethod(ResourceMethod.GET);
    taskStatusResource = getMockResource(TaskStatusCollectionResource.class);
    EasyMock.expect(taskStatusResource.get(eq(1L))).andReturn(Task.callable("myTask", new Callable<Status>() {

        @Override
        public Status call() throws Exception {
            return new Status();
        }
    })).once();
    checkInvocation(taskStatusResource, methodDescriptor, "GET", version, "/taskstatuses/1", null, buildPathKeys("statusID", 1L), new RequestExecutionCallback<RestResponse>() {

        @Override
        public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
            Assert.fail("Request failed unexpectedly.");
        }

        @Override
        public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
            Assert.assertNotNull(executionReport.getParseqTrace());
        }
    }, true, false);
}
Also used : Status(com.linkedin.restli.server.twitter.TwitterTestDataModels.Status) HttpStatus(com.linkedin.restli.common.HttpStatus) TaskStatusCollectionResource(com.linkedin.restli.server.twitter.TaskStatusCollectionResource) PromiseStatusCollectionResource(com.linkedin.restli.server.twitter.PromiseStatusCollectionResource) RestResponse(com.linkedin.r2.message.rest.RestResponse) ResourceMethodDescriptor(com.linkedin.restli.internal.server.model.ResourceMethodDescriptor) ByteString(com.linkedin.data.ByteString) CustomString(com.linkedin.restli.server.custom.types.CustomString) RequestExecutionReport(com.linkedin.restli.server.RequestExecutionReport) AsyncStatusCollectionResource(com.linkedin.restli.server.twitter.AsyncStatusCollectionResource) Capture(org.easymock.Capture) RestException(com.linkedin.r2.message.rest.RestException) URISyntaxException(java.net.URISyntaxException) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) RoutingException(com.linkedin.restli.server.RoutingException) RestLiSyntaxException(com.linkedin.restli.internal.server.util.RestLiSyntaxException) Callback(com.linkedin.common.callback.Callback) RestLiCallback(com.linkedin.restli.internal.server.RestLiCallback) FilterChainCallback(com.linkedin.restli.internal.server.filter.FilterChainCallback) RequestExecutionCallback(com.linkedin.restli.server.RequestExecutionCallback) ResourceModel(com.linkedin.restli.internal.server.model.ResourceModel) RestLiTestHelper.buildResourceModel(com.linkedin.restli.server.test.RestLiTestHelper.buildResourceModel) TaskStatusCollectionResource(com.linkedin.restli.server.twitter.TaskStatusCollectionResource) StatusCollectionResource(com.linkedin.restli.server.twitter.StatusCollectionResource) AsyncStatusCollectionResource(com.linkedin.restli.server.twitter.AsyncStatusCollectionResource) CustomStatusCollectionResource(com.linkedin.restli.server.twitter.CustomStatusCollectionResource) PromiseStatusCollectionResource(com.linkedin.restli.server.twitter.PromiseStatusCollectionResource) EasyMock.anyObject(org.easymock.EasyMock.anyObject) RestLiAttachmentReader(com.linkedin.restli.common.attachments.RestLiAttachmentReader) RestLiResponseAttachments(com.linkedin.restli.server.RestLiResponseAttachments) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest)

Example 67 with RestResponse

use of com.linkedin.r2.message.rest.RestResponse in project rest.li by linkedin.

the class TestRestLiMethodInvocation method testInvokeWithUnsupportedAcceptMimeType.

@Test
public void testInvokeWithUnsupportedAcceptMimeType() throws Exception {
    RestRequestBuilder builder = new RestRequestBuilder(new URI("")).addHeaderValue("Accept", "text/plain").setHeader(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, version.toString());
    RestRequest request = builder.build();
    final RestLiAttachmentReader attachmentReader = new RestLiAttachmentReader(null);
    final CountDownLatch latch = new CountDownLatch(1);
    RestLiResponseHandler restLiResponseHandler = new RestLiResponseHandler.Builder().build();
    RequestExecutionCallback<RestResponse> executionCallback = new RequestExecutionCallback<RestResponse>() {

        @Override
        public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
            latch.countDown();
            Assert.assertTrue(e instanceof RestException);
            RestException ex = (RestException) e;
            Assert.assertEquals(ex.getResponse().getStatus(), HttpStatus.S_406_NOT_ACCEPTABLE.getCode());
            Assert.assertEquals(requestAttachmentReader, attachmentReader);
            Assert.assertNull(responseAttachments);
        }

        @Override
        public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
            Assert.fail();
        }
    };
    ServerResourceContext resourceContext = new ResourceContextImpl(new PathKeysImpl(), new RestRequestBuilder(URI.create("")).setHeader(RestConstants.HEADER_RESTLI_PROTOCOL_VERSION, AllProtocolVersions.LATEST_PROTOCOL_VERSION.toString()).build(), new RequestContext(), false, attachmentReader);
    try {
        RoutingResult routingResult = new RoutingResult(resourceContext, null);
        RestUtils.validateRequestHeadersAndUpdateResourceContext(request.getHeaders(), (ServerResourceContext) routingResult.getContext());
        FilterChainCallback filterChainCallback = new FilterChainCallbackImpl(null, _invoker, null, null, null, restLiResponseHandler, executionCallback);
        final RestLiCallback<Object> callback = new RestLiCallback<Object>(null, new RestLiFilterResponseContextFactory<Object>(request, null, restLiResponseHandler), new RestLiFilterChain(null, filterChainCallback));
        _invoker.invoke(null, routingResult, null, callback, null);
        latch.await();
    } catch (Exception e) {
        // exception is expected
        Assert.assertTrue(e instanceof RestLiServiceException);
    }
    Assert.assertNull(resourceContext.getResponseMimeType());
}
Also used : URI(java.net.URI) RestLiFilterChain(com.linkedin.restli.internal.server.filter.RestLiFilterChain) RequestExecutionCallback(com.linkedin.restli.server.RequestExecutionCallback) RoutingResult(com.linkedin.restli.internal.server.RoutingResult) FilterChainCallback(com.linkedin.restli.internal.server.filter.FilterChainCallback) RestLiResponseHandler(com.linkedin.restli.internal.server.response.RestLiResponseHandler) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) FilterChainCallbackImpl(com.linkedin.restli.internal.server.filter.FilterChainCallbackImpl) RestLiCallback(com.linkedin.restli.internal.server.RestLiCallback) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) RequestContext(com.linkedin.r2.message.RequestContext) RestLiResponseAttachments(com.linkedin.restli.server.RestLiResponseAttachments) ResourceContextImpl(com.linkedin.restli.internal.server.ResourceContextImpl) RestResponse(com.linkedin.r2.message.rest.RestResponse) PathKeysImpl(com.linkedin.restli.internal.server.PathKeysImpl) RestException(com.linkedin.r2.message.rest.RestException) CountDownLatch(java.util.concurrent.CountDownLatch) RequestExecutionReport(com.linkedin.restli.server.RequestExecutionReport) RestException(com.linkedin.r2.message.rest.RestException) URISyntaxException(java.net.URISyntaxException) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) RoutingException(com.linkedin.restli.server.RoutingException) RestLiSyntaxException(com.linkedin.restli.internal.server.util.RestLiSyntaxException) RestRequest(com.linkedin.r2.message.rest.RestRequest) ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) EasyMock.anyObject(org.easymock.EasyMock.anyObject) RestLiAttachmentReader(com.linkedin.restli.common.attachments.RestLiAttachmentReader) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest)

Example 68 with RestResponse

use of com.linkedin.r2.message.rest.RestResponse in project rest.li by linkedin.

the class TestRestLiResponseHandler method testFieldProjectionRecordsPALSyntax.

@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "basicData")
public void testFieldProjectionRecordsPALSyntax(AcceptTypeData acceptTypeData, ProtocolVersion protocolVersion, String errorResponseHeaderName) throws Exception {
    RestResponse response;
    DataMap data = new DataMap(asMap("f1", "value", "f2", new DataMap(asMap("f3", "value", "f4", "value"))));
    // #1 all fields
    Status status = new Status(data);
    RestRequest request1 = buildRequest("/test?fields=f1,f2:(f3,f4)", acceptTypeData.acceptHeaders, protocolVersion);
    response = _responseHandler.buildResponse(request1, buildRoutingResult(request1, acceptTypeData.acceptHeaders), status);
    checkResponse(response, 200, 2, acceptTypeData.responseContentType, Status.class.getName(), null, true, errorResponseHeaderName);
    checkProjectedFields(response, new String[] { "f1", "f2", "f3" }, new String[0]);
    // #2 some fields
    RestRequest request2 = buildRequest("/test?fields=f1,f2:(f3)", acceptTypeData.acceptHeaders, protocolVersion);
    response = _responseHandler.buildResponse(request2, buildRoutingResult(request2, acceptTypeData.acceptHeaders), status);
    assertTrue(status.data().containsKey("f2"));
    checkResponse(response, 200, 2, acceptTypeData.responseContentType, Status.class.getName(), null, true, errorResponseHeaderName);
    checkProjectedFields(response, new String[] { "f1", "f2", "f3" }, new String[] { "f4" });
    // #3 no fields
    RestRequest request3 = buildRequest("/test?fields=", acceptTypeData.acceptHeaders, protocolVersion);
    response = _responseHandler.buildResponse(request3, buildRoutingResult(request3, acceptTypeData.acceptHeaders), status);
    checkResponse(response, 200, 2, acceptTypeData.responseContentType, Status.class.getName(), null, true, errorResponseHeaderName);
    checkProjectedFields(response, new String[] {}, new String[] { "f1", "f2", "f3", "f4" });
    assertTrue(status.data().containsKey("f1"));
    assertTrue(status.data().containsKey("f2"));
    // #4 fields not in schema
    RestRequest request4 = buildRequest("/test?fields=f2:(f99)", acceptTypeData.acceptHeaders, protocolVersion);
    response = _responseHandler.buildResponse(request4, buildRoutingResult(request4, acceptTypeData.acceptHeaders), status);
    checkResponse(response, 200, 2, acceptTypeData.responseContentType, Status.class.getName(), null, true, errorResponseHeaderName);
    checkProjectedFields(response, new String[] { "f2" }, new String[] { "f1", "f3", "f99" });
    assertTrue(status.data().containsKey("f2"));
}
Also used : UpdateStatus(com.linkedin.restli.common.UpdateStatus) CreateStatus(com.linkedin.restli.common.CreateStatus) Status(com.linkedin.restli.server.twitter.TwitterTestDataModels.Status) HttpStatus(com.linkedin.restli.common.HttpStatus) RestRequest(com.linkedin.r2.message.rest.RestRequest) RestResponse(com.linkedin.r2.message.rest.RestResponse) PartialRestResponse(com.linkedin.restli.internal.server.response.PartialRestResponse) DataMap(com.linkedin.data.DataMap) Test(org.testng.annotations.Test)

Example 69 with RestResponse

use of com.linkedin.r2.message.rest.RestResponse in project rest.li by linkedin.

the class TestRestLiResponseHandler method testActions.

@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "statusActionData")
public void testActions(AcceptTypeData acceptTypeData, String response1, String response2, ProtocolVersion protocolVersion, String errorResponseHeaderName) throws Exception {
    final RestRequest request = buildRequest(acceptTypeData.acceptHeaders, protocolVersion);
    RestResponse response;
    // #1 simple record template
    response = _responseHandler.buildResponse(request, buildRoutingResultAction(Status.class, request, acceptTypeData.acceptHeaders), buildStatusRecord());
    checkResponse(response, 200, 2, acceptTypeData.responseContentType, ActionResponse.class.getName(), Status.class.getName(), true, errorResponseHeaderName);
    assertEquals(response.getEntity().asAvroString(), response1);
    // #2 DataTemplate response
    StringMap map = new StringMap();
    map.put("key1", "value1");
    map.put("key2", "value2");
    response = _responseHandler.buildResponse(request, buildRoutingResultAction(StringMap.class, request, acceptTypeData.acceptHeaders), map);
    checkResponse(response, 200, 2, acceptTypeData.responseContentType, ActionResponse.class.getName(), StringMap.class.getName(), true, errorResponseHeaderName);
    //Convert both of these back into maps depending on their response type
    final DataMap actualMap;
    final DataMap expectedMap;
    if (acceptTypeData == AcceptTypeData.PSON) {
        actualMap = PSON_DATA_CODEC.bytesToMap(response.getEntity().copyBytes());
        expectedMap = PSON_DATA_CODEC.bytesToMap(ByteString.copyAvroString(response2, false).copyBytes());
    } else {
        actualMap = JACKSON_DATA_CODEC.bytesToMap(response.getEntity().copyBytes());
        expectedMap = JACKSON_DATA_CODEC.stringToMap(response2);
    }
    assertEquals(actualMap, expectedMap);
    // #3 empty response
    response = _responseHandler.buildResponse(request, buildRoutingResultAction(Void.TYPE, request, acceptTypeData.acceptHeaders), null);
    checkResponse(response, 200, 1, null, null, null, false, errorResponseHeaderName);
    assertEquals(response.getEntity().asAvroString(), "");
}
Also used : UpdateStatus(com.linkedin.restli.common.UpdateStatus) CreateStatus(com.linkedin.restli.common.CreateStatus) Status(com.linkedin.restli.server.twitter.TwitterTestDataModels.Status) HttpStatus(com.linkedin.restli.common.HttpStatus) StringMap(com.linkedin.data.template.StringMap) RestRequest(com.linkedin.r2.message.rest.RestRequest) RestResponse(com.linkedin.r2.message.rest.RestResponse) PartialRestResponse(com.linkedin.restli.internal.server.response.PartialRestResponse) ActionResponse(com.linkedin.restli.common.ActionResponse) DataMap(com.linkedin.data.DataMap) Test(org.testng.annotations.Test)

Example 70 with RestResponse

use of com.linkedin.r2.message.rest.RestResponse in project rest.li by linkedin.

the class TestRestLiResponseHandler method testFieldProjection_records.

@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "basicData")
public void testFieldProjection_records(AcceptTypeData acceptTypeData, ProtocolVersion protocolVersion, String errorResponseHeaderName) throws Exception {
    RestResponse response;
    // #1 all fields
    RestRequest request1 = buildRequest("/test?fields=f1,f2,f3", acceptTypeData.acceptHeaders, protocolVersion);
    Status status = buildStatusWithFields("f1", "f2", "f3");
    response = _responseHandler.buildResponse(request1, buildRoutingResult(request1, acceptTypeData.acceptHeaders), status);
    checkResponse(response, 200, 2, acceptTypeData.responseContentType, Status.class.getName(), null, true, errorResponseHeaderName);
    checkProjectedFields(response, new String[] { "f1", "f2", "f3" }, new String[0]);
    // #2 some fields
    RestRequest request2 = buildRequest("/test?fields=f1,f3", acceptTypeData.acceptHeaders, protocolVersion);
    response = _responseHandler.buildResponse(request2, buildRoutingResult(request2, acceptTypeData.acceptHeaders), status);
    assertTrue(status.data().containsKey("f2"));
    checkResponse(response, 200, 2, acceptTypeData.responseContentType, Status.class.getName(), null, true, errorResponseHeaderName);
    checkProjectedFields(response, new String[] { "f1", "f3" }, new String[] { "f2" });
    // #3 no fields
    RestRequest request3 = buildRequest("/test?fields=", acceptTypeData.acceptHeaders, protocolVersion);
    response = _responseHandler.buildResponse(request3, buildRoutingResult(request3, acceptTypeData.acceptHeaders), status);
    checkResponse(response, 200, 2, acceptTypeData.responseContentType, Status.class.getName(), null, true, errorResponseHeaderName);
    checkProjectedFields(response, new String[] {}, new String[] { "f1", "f2", "f3" });
    assertTrue(status.data().containsKey("f1"));
    assertTrue(status.data().containsKey("f2"));
    assertTrue(status.data().containsKey("f3"));
    // #4 fields not in schema
    RestRequest request4 = buildRequest("/test?fields=f1,f99", acceptTypeData.acceptHeaders, protocolVersion);
    response = _responseHandler.buildResponse(request4, buildRoutingResult(request4, acceptTypeData.acceptHeaders), status);
    checkResponse(response, 200, 2, acceptTypeData.responseContentType, Status.class.getName(), null, true, errorResponseHeaderName);
    checkProjectedFields(response, new String[] { "f1" }, new String[] { "f2", "f3", "f99" });
    assertTrue(status.data().containsKey("f2"));
    assertTrue(status.data().containsKey("f3"));
}
Also used : UpdateStatus(com.linkedin.restli.common.UpdateStatus) CreateStatus(com.linkedin.restli.common.CreateStatus) Status(com.linkedin.restli.server.twitter.TwitterTestDataModels.Status) HttpStatus(com.linkedin.restli.common.HttpStatus) RestRequest(com.linkedin.r2.message.rest.RestRequest) RestResponse(com.linkedin.r2.message.rest.RestResponse) PartialRestResponse(com.linkedin.restli.internal.server.response.PartialRestResponse) Test(org.testng.annotations.Test)

Aggregations

RestResponse (com.linkedin.r2.message.rest.RestResponse)231 Test (org.testng.annotations.Test)174 RestRequest (com.linkedin.r2.message.rest.RestRequest)147 RequestContext (com.linkedin.r2.message.RequestContext)108 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)100 URI (java.net.URI)74 RestException (com.linkedin.r2.message.rest.RestException)68 RestResponseBuilder (com.linkedin.r2.message.rest.RestResponseBuilder)55 ByteString (com.linkedin.data.ByteString)50 FutureCallback (com.linkedin.common.callback.FutureCallback)45 Callback (com.linkedin.common.callback.Callback)43 HashMap (java.util.HashMap)41 ExecutionException (java.util.concurrent.ExecutionException)40 Map (java.util.Map)38 StreamResponse (com.linkedin.r2.message.stream.StreamResponse)35 StreamRequest (com.linkedin.r2.message.stream.StreamRequest)29 URISyntaxException (java.net.URISyntaxException)27 FilterRequestContext (com.linkedin.restli.server.filter.FilterRequestContext)24 FilterChain (com.linkedin.r2.filter.FilterChain)23 BeforeTest (org.testng.annotations.BeforeTest)23