Search in sources :

Example 1 with SettablePromise

use of com.linkedin.parseq.promise.SettablePromise in project rest.li by linkedin.

the class TestRestLiMethodInvocation method testStreaming.

@Test
public void testStreaming() throws RestLiSyntaxException, URISyntaxException {
    Map<String, ResourceModel> resourceModelMap = buildResourceModels(StatusCollectionResource.class, AsyncStatusCollectionResource.class, PromiseStatusCollectionResource.class, TaskStatusCollectionResource.class);
    final String payload = "{\"metadata\": \"someMetadata\"}";
    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;
    //Sync Method Execution - Successful scenario
    methodDescriptor = statusResourceModel.findActionMethod("streamingAction", ResourceLevel.COLLECTION);
    statusResource = getMockResource(StatusCollectionResource.class);
    EasyMock.expect(statusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject())).andReturn(1234l).once();
    checkInvocation(statusResource, methodDescriptor, "POST", version, "/statuses/?action=streamingAction", payload, null, 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) {
        }
    }, false, false, new RestLiAttachmentReader(null), new RestLiResponseAttachments.Builder().build());
    //Sync Method Execution - Error scenario
    statusResource = getMockResource(StatusCollectionResource.class);
    EasyMock.expect(statusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject())).andThrow(new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR)).once();
    checkInvocation(statusResource, methodDescriptor, "POST", version, "/statuses/?action=streamingAction", payload, null, new RequestExecutionCallback<RestResponse>() {

        @Override
        public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
        }

        @Override
        public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
            Assert.fail("Request passed unexpectedly.");
        }
    }, false, false, new RestLiAttachmentReader(null), new RestLiResponseAttachments.Builder().build());
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //Callback Method Execution - Successful scenario
    methodDescriptor = asyncStatusResourceModel.findMethod(ResourceMethod.ACTION);
    asyncStatusResource = getMockResource(AsyncStatusCollectionResource.class);
    asyncStatusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject(), EasyMock.<Callback<Long>>anyObject());
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {

        @Override
        public Object answer() throws Throwable {
            @SuppressWarnings("unchecked") Callback<Long> callback = (Callback<Long>) EasyMock.getCurrentArguments()[2];
            callback.onSuccess(1234l);
            return null;
        }
    });
    checkInvocation(asyncStatusResource, methodDescriptor, "POST", version, "/asyncstatuses/?action=streamingAction", payload, null, 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) {
        }
    }, false, false, new RestLiAttachmentReader(null), new RestLiResponseAttachments.Builder().build());
    //Callback Method Execution - Error scenario
    asyncStatusResource = getMockResource(AsyncStatusCollectionResource.class);
    asyncStatusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject(), EasyMock.<Callback<Long>>anyObject());
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {

        @Override
        public Object answer() throws Throwable {
            @SuppressWarnings("unchecked") Callback<Long> callback = (Callback<Long>) EasyMock.getCurrentArguments()[2];
            callback.onError(new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR));
            return null;
        }
    });
    checkInvocation(asyncStatusResource, methodDescriptor, "POST", version, "/asyncstatuses/?action=streamingAction", payload, null, new RequestExecutionCallback<RestResponse>() {

        @Override
        public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
        }

        @Override
        public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
            Assert.fail("Request passed unexpectedly.");
        }
    }, false, false, new RestLiAttachmentReader(null), new RestLiResponseAttachments.Builder().build());
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //Promise Method Execution - Successful scenario
    methodDescriptor = promiseStatusResourceModel.findActionMethod("streamingAction", ResourceLevel.COLLECTION);
    promiseStatusResource = getMockResource(PromiseStatusCollectionResource.class);
    promiseStatusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject());
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {

        @Override
        public Object answer() throws Throwable {
            final SettablePromise<Long> result = Promises.settable();
            final Runnable requestHandler = new Runnable() {

                public void run() {
                    try {
                        result.done(1234l);
                    } catch (final Throwable throwable) {
                        result.fail(throwable);
                    }
                }
            };
            _scheduler.schedule(requestHandler, 0, TimeUnit.MILLISECONDS);
            return result;
        }
    });
    checkInvocation(promiseStatusResource, methodDescriptor, "POST", version, "/promisestatuses/?action=streamingAction", payload, null, 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) {
        }
    }, false, false, new RestLiAttachmentReader(null), new RestLiResponseAttachments.Builder().build());
    //Promise Method Execution - Error scenario
    promiseStatusResource = getMockResource(PromiseStatusCollectionResource.class);
    promiseStatusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject());
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {

        @Override
        public Object answer() throws Throwable {
            final SettablePromise<Long> result = Promises.settable();
            final Runnable requestHandler = new Runnable() {

                public void run() {
                    result.fail(new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR));
                }
            };
            _scheduler.schedule(requestHandler, 0, TimeUnit.MILLISECONDS);
            return result;
        }
    });
    checkInvocation(promiseStatusResource, methodDescriptor, "POST", version, "/promisestatuses/?action=streamingAction", payload, null, new RequestExecutionCallback<RestResponse>() {

        @Override
        public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
        }

        @Override
        public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
            Assert.fail("Request passed unexpectedly.");
        }
    }, false, false, new RestLiAttachmentReader(null), new RestLiResponseAttachments.Builder().build());
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //Task Method Execution - Successful scenario
    methodDescriptor = taskStatusResourceModel.findMethod(ResourceMethod.ACTION);
    taskStatusResource = getMockResource(TaskStatusCollectionResource.class);
    taskStatusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject());
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {

        @Override
        public Object answer() throws Throwable {
            return new BaseTask<Long>() {

                protected Promise<Long> run(final Context context) throws Exception {
                    return Promises.value(1234l);
                }
            };
        }
    });
    checkInvocation(taskStatusResource, methodDescriptor, "POST", version, "/taskstatuses/?action=streamingAction", payload, null, 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) {
        }
    }, false, false, new RestLiAttachmentReader(null), new RestLiResponseAttachments.Builder().build());
    //Task Method Execution - Error scenario
    taskStatusResource = getMockResource(TaskStatusCollectionResource.class);
    taskStatusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject());
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {

        @Override
        public Object answer() throws Throwable {
            return new BaseTask<Long>() {

                protected Promise<Long> run(final Context context) throws Exception {
                    return Promises.error(new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR));
                }
            };
        }
    });
    checkInvocation(taskStatusResource, methodDescriptor, "POST", version, "/taskstatuses/?action=streamingAction", payload, null, new RequestExecutionCallback<RestResponse>() {

        @Override
        public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
        }

        @Override
        public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
            Assert.fail("Request passed unexpectedly.");
        }
    }, false, false, new RestLiAttachmentReader(null), new RestLiResponseAttachments.Builder().build());
}
Also used : ResourceMethodDescriptor(com.linkedin.restli.internal.server.model.ResourceMethodDescriptor) RequestExecutionReportBuilder(com.linkedin.restli.server.RequestExecutionReportBuilder) EngineBuilder(com.linkedin.parseq.EngineBuilder) RestLiArgumentBuilder(com.linkedin.restli.internal.server.methods.arguments.RestLiArgumentBuilder) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) ErrorResponseBuilder(com.linkedin.restli.internal.server.response.ErrorResponseBuilder) ByteString(com.linkedin.data.ByteString) CustomString(com.linkedin.restli.server.custom.types.CustomString) RestLiServiceException(com.linkedin.restli.server.RestLiServiceException) 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) RestLiResponseAttachments(com.linkedin.restli.server.RestLiResponseAttachments) PagingContext(com.linkedin.restli.server.PagingContext) ResourceContext(com.linkedin.restli.server.ResourceContext) ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) Context(com.linkedin.parseq.Context) RequestContext(com.linkedin.r2.message.RequestContext) TaskStatusCollectionResource(com.linkedin.restli.server.twitter.TaskStatusCollectionResource) PromiseStatusCollectionResource(com.linkedin.restli.server.twitter.PromiseStatusCollectionResource) RestResponse(com.linkedin.r2.message.rest.RestResponse) SettablePromise(com.linkedin.parseq.promise.SettablePromise) RequestExecutionReport(com.linkedin.restli.server.RequestExecutionReport) AsyncStatusCollectionResource(com.linkedin.restli.server.twitter.AsyncStatusCollectionResource) 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) SettablePromise(com.linkedin.parseq.promise.SettablePromise) Promise(com.linkedin.parseq.promise.Promise) 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) CustomLong(com.linkedin.restli.server.custom.types.CustomLong) 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 2 with SettablePromise

use of com.linkedin.parseq.promise.SettablePromise in project rest.li by linkedin.

the class TestAsyncMethodInvocationPlanClass method engine.

private Engine engine(SettablePromise<Trace> traceHolder) {
    ExecutorService taskScheduler = Executors.newFixedThreadPool(1);
    ScheduledExecutorService timerScheduler = Executors.newSingleThreadScheduledExecutor();
    return new EngineBuilder().setTaskExecutor(taskScheduler).setTimerScheduler(timerScheduler).setPlanCompletionListener(planCtx -> {
        try {
            traceHolder.done(planCtx.getRootTask().getTrace());
        } catch (PromiseResolvedException e) {
        }
    }).build();
}
Also used : Engine(com.linkedin.parseq.Engine) DataProvider(org.testng.annotations.DataProvider) URISyntaxException(java.net.URISyntaxException) Assert.assertEquals(org.testng.Assert.assertEquals) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) Test(org.testng.annotations.Test) Callback(com.linkedin.common.callback.Callback) RestLiConfig(com.linkedin.restli.server.RestLiConfig) RestResponse(com.linkedin.r2.message.rest.RestResponse) MultiplexerRunMode(com.linkedin.restli.server.multiplexer.MultiplexerRunMode) Trace(com.linkedin.parseq.trace.Trace) ResourceModel(com.linkedin.restli.internal.server.model.ResourceModel) PromiseResolvedException(com.linkedin.parseq.promise.PromiseResolvedException) SettablePromise(com.linkedin.parseq.promise.SettablePromise) RestConstants(com.linkedin.restli.common.RestConstants) RestLiServer(com.linkedin.restli.server.RestLiServer) Map(java.util.Map) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) AllProtocolVersions(com.linkedin.restli.internal.common.AllProtocolVersions) StringMap(com.linkedin.data.template.StringMap) URI(java.net.URI) JacksonDataCodec(com.linkedin.data.codec.JacksonDataCodec) RestMethod(com.linkedin.r2.message.rest.RestMethod) IndividualRequestMap(com.linkedin.restli.common.multiplexer.IndividualRequestMap) ExecutorService(java.util.concurrent.ExecutorService) HttpMethod(com.linkedin.restli.common.HttpMethod) RestRequest(com.linkedin.r2.message.rest.RestRequest) ImmutableMap(com.google.common.collect.ImmutableMap) Promises(com.linkedin.parseq.promise.Promises) IOException(java.io.IOException) Executors(java.util.concurrent.Executors) ResourceFactory(com.linkedin.restli.server.resources.ResourceFactory) TimeUnit(java.util.concurrent.TimeUnit) MultiplexedRequestContent(com.linkedin.restli.common.multiplexer.MultiplexedRequestContent) CountDownLatch(java.util.concurrent.CountDownLatch) RequestContext(com.linkedin.r2.message.RequestContext) EngineBuilder(com.linkedin.parseq.EngineBuilder) Assert.assertTrue(org.testng.Assert.assertTrue) IndividualRequest(com.linkedin.restli.common.multiplexer.IndividualRequest) Collections(java.util.Collections) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) PromiseResolvedException(com.linkedin.parseq.promise.PromiseResolvedException) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutorService(java.util.concurrent.ExecutorService) EngineBuilder(com.linkedin.parseq.EngineBuilder)

Aggregations

Callback (com.linkedin.common.callback.Callback)2 EngineBuilder (com.linkedin.parseq.EngineBuilder)2 SettablePromise (com.linkedin.parseq.promise.SettablePromise)2 RequestContext (com.linkedin.r2.message.RequestContext)2 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)2 RestResponse (com.linkedin.r2.message.rest.RestResponse)2 ResourceModel (com.linkedin.restli.internal.server.model.ResourceModel)2 URISyntaxException (java.net.URISyntaxException)2 Test (org.testng.annotations.Test)2 ImmutableMap (com.google.common.collect.ImmutableMap)1 ByteString (com.linkedin.data.ByteString)1 JacksonDataCodec (com.linkedin.data.codec.JacksonDataCodec)1 StringMap (com.linkedin.data.template.StringMap)1 Context (com.linkedin.parseq.Context)1 Engine (com.linkedin.parseq.Engine)1 Promise (com.linkedin.parseq.promise.Promise)1 PromiseResolvedException (com.linkedin.parseq.promise.PromiseResolvedException)1 Promises (com.linkedin.parseq.promise.Promises)1 Trace (com.linkedin.parseq.trace.Trace)1 RestException (com.linkedin.r2.message.rest.RestException)1