Search in sources :

Example 1 with Promise

use of com.linkedin.parseq.promise.Promise 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 Promise

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

the class GreetingsResourceCodeGenerator method printMethodBody.

private void printMethodBody(final PrintStream out, final Method method) {
    final Type returnType = method.getGenericReturnType();
    switch(_type) {
        case CALLBACK:
            out.println("final Runnable requestHandler = new Runnable() {");
            out.println("public void run () {");
            out.println("try {");
            if (returnType == void.class) {
                printImplCall(out, method);
                out.println(";");
                out.println("callback.onSuccess(null);");
            } else {
                out.print("callback.onSuccess(");
                printImplCall(out, method);
                out.println(");");
            }
            out.println("} catch (final Throwable throwable) {");
            out.println("callback.onError(throwable);");
            // try catch
            out.println("}");
            // run
            out.println("}");
            // runnable
            out.println("};");
            out.printf("_scheduler.schedule(requestHandler, DELAY, %s.MILLISECONDS);", className(TimeUnit.class));
            break;
        case PROMISE:
            if (_useParSeqCtx) {
                out.printf("final %s result = %s.settable();%n", genericWrapper(SettablePromise.class, returnType), className(Promises.class));
                out.println("final Runnable requestHandler = new Runnable() {");
                out.println("public void run () {");
                out.println("try {");
                if (returnType == void.class) {
                    printImplCall(out, method);
                    out.println(";");
                    out.println("result.done(null);");
                } else {
                    out.print("result.done(");
                    printImplCall(out, method);
                    out.println(");");
                }
                out.println("} catch (final Throwable throwable) {");
                out.println("result.fail(throwable);");
                // try catch
                out.println("}");
                // run
                out.println("}");
                // runnable
                out.println("};");
                out.printf("psContext.run(%s.action(\"restli-%s\", requestHandler::run));%n", className(Task.class), method.getName());
                out.println("return result;");
            } else {
                out.printf("final %s result = %s.settable();%n", genericWrapper(SettablePromise.class, returnType), className(Promises.class));
                out.println("final Runnable requestHandler = new Runnable() {");
                out.println("public void run () {");
                out.println("try {");
                if (returnType == void.class) {
                    printImplCall(out, method);
                    out.println(";");
                    out.println("result.done(null);");
                } else {
                    out.print("result.done(");
                    printImplCall(out, method);
                    out.println(");");
                }
                out.println("} catch (final Throwable throwable) {");
                out.println("result.fail(throwable);");
                // try catch
                out.println("}");
                // run
                out.println("}");
                // runnable
                out.println("};");
                out.printf("_scheduler.schedule(requestHandler, DELAY, %s.MILLISECONDS);", className(TimeUnit.class));
                out.println("return result;");
            }
            break;
        case SYNC:
            if (!returnType.equals(void.class))
                out.print("return ");
            printImplCall(out, method);
            out.println(";");
            break;
        case TASK:
            out.printf("return new %s()%n", genericWrapper(BaseTask.class, returnType));
            out.println("{");
            out.printf("protected %s run(final %s context) throws Exception%n", genericWrapper(Promise.class, returnType), className(Context.class));
            out.println("{");
            if (returnType.equals(void.class)) {
                printImplCall(out, method);
                out.println(";");
                out.printf("return %s.value(null);%n", className(Promises.class));
            } else {
                out.printf("return %s.value(", className(Promises.class));
                printImplCall(out, method);
                out.println(");");
            }
            out.println("}");
            out.println("};");
            break;
    }
}
Also used : Context(com.linkedin.parseq.Context) SettablePromise(com.linkedin.parseq.promise.SettablePromise) Promise(com.linkedin.parseq.promise.Promise) GenericArrayType(java.lang.reflect.GenericArrayType) InterfaceType(com.linkedin.restli.internal.server.model.ResourceMethodDescriptor.InterfaceType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) BaseTask(com.linkedin.parseq.BaseTask) Task(com.linkedin.parseq.Task) Promises(com.linkedin.parseq.promise.Promises) BaseTask(com.linkedin.parseq.BaseTask) TimeUnit(java.util.concurrent.TimeUnit) SettablePromise(com.linkedin.parseq.promise.SettablePromise)

Example 3 with Promise

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

the class GreetingsResourceCodeGenerator method printMethod.

private void printMethod(final PrintStream out, final Method method) {
    final Type returnType = method.getGenericReturnType();
    // method annotations
    final Annotation[] annos = method.getAnnotations();
    for (final Annotation anno : annos) {
        if (RestMethod.class.equals(anno.annotationType().getEnclosingClass()))
            if (!_templateClass.equals(KeyValueResource.class))
                continue;
        out.println(toStrAnnotation(anno));
    }
    // method header
    out.print("public ");
    // return type
    switch(_type) {
        case CALLBACK:
            out.print("void");
            break;
        case PROMISE:
            out.print(genericWrapper(Promise.class, returnType));
            break;
        case SYNC:
            out.print(toStrGenericType(returnType));
            break;
        case TASK:
            out.print(genericWrapper(Task.class, returnType));
            break;
    }
    out.printf(" %s(", method.getName());
    printArgumentList(out, method);
    out.print(")");
    printThrowsClause(out, method);
    out.println();
    // begin method body
    out.println("{");
    printMethodBody(out, method);
    // end method
    out.println("}");
    out.println();
}
Also used : SettablePromise(com.linkedin.parseq.promise.SettablePromise) Promise(com.linkedin.parseq.promise.Promise) GenericArrayType(java.lang.reflect.GenericArrayType) InterfaceType(com.linkedin.restli.internal.server.model.ResourceMethodDescriptor.InterfaceType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) BaseTask(com.linkedin.parseq.BaseTask) Task(com.linkedin.parseq.Task) Annotation(java.lang.annotation.Annotation)

Aggregations

Promise (com.linkedin.parseq.promise.Promise)3 SettablePromise (com.linkedin.parseq.promise.SettablePromise)3 BaseTask (com.linkedin.parseq.BaseTask)2 Context (com.linkedin.parseq.Context)2 Task (com.linkedin.parseq.Task)2 InterfaceType (com.linkedin.restli.internal.server.model.ResourceMethodDescriptor.InterfaceType)2 GenericArrayType (java.lang.reflect.GenericArrayType)2 ParameterizedType (java.lang.reflect.ParameterizedType)2 Type (java.lang.reflect.Type)2 Callback (com.linkedin.common.callback.Callback)1 ByteString (com.linkedin.data.ByteString)1 EngineBuilder (com.linkedin.parseq.EngineBuilder)1 Promises (com.linkedin.parseq.promise.Promises)1 RequestContext (com.linkedin.r2.message.RequestContext)1 RestException (com.linkedin.r2.message.rest.RestException)1 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)1 RestResponse (com.linkedin.r2.message.rest.RestResponse)1 RestLiAttachmentReader (com.linkedin.restli.common.attachments.RestLiAttachmentReader)1 RestLiCallback (com.linkedin.restli.internal.server.RestLiCallback)1 ServerResourceContext (com.linkedin.restli.internal.server.ServerResourceContext)1