Search in sources :

Example 26 with RemoteInvocationException

use of com.linkedin.r2.RemoteInvocationException in project rest.li by linkedin.

the class RestLiExampleBasicClient method sendRequest.

public void sendRequest(String pathInfo, PrintWriter respWriter) {
    /* Supported URLs
     *  /fail: just fail
     *  /album/<album_id>: display album
     *  all others: make photos, get photos, purge photos
     */
    try {
        if (pathInfo.equals("/fail")) {
            getNonPhoto();
        } else {
            if (pathInfo.startsWith("/album/")) {
                getAlbum(respWriter, Long.parseLong(pathInfo.substring("/album/".length())));
            } else {
                // this track does not make any assumption on server
                // we need to create photo first, find it and clean them up
                // we use both sync and async approaches for creating
                final long newPhotoId = createPhoto(respWriter);
                final CountDownLatch latch = new CountDownLatch(1);
                createPhotoAsync(respWriter, latch, newPhotoId);
                getPhoto(respWriter, newPhotoId);
                findPhoto(respWriter);
                partialUpdatePhoto(respWriter, newPhotoId);
                // photos and albums have IDs starting from 1
                getAlbumSummary(respWriter, (long) new Random().nextInt(10) + 1);
                purgeAllPhotos(respWriter);
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    respWriter.println(e.getMessage());
                }
            }
        }
    } catch (RemoteInvocationException e) {
        respWriter.println("Error in example client: " + e.getMessage());
    }
    respWriter.flush();
}
Also used : Random(java.util.Random) RemoteInvocationException(com.linkedin.r2.RemoteInvocationException) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 27 with RemoteInvocationException

use of com.linkedin.r2.RemoteInvocationException in project rest.li by linkedin.

the class TestMockHttpServerFactory method testCreateUsingClassNames.

@Test
public void testCreateUsingClassNames() throws IOException, RemoteInvocationException {
    Set<Class<?>> resourceClasses = new HashSet<>();
    resourceClasses.add(PhotoResource.class);
    resourceClasses.add(AlbumResource.class);
    Map<String, Object> beans = getBeans();
    boolean[] enableAsyncOptions = { true, false };
    for (boolean enableAsync : enableAsyncOptions) {
        HttpServer server = MockHttpServerFactory.create(PORT, resourceClasses, beans, enableAsync);
        runTest(server);
    }
}
Also used : HttpServer(com.linkedin.r2.transport.http.server.HttpServer) HashSet(java.util.HashSet) Test(org.testng.annotations.Test)

Example 28 with RemoteInvocationException

use of com.linkedin.r2.RemoteInvocationException in project rest.li by linkedin.

the class AbstractEchoServiceTest method testOnExceptionEchoService.

@Test
public void testOnExceptionEchoService() throws Exception {
    final EchoService client = getEchoClient(_client, Bootstrap.getOnExceptionEchoURI());
    final String msg = "This is a simple echo message";
    final FutureCallback<String> callback = new FutureCallback<String>();
    client.echo(msg, callback);
    try {
        callback.get();
        Assert.fail("Should have thrown an exception");
    } catch (ExecutionException e) {
        Assert.assertTrue(e.getCause() instanceof RemoteInvocationException);
    }
}
Also used : EchoService(com.linkedin.r2.sample.echo.EchoService) RemoteInvocationException(com.linkedin.r2.RemoteInvocationException) ExecutionException(java.util.concurrent.ExecutionException) FutureCallback(com.linkedin.common.callback.FutureCallback) Test(org.testng.annotations.Test)

Example 29 with RemoteInvocationException

use of com.linkedin.r2.RemoteInvocationException in project rest.li by linkedin.

the class RestClientTest method testRestLiResponseFuture.

@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "sendRequestAndGetResponseOptions")
public void testRestLiResponseFuture(SendRequestOption sendRequestOption, GetResponseOption getResponseOption, TimeoutOption timeoutOption, ProtocolVersionOption versionOption, ProtocolVersion protocolVersion, String errorResponseHeaderName) throws ExecutionException, RemoteInvocationException, TimeoutException, InterruptedException, IOException {
    final String ERR_KEY = "someErr";
    final String ERR_VALUE = "WHOOPS!";
    final String ERR_MSG = "whoops2";
    final int HTTP_CODE = 200;
    final int APP_CODE = 666;
    RestClient client = mockClient(ERR_KEY, ERR_VALUE, ERR_MSG, HTTP_CODE, APP_CODE, protocolVersion, errorResponseHeaderName);
    Request<ErrorResponse> request = mockRequest(ErrorResponse.class, versionOption);
    RequestBuilder<Request<ErrorResponse>> requestBuilder = mockRequestBuilder(request);
    ResponseFuture<ErrorResponse> future = sendRequest(sendRequestOption, determineErrorHandlingBehavior(getResponseOption), client, request, requestBuilder);
    Response<ErrorResponse> response = getOkResponse(getResponseOption, future, timeoutOption);
    ErrorResponse e = response.getEntity();
    Assert.assertNull(response.getError());
    Assert.assertFalse(response.hasError());
    Assert.assertEquals(HTTP_CODE, response.getStatus());
    Assert.assertEquals(ERR_VALUE, e.getErrorDetails().data().getString(ERR_KEY));
    Assert.assertEquals(APP_CODE, e.getServiceErrorCode().intValue());
    Assert.assertEquals(ERR_MSG, e.getMessage());
}
Also used : RestRequest(com.linkedin.r2.message.rest.RestRequest) ErrorResponse(com.linkedin.restli.common.ErrorResponse) Test(org.testng.annotations.Test)

Example 30 with RemoteInvocationException

use of com.linkedin.r2.RemoteInvocationException in project parseq by linkedin.

the class GetRequestGroup method doExecuteBatchGet.

@SuppressWarnings({ "rawtypes", "unchecked" })
private <K, RT extends RecordTemplate> void doExecuteBatchGet(final Client client, final Batch<RestRequestBatchKey, Response<Object>> batch, final Set<Object> ids, final Set<PathSpec> fields, Function<Request<?>, RequestContext> requestContextProvider) {
    final BatchGetEntityRequestBuilder<K, RT> builder = new BatchGetEntityRequestBuilder<>(_baseUriTemplate, _resourceSpec, _requestOptions);
    builder.setHeaders(_headers);
    _queryParams.forEach((key, value) -> builder.setParam(key, value));
    _pathKeys.forEach((key, value) -> builder.pathKey(key, value));
    builder.ids((Set<K>) ids);
    if (fields != null && !fields.isEmpty()) {
        builder.fields(fields.toArray(new PathSpec[fields.size()]));
    }
    final BatchGetEntityRequest<K, RT> batchGet = builder.build();
    client.sendRequest(batchGet, requestContextProvider.apply(batchGet), new Callback<Response<BatchKVResponse<K, EntityResponse<RT>>>>() {

        @Override
        public void onSuccess(Response<BatchKVResponse<K, EntityResponse<RT>>> responseToBatch) {
            final ProtocolVersion version = ProtocolVersionUtil.extractProtocolVersion(responseToBatch.getHeaders());
            batch.entries().stream().forEach(entry -> {
                try {
                    RestRequestBatchKey rrbk = entry.getKey();
                    Request request = rrbk.getRequest();
                    if (request instanceof GetRequest) {
                        successGet((GetRequest) request, responseToBatch, batchGet, entry, version);
                    } else if (request instanceof BatchGetKVRequest) {
                        successBatchGetKV((BatchGetKVRequest) request, responseToBatch, entry, version);
                    } else if (request instanceof BatchGetRequest) {
                        successBatchGet((BatchGetRequest) request, responseToBatch, entry, version);
                    } else if (request instanceof BatchGetEntityRequest) {
                        successBatchGetEntity((BatchGetEntityRequest) request, responseToBatch, entry, version);
                    } else {
                        entry.getValue().getPromise().fail(unsupportedGetRequestType(request));
                    }
                } catch (RemoteInvocationException e) {
                    entry.getValue().getPromise().fail(e);
                }
            });
        }

        @SuppressWarnings({ "deprecation" })
        private void successBatchGetEntity(BatchGetEntityRequest request, Response<BatchKVResponse<K, EntityResponse<RT>>> responseToBatch, Entry<RestRequestBatchKey, BatchEntry<Response<Object>>> entry, final ProtocolVersion version) {
            Set<String> ids = (Set<String>) request.getObjectIds().stream().map(o -> BatchResponse.keyToString(o, version)).collect(Collectors.toSet());
            DataMap dm = filterIdsInBatchResult(responseToBatch.getEntity().data(), ids);
            BatchKVResponse br = new BatchEntityResponse<>(dm, request.getResourceSpec().getKeyType(), request.getResourceSpec().getValueType(), request.getResourceSpec().getKeyParts(), request.getResourceSpec().getComplexKeyType(), version);
            Response rsp = new ResponseImpl(responseToBatch, br);
            entry.getValue().getPromise().done(rsp);
        }

        private void successBatchGet(BatchGetRequest request, Response<BatchKVResponse<K, EntityResponse<RT>>> responseToBatch, Entry<RestRequestBatchKey, BatchEntry<Response<Object>>> entry, final ProtocolVersion version) {
            Set<String> ids = (Set<String>) request.getObjectIds().stream().map(o -> BatchResponse.keyToString(o, version)).collect(Collectors.toSet());
            DataMap dm = filterIdsInBatchResult(responseToBatch.getEntity().data(), ids);
            BatchResponse br = new BatchResponse<>(dm, request.getResponseDecoder().getEntityClass());
            Response rsp = new ResponseImpl(responseToBatch, br);
            entry.getValue().getPromise().done(rsp);
        }

        @SuppressWarnings({ "deprecation" })
        private void successBatchGetKV(BatchGetKVRequest request, Response<BatchKVResponse<K, EntityResponse<RT>>> responseToBatch, Entry<RestRequestBatchKey, BatchEntry<Response<Object>>> entry, final ProtocolVersion version) {
            Set<String> ids = (Set<String>) request.getObjectIds().stream().map(o -> BatchResponse.keyToString(o, version)).collect(Collectors.toSet());
            DataMap dm = filterIdsInBatchResult(responseToBatch.getEntity().data(), ids);
            BatchKVResponse br = new BatchKVResponse(dm, request.getResourceSpec().getKeyType(), request.getResourceSpec().getValueType(), request.getResourceSpec().getKeyParts(), request.getResourceSpec().getComplexKeyType(), version);
            Response rsp = new ResponseImpl(responseToBatch, br);
            entry.getValue().getPromise().done(rsp);
        }

        @SuppressWarnings({ "deprecation" })
        private void successGet(GetRequest request, Response<BatchKVResponse<K, EntityResponse<RT>>> responseToBatch, final BatchGetEntityRequest<K, RT> batchGet, Entry<RestRequestBatchKey, BatchEntry<Response<Object>>> entry, final ProtocolVersion version) throws RemoteInvocationException {
            String idString = BatchResponse.keyToString(request.getObjectId(), version);
            Object id = ResponseUtils.convertKey(idString, request.getResourceSpec().getKeyType(), request.getResourceSpec().getKeyParts(), request.getResourceSpec().getComplexKeyType(), version);
            Response rsp = unbatchResponse(batchGet, responseToBatch, id);
            entry.getValue().getPromise().done(rsp);
        }

        @Override
        public void onError(Throwable e) {
            batch.failAll(e);
        }
    });
}
Also used : ResponseImpl(com.linkedin.restli.internal.client.ResponseImpl) ResourceMethod(com.linkedin.restli.common.ResourceMethod) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) Callback(com.linkedin.common.callback.Callback) Function(java.util.function.Function) BatchEntityResponse(com.linkedin.restli.internal.client.response.BatchEntityResponse) HashSet(java.util.HashSet) DataMap(com.linkedin.data.DataMap) BatchKVResponse(com.linkedin.restli.client.response.BatchKVResponse) RestConstants(com.linkedin.restli.common.RestConstants) Map(java.util.Map) EntityResponse(com.linkedin.restli.common.EntityResponse) PathSpec(com.linkedin.data.schema.PathSpec) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) ProtocolVersionUtil(com.linkedin.restli.internal.common.ProtocolVersionUtil) RecordTemplate(com.linkedin.data.template.RecordTemplate) ProtocolVersion(com.linkedin.restli.common.ProtocolVersion) Logger(org.slf4j.Logger) ResourceSpec(com.linkedin.restli.common.ResourceSpec) BatchEntry(com.linkedin.parseq.batching.BatchImpl.BatchEntry) RemoteInvocationException(com.linkedin.r2.RemoteInvocationException) Set(java.util.Set) Batch(com.linkedin.parseq.batching.Batch) Tuple3(com.linkedin.parseq.function.Tuple3) Tuples(com.linkedin.parseq.function.Tuples) Collectors(java.util.stream.Collectors) RequestContext(com.linkedin.r2.message.RequestContext) ErrorResponse(com.linkedin.restli.common.ErrorResponse) HttpStatus(com.linkedin.restli.common.HttpStatus) Entry(java.util.Map.Entry) ResponseUtils(com.linkedin.restli.internal.common.ResponseUtils) BatchResponse(com.linkedin.restli.common.BatchResponse) HashSet(java.util.HashSet) Set(java.util.Set) BatchResponse(com.linkedin.restli.common.BatchResponse) ProtocolVersion(com.linkedin.restli.common.ProtocolVersion) PathSpec(com.linkedin.data.schema.PathSpec) BatchKVResponse(com.linkedin.restli.client.response.BatchKVResponse) DataMap(com.linkedin.data.DataMap) RemoteInvocationException(com.linkedin.r2.RemoteInvocationException) BatchEntry(com.linkedin.parseq.batching.BatchImpl.BatchEntry) ResponseImpl(com.linkedin.restli.internal.client.ResponseImpl) BatchEntityResponse(com.linkedin.restli.internal.client.response.BatchEntityResponse) BatchKVResponse(com.linkedin.restli.client.response.BatchKVResponse) EntityResponse(com.linkedin.restli.common.EntityResponse) ErrorResponse(com.linkedin.restli.common.ErrorResponse) BatchResponse(com.linkedin.restli.common.BatchResponse) BatchEntityResponse(com.linkedin.restli.internal.client.response.BatchEntityResponse) EntityResponse(com.linkedin.restli.common.EntityResponse)

Aggregations

Test (org.testng.annotations.Test)32 RemoteInvocationException (com.linkedin.r2.RemoteInvocationException)29 RestRequest (com.linkedin.r2.message.rest.RestRequest)13 RequestContext (com.linkedin.r2.message.RequestContext)10 HashMap (java.util.HashMap)10 ErrorResponse (com.linkedin.restli.common.ErrorResponse)8 URI (java.net.URI)8 FutureCallback (com.linkedin.common.callback.FutureCallback)7 EmptyRecord (com.linkedin.restli.common.EmptyRecord)7 Map (java.util.Map)7 ExecutionException (java.util.concurrent.ExecutionException)7 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)6 Greeting (com.linkedin.restli.examples.greetings.api.Greeting)6 Callback (com.linkedin.common.callback.Callback)5 ByteString (com.linkedin.data.ByteString)5 RestException (com.linkedin.r2.message.rest.RestException)5 TransportClient (com.linkedin.r2.transport.common.bridge.client.TransportClient)5 TimeoutException (java.util.concurrent.TimeoutException)5 RestResponse (com.linkedin.r2.message.rest.RestResponse)4 StreamRequest (com.linkedin.r2.message.stream.StreamRequest)4