Search in sources :

Example 61 with RestResponseBuilder

use of com.linkedin.r2.message.rest.RestResponseBuilder in project rest.li by linkedin.

the class TestBackupRequestsClient method createAlwaysBackupClientWithHosts.

private BackupRequestsClient createAlwaysBackupClientWithHosts(List<String> uris, Deque<URI> hostsReceivingRequestList, int responseDelayNano, int backupDelayNano, boolean isD2Async) throws IOException {
    Map<URI, Map<Integer, PartitionData>> partitionDescriptions = new HashMap<>();
    uris.forEach(uri -> partitionDescriptions.put(URI.create(uri), Collections.singletonMap(0, new PartitionData(1))));
    StaticLoadBalancerState LbState = new StaticLoadBalancerState() {

        @Override
        public TrackerClient getClient(String serviceName, URI uri) {
            return new DegraderTrackerClientImpl(uri, partitionDescriptions.get(uri), null, SystemClock.instance(), null) {

                @Override
                public void restRequest(RestRequest request, RequestContext requestContext, Map<String, String> wireAttrs, TransportCallback<RestResponse> callback) {
                    // whenever a trackerClient is used to make request, record down it's hostname
                    hostsReceivingRequestList.add(uri);
                    // delay response to allow backup request to happen
                    _executor.schedule(() -> callback.onResponse(TransportResponseImpl.success(new RestResponseBuilder().build())), responseDelayNano, TimeUnit.NANOSECONDS);
                }

                @Override
                public void streamRequest(StreamRequest request, RequestContext requestContext, Map<String, String> wireAttrs, TransportCallback<StreamResponse> callback) {
                    // whenever a trackerClient is used to make request, record down it's hostname
                    hostsReceivingRequestList.add(uri);
                    if (null != requestContext.getLocalAttr(R2Constants.BACKUP_REQUEST_BUFFERED_BODY)) {
                        callback.onResponse(TransportResponseImpl.success(new StreamResponseBuilder().setHeader(BUFFERED_HEADER, String.valueOf(requestContext.getLocalAttr(R2Constants.BACKUP_REQUEST_BUFFERED_BODY) != null)).build(EntityStreams.emptyStream())));
                        return;
                    }
                    request.getEntityStream().setReader(new DrainReader() {

                        public void onDone() {
                            // delay response to allow backup request to happen
                            _executor.schedule(() -> callback.onResponse(TransportResponseImpl.success(new StreamResponseBuilder().setHeader(BUFFERED_HEADER, String.valueOf(requestContext.getLocalAttr(R2Constants.BACKUP_REQUEST_BUFFERED_BODY) != null)).build(EntityStreams.emptyStream()))), responseDelayNano, TimeUnit.NANOSECONDS);
                        }
                    });
                }
            };
        }
    };
    LbState.TEST_URIS_PARTITIONDESCRIPTIONS.putAll(partitionDescriptions);
    LbState.TEST_SERVICE_BACKUP_REQUEST_PROPERTIES.add(createBackupRequestsConfiguration(5, "get"));
    LbState.refreshDefaultProperties();
    LoadBalancer loadBalancer = new SimpleLoadBalancer(LbState, _executor);
    DynamicClient dynamicClient = new DynamicClient(loadBalancer, null);
    return new BackupRequestsClient(dynamicClient, loadBalancer, _executor, null, 10, TimeUnit.SECONDS, isD2Async) {

        @Override
        Optional<TrackingBackupRequestsStrategy> getStrategyAfterUpdate(final String serviceName, final String operation) {
            // constantly enable backup request after backupDelayNano time.
            BackupRequestsStrategy alwaysBackup = new TestTrackingBackupRequestsStrategy.MockBackupRequestsStrategy(() -> Optional.of((long) backupDelayNano), () -> true);
            return Optional.of(new TrackingBackupRequestsStrategy(alwaysBackup));
        }
    };
}
Also used : TransportCallback(com.linkedin.r2.transport.common.bridge.common.TransportCallback) StreamResponseBuilder(com.linkedin.r2.message.stream.StreamResponseBuilder) SimpleLoadBalancer(com.linkedin.d2.balancer.simple.SimpleLoadBalancer) HashMap(java.util.HashMap) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) SimpleLoadBalancer(com.linkedin.d2.balancer.simple.SimpleLoadBalancer) LoadBalancer(com.linkedin.d2.balancer.LoadBalancer) ByteString(com.linkedin.data.ByteString) TrackingBackupRequestsStrategy(com.linkedin.d2.backuprequests.TrackingBackupRequestsStrategy) TestTrackingBackupRequestsStrategy(com.linkedin.d2.backuprequests.TestTrackingBackupRequestsStrategy) URI(java.net.URI) DrainReader(com.linkedin.r2.message.stream.entitystream.DrainReader) StreamRequest(com.linkedin.r2.message.stream.StreamRequest) RestRequest(com.linkedin.r2.message.rest.RestRequest) BackupRequestsStrategy(com.linkedin.d2.backuprequests.BackupRequestsStrategy) TrackingBackupRequestsStrategy(com.linkedin.d2.backuprequests.TrackingBackupRequestsStrategy) TestTrackingBackupRequestsStrategy(com.linkedin.d2.backuprequests.TestTrackingBackupRequestsStrategy) PartitionData(com.linkedin.d2.balancer.properties.PartitionData) StaticLoadBalancerState(com.linkedin.d2.balancer.StaticLoadBalancerState) RequestContext(com.linkedin.r2.message.RequestContext) Map(java.util.Map) HashMap(java.util.HashMap)

Example 62 with RestResponseBuilder

use of com.linkedin.r2.message.rest.RestResponseBuilder in project rest.li by linkedin.

the class Messages method toRestResponse.

/**
 * Converts a StreamResponse to RestResponse
 * @param streamResponse the stream request to be converted
 * @param callback the callback to be invoked when the rest response is constructed
 * @param addContentLengthHeader whether the rest response should have content-length header
 */
public static void toRestResponse(StreamResponse streamResponse, final Callback<RestResponse> callback, final boolean addContentLengthHeader) {
    final RestResponseBuilder builder = new RestResponseBuilder(streamResponse);
    Callback<ByteString> assemblyCallback = new Callback<ByteString>() {

        @Override
        public void onError(Throwable e) {
            callback.onError(e);
        }

        @Override
        public void onSuccess(ByteString result) {
            if (addContentLengthHeader) {
                builder.setHeader(HttpConstants.CONTENT_LENGTH, String.valueOf(result.length()));
            }
            RestResponse restResponse = builder.setEntity(result).build();
            callback.onSuccess(restResponse);
        }
    };
    streamResponse.getEntityStream().setReader(new FullEntityReader(assemblyCallback));
}
Also used : FullEntityReader(com.linkedin.r2.message.stream.entitystream.FullEntityReader) Callback(com.linkedin.common.callback.Callback) TransportCallback(com.linkedin.r2.transport.common.bridge.common.TransportCallback) ByteString(com.linkedin.data.ByteString) RestResponse(com.linkedin.r2.message.rest.RestResponse) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder)

Example 63 with RestResponseBuilder

use of com.linkedin.r2.message.rest.RestResponseBuilder in project rest.li by linkedin.

the class TestMessages method testToRestTransportCallbackRestException.

@Test
public void testToRestTransportCallbackRestException() {
    TransportCallback<StreamResponse> streamCallback = response -> {
        Assert.assertTrue(response.hasError());
        Assert.assertNotNull(response.getError());
        Assert.assertTrue(response.getError() instanceof StreamException);
        Assert.assertNotNull(response.getWireAttributes());
        Assert.assertEquals(response.getWireAttributes(), WIRE_ATTR);
        Assert.assertEquals(response.getError().getStackTrace().length, 0);
    };
    TransportCallback<RestResponse> restCallback = Messages.toRestTransportCallback(streamCallback);
    RestResponseBuilder builder = new RestResponseBuilder();
    builder.setEntity(DATA);
    RestResponse restResponse = builder.build();
    restCallback.onResponse(TransportResponseImpl.error(new RestException(restResponse, new IllegalStateException()), WIRE_ATTR));
}
Also used : ByteStringWriter(com.linkedin.r2.message.stream.entitystream.ByteStringWriter) Callback(com.linkedin.common.callback.Callback) FullEntityReader(com.linkedin.r2.message.stream.entitystream.FullEntityReader) HashMap(java.util.HashMap) Test(org.testng.annotations.Test) TransportCallback(com.linkedin.r2.transport.common.bridge.common.TransportCallback) Messages(com.linkedin.r2.message.Messages) RestResponse(com.linkedin.r2.message.rest.RestResponse) EntityStreams(com.linkedin.r2.message.stream.entitystream.EntityStreams) TransportResponseImpl(com.linkedin.r2.transport.common.bridge.common.TransportResponseImpl) Assert(org.testng.Assert) StreamResponseBuilder(com.linkedin.r2.message.stream.StreamResponseBuilder) ByteString(com.linkedin.data.ByteString) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) Map(java.util.Map) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) StreamException(com.linkedin.r2.message.stream.StreamException) RestException(com.linkedin.r2.message.rest.RestException) RestResponse(com.linkedin.r2.message.rest.RestResponse) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) RestException(com.linkedin.r2.message.rest.RestException) StreamException(com.linkedin.r2.message.stream.StreamException) Test(org.testng.annotations.Test)

Example 64 with RestResponseBuilder

use of com.linkedin.r2.message.rest.RestResponseBuilder in project rest.li by linkedin.

the class TestMessages method testToRestTransportCallbackSuccess.

@Test
public void testToRestTransportCallbackSuccess() {
    TransportCallback<StreamResponse> streamCallback = response -> {
        Assert.assertFalse(response.hasError());
        Assert.assertNotNull(response.getResponse());
        response.getResponse().getEntityStream().setReader(ENTITY_VERIFIER);
        Assert.assertNotNull(response.getWireAttributes());
        Assert.assertEquals(response.getWireAttributes(), WIRE_ATTR);
    };
    TransportCallback<RestResponse> restCallback = Messages.toRestTransportCallback(streamCallback);
    RestResponseBuilder builder = new RestResponseBuilder();
    builder.setEntity(DATA);
    RestResponse restResponse = builder.build();
    restCallback.onResponse(TransportResponseImpl.success(restResponse, WIRE_ATTR));
}
Also used : ByteStringWriter(com.linkedin.r2.message.stream.entitystream.ByteStringWriter) Callback(com.linkedin.common.callback.Callback) FullEntityReader(com.linkedin.r2.message.stream.entitystream.FullEntityReader) HashMap(java.util.HashMap) Test(org.testng.annotations.Test) TransportCallback(com.linkedin.r2.transport.common.bridge.common.TransportCallback) Messages(com.linkedin.r2.message.Messages) RestResponse(com.linkedin.r2.message.rest.RestResponse) EntityStreams(com.linkedin.r2.message.stream.entitystream.EntityStreams) TransportResponseImpl(com.linkedin.r2.transport.common.bridge.common.TransportResponseImpl) Assert(org.testng.Assert) StreamResponseBuilder(com.linkedin.r2.message.stream.StreamResponseBuilder) ByteString(com.linkedin.data.ByteString) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) Map(java.util.Map) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) StreamException(com.linkedin.r2.message.stream.StreamException) RestException(com.linkedin.r2.message.rest.RestException) RestResponse(com.linkedin.r2.message.rest.RestResponse) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) Test(org.testng.annotations.Test)

Example 65 with RestResponseBuilder

use of com.linkedin.r2.message.rest.RestResponseBuilder in project rest.li by linkedin.

the class TestCapRepFilter method testRestException.

@Test
public void testRestException() throws IOException {
    Path dirPath = Files.createTempDirectory("caprep-test");
    CaptureLastCallFilter lastCallFilter = new CaptureLastCallFilter();
    FilterChain fc = FilterChains.createRestChain(lastCallFilter, _filter);
    RestRequest myRequest = new RestRequestBuilder(URI.create("/req1")).setEntity("123".getBytes()).build();
    RestResponse myErrorResponse = new RestResponseBuilder().setStatus(400).setEntity("321".getBytes()).build();
    RestException myRestException = new RestException(myErrorResponse);
    _filter.capture(dirPath.toString());
    RequestContext requestContext = new RequestContext();
    FilterUtil.fireRestRequest(fc, myRequest, requestContext, FilterUtil.emptyWireAttrs());
    FilterUtil.fireRestError(fc, myRestException, requestContext, FilterUtil.emptyWireAttrs());
    lastCallFilter.reset();
    _filter.replay(dirPath.toString());
    FilterUtil.fireSimpleRestRequest(fc);
    Assert.assertNull(lastCallFilter.getLastErr());
    FilterUtil.fireRestRequest(fc, myRequest);
    Assert.assertTrue(lastCallFilter.getLastErr() instanceof RestException);
    Assert.assertEquals(((RestException) lastCallFilter.getLastErr()).getResponse(), myErrorResponse);
}
Also used : Path(java.nio.file.Path) RestRequest(com.linkedin.r2.message.rest.RestRequest) CaptureLastCallFilter(com.linkedin.r2.testutils.filter.CaptureLastCallFilter) RestResponse(com.linkedin.r2.message.rest.RestResponse) FilterChain(com.linkedin.r2.filter.FilterChain) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) RestException(com.linkedin.r2.message.rest.RestException) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) RequestContext(com.linkedin.r2.message.RequestContext) Test(org.testng.annotations.Test)

Aggregations

RestResponseBuilder (com.linkedin.r2.message.rest.RestResponseBuilder)87 RestResponse (com.linkedin.r2.message.rest.RestResponse)55 Test (org.testng.annotations.Test)53 RestRequest (com.linkedin.r2.message.rest.RestRequest)22 RestException (com.linkedin.r2.message.rest.RestException)18 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)17 RequestContext (com.linkedin.r2.message.RequestContext)15 ByteString (com.linkedin.data.ByteString)13 Map (java.util.Map)10 RestLiServiceException (com.linkedin.restli.server.RestLiServiceException)8 HashMap (java.util.HashMap)8 TransportCallback (com.linkedin.r2.transport.common.bridge.common.TransportCallback)6 RoutingException (com.linkedin.restli.server.RoutingException)6 DataMap (com.linkedin.data.DataMap)5 FilterChain (com.linkedin.r2.filter.FilterChain)5 CaptureLastCallFilter (com.linkedin.r2.testutils.filter.CaptureLastCallFilter)5 FilterRequestContext (com.linkedin.restli.server.filter.FilterRequestContext)5 FilterResponseContext (com.linkedin.restli.server.filter.FilterResponseContext)5 IOException (java.io.IOException)5 URI (java.net.URI)5