Search in sources :

Example 6 with Response

use of com.linkedin.restli.client.Response in project rest.li by linkedin.

the class MockFailedResponseFutureBuilder method buildWithEntity.

private ResponseFuture<V> buildWithEntity() {
    int status = getStatus();
    byte[] entity = mapToBytes(getEntity().data());
    Response<V> decodedResponse = new MockResponseBuilder<K, V>().setEntity(getEntity()).setStatus(status).setHeaders(getHeaders()).setCookies(getCookies()).setProtocolVersion(getProtocolVersion()).build();
    RestResponse restResponse = new RestResponseBuilder().setEntity(entity).setStatus(status).setHeaders(decodedResponse.getHeaders()).setCookies(CookieUtil.encodeCookies(decodedResponse.getCookies())).build();
    RestLiResponseException restLiResponseException = new RestLiResponseException(restResponse, decodedResponse, new ErrorResponse());
    ExecutionException executionException = new ExecutionException(restLiResponseException);
    Future<Response<V>> responseFuture = buildFuture(null, executionException);
    return new ResponseFutureImpl<V>(responseFuture, _errorHandlingBehavior);
}
Also used : RestResponse(com.linkedin.r2.message.rest.RestResponse) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) ErrorResponse(com.linkedin.restli.common.ErrorResponse) RestResponse(com.linkedin.r2.message.rest.RestResponse) Response(com.linkedin.restli.client.Response) ErrorResponse(com.linkedin.restli.common.ErrorResponse) RestLiResponseException(com.linkedin.restli.client.RestLiResponseException) ExecutionException(java.util.concurrent.ExecutionException) ResponseFutureImpl(com.linkedin.restli.internal.client.ResponseFutureImpl)

Example 7 with Response

use of com.linkedin.restli.client.Response in project rest.li by linkedin.

the class RestLiExampleBasicClient method getAlbum.

/**
   * Retrieve the album information and each photo in the album. The photos are retrieved in parallel.
   */
private void getAlbum(PrintWriter respWriter, long albumId) throws RemoteInvocationException {
    // get the specific album
    final Request<Album> getAlbumReq = _albumBuilders.get().id(albumId).build();
    final ResponseFuture<Album> getAlbumFuture = _restClient.sendRequest(getAlbumReq);
    final Response<Album> getResp = getAlbumFuture.getResponse();
    final Album album = getResp.getEntity();
    respWriter.println(album.getTitle());
    respWriter.println("Created on " + new Date(album.getCreationTime()));
    // get the album's entries
    final FindRequest<AlbumEntry> searchReq = _albumEntryBuilders.findBySearch().albumIdParam(albumId).build();
    final ResponseFuture<CollectionResponse<AlbumEntry>> responseFuture = _restClient.sendRequest(searchReq);
    final Response<CollectionResponse<AlbumEntry>> response = responseFuture.getResponse();
    final List<AlbumEntry> entries = new ArrayList<AlbumEntry>(response.getEntity().getElements());
    entries.add(new AlbumEntry().setAlbumId(-1).setPhotoId(9999));
    // don't return until all photo requests done
    final CountDownLatch latch = new CountDownLatch(entries.size());
    // fetch every photo asynchronously
    // store either a photo or an exception
    final Object[] photos = new Object[entries.size()];
    for (int i = 0; i < entries.size(); i++) {
        // need final version for callback
        final int finalI = i;
        final AlbumEntry entry = entries.get(i);
        final long photoId = entry.getPhotoId();
        final Request<Photo> getPhotoReq = _photoBuilders.get().id(photoId).build();
        _restClient.sendRequest(getPhotoReq, new Callback<Response<Photo>>() {

            @Override
            public void onSuccess(Response<Photo> result) {
                photos[finalI] = result.getEntity();
                latch.countDown();
            }

            @Override
            public void onError(Throwable e) {
                photos[finalI] = e;
            }
        });
    }
    try {
        // wait for all requests to finish
        latch.await(2, TimeUnit.SECONDS);
        if (latch.getCount() > 0) {
            respWriter.println("Failed to retrieve some photo(s)");
        }
    } catch (InterruptedException e) {
        e.printStackTrace(respWriter);
    }
    // print photo data
    for (int i = 0; i < entries.size(); i++) {
        final Object val = photos[i];
        final AlbumEntry entry = entries.get(i);
        if (val instanceof Throwable) {
            respWriter.println("Failed to load photo " + entry.getPhotoId());
            respWriter.println("Stack trace:");
            ((Throwable) val).printStackTrace(respWriter);
            respWriter.println();
        } else if (val instanceof Photo) {
            final Photo photo = (Photo) val;
            respWriter.println("Photo " + photo.getTitle() + ":");
            respWriter.println(photo);
            respWriter.println("Added on " + new Date(entry.getAddTime()));
        } else {
            throw new AssertionError("expected photo or exception");
        }
    }
}
Also used : ArrayList(java.util.ArrayList) CollectionResponse(com.linkedin.restli.common.CollectionResponse) CountDownLatch(java.util.concurrent.CountDownLatch) Date(java.util.Date) CollectionResponse(com.linkedin.restli.common.CollectionResponse) IdResponse(com.linkedin.restli.common.IdResponse) Response(com.linkedin.restli.client.Response)

Example 8 with Response

use of com.linkedin.restli.client.Response 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 9 with Response

use of com.linkedin.restli.client.Response in project rest.li by linkedin.

the class TestMultiplexerIntegration method singleCallWithError.

@Test
public void singleCallWithError() throws Exception {
    GetRequest<Greeting> request = new GreetingsCallbackBuilders().get().id(Long.MAX_VALUE).build();
    FutureCallback<Response<Greeting>> muxCallback = new FutureCallback<Response<Greeting>>();
    FutureCallback<Response<Greeting>> directCallback = new FutureCallback<Response<Greeting>>();
    MultiplexedRequest multiplexedRequest = MultiplexedRequestBuilder.createParallelRequest().addRequest(request, muxCallback).build();
    getClient().sendRequest(multiplexedRequest);
    getClient().sendRequest(request, directCallback);
    assertEqualErrors(muxCallback, directCallback);
}
Also used : Response(com.linkedin.restli.client.Response) Greeting(com.linkedin.restli.examples.greetings.api.Greeting) FutureCallback(com.linkedin.common.callback.FutureCallback) GreetingsCallbackBuilders(com.linkedin.restli.examples.greetings.client.GreetingsCallbackBuilders) RestLiIntegrationTest(com.linkedin.restli.examples.RestLiIntegrationTest) Test(org.testng.annotations.Test)

Example 10 with Response

use of com.linkedin.restli.client.Response in project rest.li by linkedin.

the class TestMultiplexerIntegration method twoParallelCallsWithOneError.

@Test
public void twoParallelCallsWithOneError() throws Exception {
    GetRequest<Greeting> request1 = new GreetingsCallbackBuilders().get().id(1L).build();
    FutureCallback<Response<Greeting>> muxCallback1 = new FutureCallback<Response<Greeting>>();
    FutureCallback<Response<Greeting>> directCallback1 = new FutureCallback<Response<Greeting>>();
    GetRequest<Greeting> request2 = new GreetingsCallbackBuilders().get().id(Long.MAX_VALUE).build();
    FutureCallback<Response<Greeting>> muxCallback2 = new FutureCallback<Response<Greeting>>();
    FutureCallback<Response<Greeting>> directCallback2 = new FutureCallback<Response<Greeting>>();
    MultiplexedRequest multiplexedRequest = MultiplexedRequestBuilder.createParallelRequest().addRequest(request1, muxCallback1).addRequest(request2, muxCallback2).build();
    getClient().sendRequest(multiplexedRequest);
    getClient().sendRequest(request1, directCallback1);
    getClient().sendRequest(request2, directCallback2);
    assertEqualResponses(muxCallback1, directCallback1);
    assertEqualErrors(muxCallback2, directCallback2);
}
Also used : Response(com.linkedin.restli.client.Response) Greeting(com.linkedin.restli.examples.greetings.api.Greeting) FutureCallback(com.linkedin.common.callback.FutureCallback) GreetingsCallbackBuilders(com.linkedin.restli.examples.greetings.client.GreetingsCallbackBuilders) RestLiIntegrationTest(com.linkedin.restli.examples.RestLiIntegrationTest) Test(org.testng.annotations.Test)

Aggregations

Response (com.linkedin.restli.client.Response)11 Greeting (com.linkedin.restli.examples.greetings.api.Greeting)8 Test (org.testng.annotations.Test)8 FutureCallback (com.linkedin.common.callback.FutureCallback)6 RestLiIntegrationTest (com.linkedin.restli.examples.RestLiIntegrationTest)6 GreetingsCallbackBuilders (com.linkedin.restli.examples.greetings.client.GreetingsCallbackBuilders)6 CountDownLatch (java.util.concurrent.CountDownLatch)3 RestResponse (com.linkedin.r2.message.rest.RestResponse)2 RestLiResponseException (com.linkedin.restli.client.RestLiResponseException)2 CollectionResponse (com.linkedin.restli.common.CollectionResponse)2 ErrorResponse (com.linkedin.restli.common.ErrorResponse)2 IdResponse (com.linkedin.restli.common.IdResponse)2 ResponseFutureImpl (com.linkedin.restli.internal.client.ResponseFutureImpl)2 ArrayList (java.util.ArrayList)2 ExecutionException (java.util.concurrent.ExecutionException)2 Callback (com.linkedin.common.callback.Callback)1 HostSet (com.linkedin.d2.balancer.util.HostSet)1 ConsistentHashKeyMapper (com.linkedin.d2.balancer.util.hashing.ConsistentHashKeyMapper)1 ConsistentHashKeyMapperTest (com.linkedin.d2.balancer.util.hashing.ConsistentHashKeyMapperTest)1 FieldDef (com.linkedin.data.template.FieldDef)1