Search in sources :

Example 61 with Callback

use of com.linkedin.common.callback.Callback in project rest.li by linkedin.

the class TestAllPartitionsRequestBuilder method testSendAllPartitionsRequests.

@Test(dataProvider = com.linkedin.restli.internal.common.TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "restliRequestOptions")
public void testSendAllPartitionsRequests(RestliRequestOptions options, RingFactory<URI> ringFactory) throws ServiceUnavailableException, URISyntaxException, RestException, InterruptedException {
    final int PARTITION_NUM = 5;
    List<URI> expectedUris = new ArrayList<URI>();
    ConsistentHashKeyMapper mapper = getKeyToHostMapper(PARTITION_NUM, expectedUris, ringFactory);
    AllPartitionsRequestBuilder<Greeting> searchRB = new AllPartitionsRequestBuilder<Greeting>(mapper);
    ActionRequestBuilder<Long, Greeting> builder = new ActionRequestBuilder<Long, Greeting>(TEST_URI, Greeting.class, _COLL_SPEC, options);
    ActionRequest<Greeting> request = builder.name("updateTone").id(1L).setParam(new FieldDef<Tone>("newTone", Tone.class, DataTemplateUtil.getSchema(Tone.class)), Tone.FRIENDLY).build();
    final Map<String, Greeting> results = new ConcurrentHashMap<String, Greeting>();
    final CountDownLatch latch = new CountDownLatch(PARTITION_NUM);
    final List<Throwable> errors = new ArrayList<Throwable>();
    final List<Greeting> responses = new ArrayList<Greeting>();
    Callback<Response<Greeting>> cb = new Callback<Response<Greeting>>() {

        @Override
        public void onError(Throwable e) {
            synchronized (errors) {
                errors.add(e);
            }
            latch.countDown();
        }

        @Override
        public void onSuccess(Response<Greeting> response) {
            results.put(response.getEntity().toString(), response.getEntity());
            synchronized (responses) {
                responses.add(response.getEntity());
            }
            latch.countDown();
        }
    };
    HostSet hostsResult = searchRB.sendRequests(getClient(), request, new RequestContext(), cb);
    List<URI> uris = hostsResult.getAllHosts();
    Assert.assertTrue(uris.containsAll(expectedUris));
    Assert.assertTrue(expectedUris.containsAll(uris));
    latch.await();
    if (!errors.isEmpty()) {
        Assert.fail("I knew it: " + errors.toString());
    }
    Assert.assertEquals(PARTITION_NUM, responses.size());
}
Also used : Greeting(com.linkedin.restli.examples.greetings.api.Greeting) ArrayList(java.util.ArrayList) URI(java.net.URI) HostSet(com.linkedin.d2.balancer.util.HostSet) AllPartitionsRequestBuilder(com.linkedin.restli.client.AllPartitionsRequestBuilder) RequestContext(com.linkedin.r2.message.RequestContext) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CountDownLatch(java.util.concurrent.CountDownLatch) Response(com.linkedin.restli.client.Response) FieldDef(com.linkedin.data.template.FieldDef) ActionRequestBuilder(com.linkedin.restli.client.ActionRequestBuilder) Callback(com.linkedin.common.callback.Callback) Tone(com.linkedin.restli.examples.greetings.api.Tone) ConsistentHashKeyMapper(com.linkedin.d2.balancer.util.hashing.ConsistentHashKeyMapper) ConsistentHashKeyMapperTest(com.linkedin.d2.balancer.util.hashing.ConsistentHashKeyMapperTest) Test(org.testng.annotations.Test)

Example 62 with Callback

use of com.linkedin.common.callback.Callback in project rest.li by linkedin.

the class TestScatterGather method testSendSGKVRequests.

private static void testSendSGKVRequests(Collection<ScatterGatherBuilder.KVRequestInfo<Long, UpdateStatus>> scatterGatherRequests, Long[] requestIds) throws InterruptedException {
    final Map<Long, UpdateStatus> results = new ConcurrentHashMap<Long, UpdateStatus>();
    final CountDownLatch latch = new CountDownLatch(scatterGatherRequests.size());
    final List<Throwable> errors = new ArrayList<Throwable>();
    final List<BatchKVResponse<Long, UpdateStatus>> responses = new ArrayList<BatchKVResponse<Long, UpdateStatus>>();
    for (ScatterGatherBuilder.KVRequestInfo<Long, UpdateStatus> requestInfo : scatterGatherRequests) {
        Callback<Response<BatchKVResponse<Long, UpdateStatus>>> cb = new Callback<Response<BatchKVResponse<Long, UpdateStatus>>>() {

            @Override
            public void onSuccess(Response<BatchKVResponse<Long, UpdateStatus>> 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();
            }
        };
        BatchRequest<BatchKVResponse<Long, UpdateStatus>> request = requestInfo.getRequest();
        RequestContext requestContext = requestInfo.getRequestContext();
        REST_CLIENT.sendRequest(request, requestContext, 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, UpdateStatus> 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);
}
Also used : UpdateStatus(com.linkedin.restli.common.UpdateStatus) Set(java.util.Set) HashSet(java.util.HashSet) ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) BatchKVResponse(com.linkedin.restli.client.response.BatchKVResponse) EntityResponse(com.linkedin.restli.common.EntityResponse) BatchCreateIdResponse(com.linkedin.restli.common.BatchCreateIdResponse) BatchResponse(com.linkedin.restli.common.BatchResponse) BatchKVResponse(com.linkedin.restli.client.response.BatchKVResponse) Callback(com.linkedin.common.callback.Callback) RequestContext(com.linkedin.r2.message.RequestContext) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashSet(java.util.HashSet)

Example 63 with Callback

use of com.linkedin.common.callback.Callback in project rest.li by linkedin.

the class TestScatterGather method testSendGetSGRequests.

private static void testSendGetSGRequests(ScatterGatherBuilder<Greeting> sg, Long[] requestIds) throws ServiceUnavailableException, InterruptedException {
    Collection<ScatterGatherBuilder.RequestInfo<Greeting>> scatterGatherRequests = buildScatterGatherGetRequests(sg, requestIds);
    final Map<String, Greeting> results = new ConcurrentHashMap<String, Greeting>();
    final CountDownLatch latch = new CountDownLatch(scatterGatherRequests.size());
    final List<Throwable> errors = new ArrayList<Throwable>();
    final List<BatchResponse<Greeting>> responses = new ArrayList<BatchResponse<Greeting>>();
    for (ScatterGatherBuilder.RequestInfo<Greeting> requestInfo : scatterGatherRequests) {
        Callback<Response<BatchResponse<Greeting>>> cb = new Callback<Response<BatchResponse<Greeting>>>() {

            @Override
            public void onSuccess(Response<BatchResponse<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<String>> responseIdSets = new HashSet<Set<String>>();
    Set<Long> responseIds = new HashSet<Long>();
    for (BatchResponse<Greeting> response : responses) {
        Set<String> theseIds = response.getResults().keySet();
        //no duplicate requests
        Assert.assertFalse(responseIdSets.contains(theseIds));
        for (String id : theseIds) {
            //no duplicate ids
            Assert.assertFalse(responseIds.contains(Long.parseLong(id)));
            responseIds.add(Long.parseLong(id));
        }
        responseIdSets.add(theseIds);
    }
    Assert.assertTrue(responseIds.containsAll(Arrays.asList(requestIds)));
    Assert.assertEquals(responseIds.size(), requestIds.length);
}
Also used : Greeting(com.linkedin.restli.examples.greetings.api.Greeting) Set(java.util.Set) HashSet(java.util.HashSet) BatchResponse(com.linkedin.restli.common.BatchResponse) ArrayList(java.util.ArrayList) CountDownLatch(java.util.concurrent.CountDownLatch) EntityResponse(com.linkedin.restli.common.EntityResponse) BatchCreateIdResponse(com.linkedin.restli.common.BatchCreateIdResponse) BatchResponse(com.linkedin.restli.common.BatchResponse) BatchKVResponse(com.linkedin.restli.client.response.BatchKVResponse) Callback(com.linkedin.common.callback.Callback) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashSet(java.util.HashSet)

Example 64 with Callback

use of com.linkedin.common.callback.Callback in project rest.li by linkedin.

the class TestRestLiMethodInvocation method testAsyncGetAllComplexKeyResource.

@Test
public void testAsyncGetAllComplexKeyResource() throws Exception {
    ResourceModel discoveredResourceModel = buildResourceModel(AsyncDiscoveredItemsResource.class);
    RestLiCallback<?> callback = getCallback();
    ResourceMethodDescriptor methodDescriptor;
    AsyncDiscoveredItemsResource discoveredResource;
    methodDescriptor = discoveredResourceModel.findMethod(ResourceMethod.GET_ALL);
    discoveredResource = getMockResource(AsyncDiscoveredItemsResource.class);
    @SuppressWarnings("unchecked") PagingContext mockCtx = (PagingContext) EasyMock.anyObject();
    discoveredResource.getAll(mockCtx, EasyMock.<Callback<List<DiscoveredItem>>>anyObject());
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {

        @Override
        public Object answer() throws Throwable {
            @SuppressWarnings("unchecked") Callback<List<DiscoveredItem>> callback = (Callback<List<DiscoveredItem>>) EasyMock.getCurrentArguments()[1];
            callback.onSuccess(null);
            return null;
        }
    });
    EasyMock.replay(discoveredResource);
    checkAsyncInvocation(discoveredResource, callback, methodDescriptor, "GET", version, "/asyncdiscovereditems", buildBatchPathKeys());
}
Also used : AsyncDiscoveredItemsResource(com.linkedin.restli.server.twitter.AsyncDiscoveredItemsResource) ResourceMethodDescriptor(com.linkedin.restli.internal.server.model.ResourceMethodDescriptor) 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) PagingContext(com.linkedin.restli.server.PagingContext) DiscoveredItem(com.linkedin.restli.server.twitter.TwitterTestDataModels.DiscoveredItem) ResourceModel(com.linkedin.restli.internal.server.model.ResourceModel) RestLiTestHelper.buildResourceModel(com.linkedin.restli.server.test.RestLiTestHelper.buildResourceModel) List(java.util.List) EasyMock.anyObject(org.easymock.EasyMock.anyObject) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest)

Example 65 with Callback

use of com.linkedin.common.callback.Callback in project rest.li by linkedin.

the class TestRestLiMethodInvocation method testAsyncGetAssociativeResource.

@Test
public void testAsyncGetAssociativeResource() throws Exception {
    ResourceModel followsResourceModel = buildResourceModel(AsyncFollowsAssociativeResource.class);
    RestLiCallback<?> callback = getCallback();
    ResourceMethodDescriptor methodDescriptor;
    AsyncFollowsAssociativeResource resource;
    // #1: get
    methodDescriptor = followsResourceModel.findMethod(ResourceMethod.GET);
    resource = getMockResource(AsyncFollowsAssociativeResource.class);
    CompoundKey rawKey = new CompoundKey();
    rawKey.append("followerID", 1L);
    rawKey.append("followeeID", 2L);
    CompoundKey key = eq(rawKey);
    resource.get(key, EasyMock.<Callback<Followed>>anyObject());
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {

        @Override
        public Object answer() throws Throwable {
            @SuppressWarnings("unchecked") Callback<Followed> callback = (Callback<Followed>) EasyMock.getCurrentArguments()[1];
            callback.onSuccess(null);
            return null;
        }
    });
    EasyMock.replay(resource);
    checkAsyncInvocation(resource, callback, methodDescriptor, "GET", version, "/asyncfollows/(followerID:1,followeeID:2)", buildPathKeys("followerID", 1L, "followeeID", 2L, followsResourceModel.getKeyName(), rawKey));
}
Also used : 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) CompoundKey(com.linkedin.restli.common.CompoundKey) ResourceMethodDescriptor(com.linkedin.restli.internal.server.model.ResourceMethodDescriptor) Followed(com.linkedin.restli.server.twitter.TwitterTestDataModels.Followed) ResourceModel(com.linkedin.restli.internal.server.model.ResourceModel) RestLiTestHelper.buildResourceModel(com.linkedin.restli.server.test.RestLiTestHelper.buildResourceModel) EasyMock.anyObject(org.easymock.EasyMock.anyObject) AsyncFollowsAssociativeResource(com.linkedin.restli.server.twitter.AsyncFollowsAssociativeResource) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest)

Aggregations

Callback (com.linkedin.common.callback.Callback)95 Test (org.testng.annotations.Test)64 AfterTest (org.testng.annotations.AfterTest)43 BeforeTest (org.testng.annotations.BeforeTest)43 RequestContext (com.linkedin.r2.message.RequestContext)37 RestResponse (com.linkedin.r2.message.rest.RestResponse)34 ByteString (com.linkedin.data.ByteString)29 RestRequest (com.linkedin.r2.message.rest.RestRequest)28 StreamResponse (com.linkedin.r2.message.stream.StreamResponse)28 AsyncStatusCollectionResource (com.linkedin.restli.server.twitter.AsyncStatusCollectionResource)28 URI (java.net.URI)28 RestLiCallback (com.linkedin.restli.internal.server.RestLiCallback)26 FilterChainCallback (com.linkedin.restli.internal.server.filter.FilterChainCallback)26 ResourceMethodDescriptor (com.linkedin.restli.internal.server.model.ResourceMethodDescriptor)26 ResourceModel (com.linkedin.restli.internal.server.model.ResourceModel)26 RequestExecutionCallback (com.linkedin.restli.server.RequestExecutionCallback)26 RestLiTestHelper.buildResourceModel (com.linkedin.restli.server.test.RestLiTestHelper.buildResourceModel)26 EasyMock.anyObject (org.easymock.EasyMock.anyObject)26 StreamRequest (com.linkedin.r2.message.stream.StreamRequest)25 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)22