Search in sources :

Example 1 with Context

use of com.linkedin.parseq.Context in project rest.li by linkedin.

the class TestRestLiMethodInvocation method testStreaming.

@Test
public void testStreaming() throws Exception {
    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.anyObject(), EasyMock.anyObject())).andReturn(1234l).once();
    checkInvocation(statusResource, new RequestContext(), methodDescriptor, "POST", version, "/statuses/?action=streamingAction", payload, null, new Callback<RestResponse>() {

        @Override
        public void onError(Throwable e) {
            Assert.fail("Request failed unexpectedly.");
        }

        @Override
        public void onSuccess(RestResponse result) {
        }
    }, false, false, new RestLiAttachmentReader(null), new RestLiResponseAttachments.Builder().build());
    // Sync Method Execution - Error scenario
    statusResource = getMockResource(StatusCollectionResource.class);
    EasyMock.expect(statusResource.streamingAction(EasyMock.anyObject(), EasyMock.anyObject())).andThrow(new RestLiServiceException(HttpStatus.S_500_INTERNAL_SERVER_ERROR)).once();
    checkInvocation(statusResource, new RequestContext(), methodDescriptor, "POST", version, "/statuses/?action=streamingAction", payload, null, new Callback<RestResponse>() {

        @Override
        public void onError(Throwable e) {
        }

        @Override
        public void onSuccess(RestResponse result) {
            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.anyObject(), EasyMock.anyObject(), EasyMock.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, new RequestContext(), methodDescriptor, "POST", version, "/asyncstatuses/?action=streamingAction", payload, null, new Callback<RestResponse>() {

        @Override
        public void onError(Throwable e) {
            Assert.fail("Request failed unexpectedly.");
        }

        @Override
        public void onSuccess(RestResponse result) {
        }
    }, false, false, new RestLiAttachmentReader(null), new RestLiResponseAttachments.Builder().build());
    // Callback Method Execution - Error scenario
    asyncStatusResource = getMockResource(AsyncStatusCollectionResource.class);
    asyncStatusResource.streamingAction(EasyMock.anyObject(), EasyMock.anyObject(), EasyMock.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, new RequestContext(), methodDescriptor, "POST", version, "/asyncstatuses/?action=streamingAction", payload, null, new Callback<RestResponse>() {

        @Override
        public void onError(Throwable e) {
        }

        @Override
        public void onSuccess(RestResponse result) {
            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.anyObject(), EasyMock.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, new RequestContext(), methodDescriptor, "POST", version, "/promisestatuses/?action=streamingAction", payload, null, new Callback<RestResponse>() {

        @Override
        public void onError(Throwable e) {
            Assert.fail("Request failed unexpectedly.");
        }

        @Override
        public void onSuccess(RestResponse result) {
        }
    }, false, false, new RestLiAttachmentReader(null), new RestLiResponseAttachments.Builder().build());
    // Promise Method Execution - Error scenario
    promiseStatusResource = getMockResource(PromiseStatusCollectionResource.class);
    promiseStatusResource.streamingAction(EasyMock.anyObject(), EasyMock.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, new RequestContext(), methodDescriptor, "POST", version, "/promisestatuses/?action=streamingAction", payload, null, new Callback<RestResponse>() {

        @Override
        public void onError(Throwable e) {
        }

        @Override
        public void onSuccess(RestResponse result) {
            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.anyObject(), EasyMock.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, new RequestContext(), methodDescriptor, "POST", version, "/taskstatuses/?action=streamingAction", payload, null, new Callback<RestResponse>() {

        @Override
        public void onError(Throwable e) {
            Assert.fail("Request failed unexpectedly.");
        }

        @Override
        public void onSuccess(RestResponse result) {
        }
    }, false, false, new RestLiAttachmentReader(null), new RestLiResponseAttachments.Builder().build());
    // Task Method Execution - Error scenario
    taskStatusResource = getMockResource(TaskStatusCollectionResource.class);
    taskStatusResource.streamingAction(EasyMock.anyObject(), EasyMock.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, new RequestContext(), methodDescriptor, "POST", version, "/taskstatuses/?action=streamingAction", payload, null, new Callback<RestResponse>() {

        @Override
        public void onError(Throwable e) {
        }

        @Override
        public void onSuccess(RestResponse result) {
            Assert.fail("Request passed unexpectedly.");
        }
    }, false, false, new RestLiAttachmentReader(null), new RestLiResponseAttachments.Builder().build());
}
Also used : ResourceMethodDescriptor(com.linkedin.restli.internal.server.model.ResourceMethodDescriptor) RestLiMethodConfigBuilder(com.linkedin.restli.server.config.RestLiMethodConfigBuilder) 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) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) RequestContext(com.linkedin.r2.message.RequestContext) PagingContext(com.linkedin.restli.server.PagingContext) 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) AsyncStatusCollectionResource(com.linkedin.restli.server.twitter.AsyncStatusCollectionResource) RestException(com.linkedin.r2.message.rest.RestException) 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) CustomLong(com.linkedin.restli.server.custom.types.CustomLong) 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 Context

use of com.linkedin.parseq.Context in project parseq by linkedin.

the class TestTaskToTrace method testUnfinishedTrace.

@Test
public void testUnfinishedTrace() throws InterruptedException {
    // Used to ensure that the task has started running
    final CountDownLatch cdl = new CountDownLatch(1);
    final SettablePromise<Void> promise = Promises.settable();
    final Task<Void> task = new BaseTask<Void>() {

        @Override
        public Promise<Void> run(final Context context) throws Exception {
            cdl.countDown();
            // Return a promise that won't be satisfied until after out test
            return promise;
        }
    };
    getEngine().run(task);
    assertTrue(cdl.await(5, TimeUnit.SECONDS));
    logTracingResults("TestTaskToTrace.testUnfinishedTrace", task);
    verifyShallowTrace(task);
    // Finish task
    promise.done(null);
}
Also used : Context(com.linkedin.parseq.Context) BaseTask(com.linkedin.parseq.BaseTask) CountDownLatch(java.util.concurrent.CountDownLatch) BaseEngineTest(com.linkedin.parseq.BaseEngineTest) Test(org.testng.annotations.Test)

Example 3 with Context

use of com.linkedin.parseq.Context 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 4 with Context

use of com.linkedin.parseq.Context in project rest.li by linkedin.

the class TestGetArgumentBuilder method asyncArgumentData.

@DataProvider(name = "asyncArgumentData")
private Object[][] asyncArgumentData() {
    List<Parameter<?>> callbackParams = new ArrayList<>();
    callbackParams.add(getIntegerParam());
    @SuppressWarnings("rawtypes") Parameter<Callback> cParam = new Parameter<>("", Callback.class, null, false, null, Parameter.ParamType.CALLBACK, false, new AnnotationSet(new Annotation[] {}));
    callbackParams.add(cParam);
    List<Parameter<?>> parSeqContextParams = new ArrayList<>();
    parSeqContextParams.add(getIntegerParam());
    parSeqContextParams.add(new Parameter<>("", Context.class, null, false, null, Parameter.ParamType.PARSEQ_CONTEXT_PARAM, false, new AnnotationSet(new Annotation[] {})));
    List<Parameter<?>> deprecatedParSeqContextParams = new ArrayList<>();
    deprecatedParSeqContextParams.add(getIntegerParam());
    @SuppressWarnings("deprecation") Parameter<Context> contextParam = new Parameter<>("", Context.class, null, false, null, Parameter.ParamType.PARSEQ_CONTEXT, false, new AnnotationSet(new Annotation[] {}));
    deprecatedParSeqContextParams.add(contextParam);
    return new Object[][] { { callbackParams }, { parSeqContextParams }, { deprecatedParSeqContextParams } };
}
Also used : Context(com.linkedin.parseq.Context) ServerResourceContext(com.linkedin.restli.internal.server.ServerResourceContext) Callback(com.linkedin.common.callback.Callback) ArrayList(java.util.ArrayList) Parameter(com.linkedin.restli.internal.server.model.Parameter) AnnotationSet(com.linkedin.restli.internal.server.model.AnnotationSet) Annotation(java.lang.annotation.Annotation) DataProvider(org.testng.annotations.DataProvider)

Example 5 with Context

use of com.linkedin.parseq.Context in project rest.li by linkedin.

the class RestLiAnnotationReader method buildPagingContextParam.

@SuppressWarnings("deprecation")
private static Parameter<?> buildPagingContextParam(final AnnotationSet annotations, final Class<?> paramType, final Class<?> paramAnnotationType) {
    if (!paramType.equals(PagingContext.class)) {
        throw new ResourceConfigException("Incorrect data type for param: @" + PagingContextParam.class.getSimpleName() + " or @" + com.linkedin.restli.server.annotations.Context.class.getSimpleName() + " parameter annotation must be of type " + PagingContext.class.getName());
    }
    PagingContext defaultContext = null;
    Parameter.ParamType parameter = null;
    if (paramAnnotationType.equals(PagingContextParam.class)) {
        PagingContextParam pagingContextParam = annotations.get(PagingContextParam.class);
        defaultContext = new PagingContext(pagingContextParam.defaultStart(), pagingContextParam.defaultCount(), false, false);
        parameter = Parameter.ParamType.PAGING_CONTEXT_PARAM;
    } else if (paramAnnotationType.equals(com.linkedin.restli.server.annotations.Context.class)) {
        com.linkedin.restli.server.annotations.Context contextParam = annotations.get(com.linkedin.restli.server.annotations.Context.class);
        defaultContext = new PagingContext(contextParam.defaultStart(), contextParam.defaultCount(), false, false);
        parameter = Parameter.ParamType.CONTEXT;
    } else {
        throw new ResourceConfigException("Param Annotation type must be 'PagingContextParam' or the deprecated 'Context' for PagingContext");
    }
    Optional optional = annotations.get(Optional.class);
    @SuppressWarnings({ "unchecked", "rawtypes" }) Parameter<?> param = new Parameter("", paramType, null, optional != null, defaultContext, parameter, false, annotations);
    return param;
}
Also used : PagingContext(com.linkedin.restli.server.PagingContext) ResourceContext(com.linkedin.restli.server.ResourceContext) Context(com.linkedin.parseq.Context) PagingContextParam(com.linkedin.restli.server.annotations.PagingContextParam) Optional(com.linkedin.restli.server.annotations.Optional) PagingContext(com.linkedin.restli.server.PagingContext) ResourceConfigException(com.linkedin.restli.server.ResourceConfigException)

Aggregations

Context (com.linkedin.parseq.Context)5 Callback (com.linkedin.common.callback.Callback)2 BaseTask (com.linkedin.parseq.BaseTask)2 Promise (com.linkedin.parseq.promise.Promise)2 SettablePromise (com.linkedin.parseq.promise.SettablePromise)2 ServerResourceContext (com.linkedin.restli.internal.server.ServerResourceContext)2 PagingContext (com.linkedin.restli.server.PagingContext)2 Test (org.testng.annotations.Test)2 ByteString (com.linkedin.data.ByteString)1 BaseEngineTest (com.linkedin.parseq.BaseEngineTest)1 EngineBuilder (com.linkedin.parseq.EngineBuilder)1 Task (com.linkedin.parseq.Task)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 FilterChainCallback (com.linkedin.restli.internal.server.filter.FilterChainCallback)1