use of com.linkedin.common.callback.Callback in project rest.li by linkedin.
the class TestMultiplexedCallback method testError.
@Test
public void testError() throws Exception {
FutureCallback<RestResponse> callback1 = new FutureCallback<RestResponse>();
FutureCallback<RestResponse> callback2 = new FutureCallback<RestResponse>();
ImmutableMap<Integer, Callback<RestResponse>> individualCallbacks = ImmutableMap.<Integer, Callback<RestResponse>>of(ID1, callback1, ID2, callback2);
FutureCallback<MultiplexedResponse> aggregatedCallback = new FutureCallback<MultiplexedResponse>();
MultiplexedCallback multiplexedCallback = new MultiplexedCallback(individualCallbacks, aggregatedCallback);
RestLiDecodingException exception = new RestLiDecodingException(null, null);
multiplexedCallback.onError(exception);
Assert.assertSame(getError(callback1), exception);
Assert.assertSame(getError(callback2), exception);
Assert.assertSame(getError(aggregatedCallback), exception);
}
use of com.linkedin.common.callback.Callback in project rest.li by linkedin.
the class TestScatterGather method testSendGetKVSGRequests.
private static void testSendGetKVSGRequests(ScatterGatherBuilder<Greeting> sg, Long[] requestIds) throws ServiceUnavailableException, InterruptedException {
Collection<ScatterGatherBuilder.KVRequestInfo<Long, Greeting>> scatterGatherRequests = buildScatterGatherGetKVRequests(sg, requestIds);
final Map<Long, Greeting> results = new ConcurrentHashMap<Long, Greeting>();
final CountDownLatch latch = new CountDownLatch(scatterGatherRequests.size());
final List<Throwable> errors = new ArrayList<Throwable>();
final List<BatchKVResponse<Long, Greeting>> responses = new ArrayList<BatchKVResponse<Long, Greeting>>();
for (ScatterGatherBuilder.KVRequestInfo<Long, Greeting> requestInfo : scatterGatherRequests) {
Callback<Response<BatchKVResponse<Long, Greeting>>> cb = new Callback<Response<BatchKVResponse<Long, Greeting>>>() {
@Override
public void onSuccess(Response<BatchKVResponse<Long, Greeting>> response) {
results.putAll(response.getEntity().getResults());
synchronized (responses) {
responses.add(response.getEntity());
}
latch.countDown();
}
@Override
public void onError(Throwable e) {
synchronized (errors) {
errors.add(e);
}
latch.countDown();
}
};
REST_CLIENT.sendRequest(requestInfo.getRequest(), requestInfo.getRequestContext(), cb);
}
latch.await();
if (!errors.isEmpty()) {
Assert.fail("Errors in scatter/gather: " + errors.toString());
}
Assert.assertEquals(results.values().size(), requestIds.length);
Set<Set<Long>> responseIdSets = new HashSet<Set<Long>>();
Set<Long> responseIds = new HashSet<Long>();
for (BatchKVResponse<Long, Greeting> response : responses) {
Set<Long> theseIds = response.getResults().keySet();
//no duplicate requests
Assert.assertFalse(responseIdSets.contains(theseIds));
for (Long id : theseIds) {
//no duplicate ids
Assert.assertFalse(responseIds.contains(id));
responseIds.add(id);
}
responseIdSets.add(theseIds);
}
Assert.assertTrue(responseIds.containsAll(Arrays.asList(requestIds)));
Assert.assertEquals(responseIds.size(), requestIds.length);
}
use of com.linkedin.common.callback.Callback in project rest.li by linkedin.
the class TestRestLiMethodInvocation method testAsyncBatchDelete.
@Test
public void testAsyncBatchDelete() throws Exception {
ResourceModel statusResourceModel = buildResourceModel(AsyncStatusCollectionResource.class);
RestLiCallback<?> callback = getCallback();
ResourceMethodDescriptor methodDescriptor;
AsyncStatusCollectionResource statusResource;
methodDescriptor = statusResourceModel.findMethod(ResourceMethod.BATCH_DELETE);
statusResource = getMockResource(AsyncStatusCollectionResource.class);
@SuppressWarnings("unchecked") BatchDeleteRequest<Long, Status> mockBatchDeleteReq = (BatchDeleteRequest<Long, Status>) EasyMock.anyObject();
statusResource.batchDelete(mockBatchDeleteReq, EasyMock.<Callback<BatchUpdateResult<Long, Status>>>anyObject());
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
@SuppressWarnings("unchecked") Callback<BatchCreateResult<Long, Status>> callback = (Callback<BatchCreateResult<Long, Status>>) EasyMock.getCurrentArguments()[1];
callback.onSuccess(null);
return null;
}
});
EasyMock.replay(statusResource);
checkAsyncInvocation(statusResource, callback, methodDescriptor, "DELETE", version, "/asyncstatuses?ids=List(1,2,3)", buildBatchPathKeys(1L, 2L, 3L));
}
use of com.linkedin.common.callback.Callback in project rest.li by linkedin.
the class TestRestLiMethodInvocation method testAsyncPut.
@SuppressWarnings("unchecked")
@Test
public void testAsyncPut() throws Exception {
Map<String, ResourceModel> resourceModelMap = buildResourceModels(AsyncStatusCollectionResource.class, AsyncLocationResource.class, AsyncDiscoveredItemsResource.class);
ResourceModel statusResourceModel = resourceModelMap.get("/asyncstatuses");
ResourceModel locationResourceModel = statusResourceModel.getSubResource("asynclocation");
ResourceModel followsAssociationResourceModel = buildResourceModel(AsyncFollowsAssociativeResource.class);
ResourceModel discoveredItemsResourceModel = resourceModelMap.get("/asyncdiscovereditems");
RestLiCallback<?> callback = getCallback();
ResourceMethodDescriptor methodDescriptor;
AsyncStatusCollectionResource statusResource;
AsyncFollowsAssociativeResource followsResource;
AsyncLocationResource locationResource;
AsyncDiscoveredItemsResource discoveredItemsResource;
// #1 Update on collection resource
methodDescriptor = statusResourceModel.findMethod(ResourceMethod.UPDATE);
statusResource = getMockResource(AsyncStatusCollectionResource.class);
long id = eq(1L);
Status status = (Status) EasyMock.anyObject();
statusResource.update(id, status, EasyMock.<Callback<UpdateResponse>>anyObject());
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
@SuppressWarnings("unchecked") Callback<UpdateResponse> callback = (Callback<UpdateResponse>) EasyMock.getCurrentArguments()[2];
callback.onSuccess(null);
return null;
}
});
EasyMock.replay(statusResource);
checkAsyncInvocation(statusResource, callback, methodDescriptor, "PUT", version, "/asyncstatuses/1", "{}", buildPathKeys("statusID", 1L));
// #2 Update on association resource
methodDescriptor = followsAssociationResourceModel.findMethod(ResourceMethod.UPDATE);
followsResource = getMockResource(AsyncFollowsAssociativeResource.class);
CompoundKey rawKey = new CompoundKey();
rawKey.append("followerID", 1L);
rawKey.append("followeeID", 2L);
CompoundKey key = eq(rawKey);
Followed followed = (Followed) EasyMock.anyObject();
followsResource.update(key, followed, (Callback<UpdateResponse>) EasyMock.anyObject());
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
Callback<UpdateResponse> callback = (Callback<UpdateResponse>) EasyMock.getCurrentArguments()[2];
callback.onSuccess(null);
return null;
}
});
EasyMock.replay(followsResource);
checkAsyncInvocation(followsResource, callback, methodDescriptor, "PUT", version, "/asyncfollows/(followerID:1,followeeID:2)", "{}", buildPathKeys("followerID", 1L, "followeeID", 2L, followsAssociationResourceModel.getKeyName(), rawKey));
// #3 Update on simple resource
methodDescriptor = locationResourceModel.findMethod(ResourceMethod.UPDATE);
locationResource = getMockResource(AsyncLocationResource.class);
Location location = (Location) EasyMock.anyObject();
locationResource.update(location, EasyMock.<Callback<UpdateResponse>>anyObject());
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
@SuppressWarnings("unchecked") Callback<UpdateResponse> callback = (Callback<UpdateResponse>) EasyMock.getCurrentArguments()[1];
callback.onSuccess(null);
return null;
}
});
EasyMock.replay(locationResource);
checkAsyncInvocation(locationResource, callback, methodDescriptor, "PUT", version, "/asyncstatuses/1/asynclocation", "{}", buildPathKeys("statusID", 1L));
// #4 Update on complex-key resource
methodDescriptor = discoveredItemsResourceModel.findMethod(ResourceMethod.UPDATE);
discoveredItemsResource = getMockResource(AsyncDiscoveredItemsResource.class);
ComplexResourceKey<DiscoveredItemKey, DiscoveredItemKeyParams> complexKey = getDiscoveredItemComplexKey(1L, 2, 3L);
discoveredItemsResource.update(eq(complexKey), (DiscoveredItem) EasyMock.anyObject(), EasyMock.<Callback<UpdateResponse>>anyObject());
EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
@Override
public Object answer() throws Throwable {
@SuppressWarnings("unchecked") Callback<UpdateResponse> callback = (Callback<UpdateResponse>) EasyMock.getCurrentArguments()[2];
callback.onSuccess(null);
return null;
}
});
EasyMock.replay(discoveredItemsResource);
checkAsyncInvocation(discoveredItemsResource, callback, methodDescriptor, "PUT", version, "/asyncdiscovereditems/(itemId:1,type:2,userId:3)", "{}", buildPathKeys("asyncDiscoveredItemId", complexKey));
}
use of com.linkedin.common.callback.Callback 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());
}
Aggregations