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());
}
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);
}
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;
}
}
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 } };
}
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;
}
Aggregations