Search in sources :

Example 21 with Response

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

the class TestRestCompressionEcho method testResponseCompression.

@Test(dataProvider = "compressionEchoData")
public void testResponseCompression(Client client, long bytes) throws InterruptedException, TimeoutException, ExecutionException {
    RestRequestBuilder builder = new RestRequestBuilder((Bootstrap.createHttpURI(PORT, ECHO_URI)));
    byte[] content = new byte[(int) bytes];
    for (int i = 0; i < bytes; i++) {
        content[i] = (byte) (i % 256);
    }
    RestRequest request = builder.setEntity(content).build();
    final FutureCallback<RestResponse> callback = new FutureCallback<RestResponse>();
    RequestContext requestContext = new RequestContext();
    // OPERATION is required to enabled response compression
    requestContext.putLocalAttr(R2Constants.OPERATION, "get");
    client.restRequest(request, requestContext, callback);
    final RestResponse response = callback.get(60, TimeUnit.SECONDS);
    Assert.assertEquals(response.getStatus(), RestStatus.OK);
    Assert.assertEquals(response.getEntity().copyBytes(), content);
}
Also used : RestRequest(com.linkedin.r2.message.rest.RestRequest) RestResponse(com.linkedin.r2.message.rest.RestResponse) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) RequestContext(com.linkedin.r2.message.RequestContext) FutureCallback(com.linkedin.common.callback.FutureCallback) Test(org.testng.annotations.Test)

Example 22 with Response

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

the class TestDisruptor method testStreamLatencyDisrupt.

@Test
public void testStreamLatencyDisrupt() throws Exception {
    final Map<String, String> properties = new HashMap<>();
    final TransportClientFactory factory = new HttpClientFactory.Builder().build();
    final TransportClient client = factory.getClient(properties);
    final RequestContext requestContext = new RequestContext();
    requestContext.putLocalAttr(DISRUPT_CONTEXT_KEY, DisruptContexts.delay(REQUEST_LATENCY));
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean success = new AtomicBoolean(false);
    client.streamRequest(new StreamRequestBuilder(new URI(REQUEST_URI)).build(EntityStreams.emptyStream()), requestContext, new HashMap<>(), response -> {
        success.set(!response.hasError() && response.getResponse() != null);
        latch.countDown();
    });
    Assert.assertTrue(latch.await(TEST_TIMEOUT, TimeUnit.MILLISECONDS), "Test execution timeout");
    Assert.assertTrue(success.get(), "Unexpected transport response");
}
Also used : TransportClient(com.linkedin.r2.transport.common.bridge.client.TransportClient) HashMap(java.util.HashMap) CountDownLatch(java.util.concurrent.CountDownLatch) StreamRequestBuilder(com.linkedin.r2.message.stream.StreamRequestBuilder) URI(java.net.URI) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RequestContext(com.linkedin.r2.message.RequestContext) TransportClientFactory(com.linkedin.r2.transport.common.TransportClientFactory) HttpClientFactory(com.linkedin.r2.transport.http.client.HttpClientFactory) Test(org.testng.annotations.Test)

Example 23 with Response

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

the class TestHttpClient method testSimpleURI.

@Test(dataProvider = "configs")
public void testSimpleURI(Server server, Client client) throws Exception {
    try {
        server.start();
        // Note no trailing slash; the point of the test is to ensure this URI will
        // send a Request-URI of "/".
        URI uri = URI.create("http://localhost:" + PORT);
        RestRequestBuilder rb = new RestRequestBuilder(uri);
        rb.setMethod("GET");
        RestRequest request = rb.build();
        Future<RestResponse> f = client.restRequest(request);
        // This will block
        RestResponse response = f.get();
        assertEquals(response.getStatus(), 200);
        final FutureCallback<None> callback = new FutureCallback<None>();
        client.shutdown(callback);
        callback.get();
    } finally {
        server.stop();
    }
}
Also used : RestRequest(com.linkedin.r2.message.rest.RestRequest) RestResponse(com.linkedin.r2.message.rest.RestResponse) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) URI(java.net.URI) None(com.linkedin.common.util.None) FutureCallback(com.linkedin.common.callback.FutureCallback) Test(org.testng.annotations.Test)

Example 24 with Response

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

the class TestRAPClientCodec method testResponseDecoder.

@Test(dataProvider = "responseData")
public void testResponseDecoder(int status, String entity, HttpHeaders headers, String[] cookies) {
    final EmbeddedChannel ch = new EmbeddedChannel(new RAPClientCodec());
    ByteBuf content = Unpooled.copiedBuffer(entity, CHARSET);
    FullHttpResponse nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(status), content);
    nettyResponse.headers().set(headers);
    for (String cookie : cookies) {
        nettyResponse.headers().add(HttpHeaderNames.SET_COOKIE, cookie);
    }
    ch.writeInbound(nettyResponse);
    RestResponse response = (RestResponse) ch.readInbound();
    Assert.assertEquals(response.getStatus(), status);
    Assert.assertEquals(response.getEntity().asString(CHARSET), entity);
    assertList(response.getCookies(), nettyResponse.headers().getAll(HttpConstants.RESPONSE_COOKIE_HEADER_NAME));
    for (Map.Entry<String, String> header : nettyResponse.headers()) {
        if (!header.getKey().equalsIgnoreCase(HttpConstants.RESPONSE_COOKIE_HEADER_NAME)) {
            List<String> values = response.getHeaderValues(header.getKey());
            Assert.assertNotNull(values);
            Assert.assertTrue(values.contains(header.getValue()));
        }
    }
    // make sure the incoming ByteBuf is released
    Assert.assertEquals(content.refCnt(), 0);
    ch.finish();
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) RestResponse(com.linkedin.r2.message.rest.RestResponse) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) ByteString(com.linkedin.data.ByteString) ByteBuf(io.netty.buffer.ByteBuf) Map(java.util.Map) Test(org.testng.annotations.Test)

Example 25 with Response

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

the class TestRestClientRequestBuilder method clientGeneratedStreamRequest.

//This is similar to clientGeneratedRestRequest above except that it will generate a StreamRequest instead
//of a RestRequest. Note that this will ONLY happen if either acceptResponseAttachments below is 'true' OR
//streamingAttachmentDataSources below is non-null with a size greater then 0. If both of these do not hold,
//then a StreamRequest will not be generated by the RestClient.
@SuppressWarnings({ "unchecked", "rawtypes", "deprecation" })
private <T extends Request> StreamRequest clientGeneratedStreamRequest(Class<T> requestClass, ResourceMethod method, DataMap entityBody, RestClient.ContentType contentType, List<RestClient.AcceptType> acceptTypes, boolean acceptContentTypePerClient, List<Object> streamingAttachmentDataSources, boolean acceptResponseAttachments) throws URISyntaxException {
    // massive setup...
    Client mockClient = EasyMock.createMock(Client.class);
    @SuppressWarnings({ "rawtypes" }) Request<?> mockRequest = EasyMock.createMock(requestClass);
    RecordTemplate mockRecordTemplate = EasyMock.createMock(RecordTemplate.class);
    @SuppressWarnings({ "rawtypes" }) RestResponseDecoder mockResponseDecoder = EasyMock.createMock(RestResponseDecoder.class);
    RestliRequestOptions requestOptions = RestliRequestOptions.DEFAULT_OPTIONS;
    //If there is a desire to receive response attachments, then we must use request options.
    if (!acceptContentTypePerClient || acceptResponseAttachments) {
        requestOptions = new RestliRequestOptions(ProtocolVersionOption.USE_LATEST_IF_AVAILABLE, null, null, contentType, acceptTypes, acceptResponseAttachments);
    }
    setCommonExpectations(mockRequest, method, mockResponseDecoder, requestOptions);
    if (streamingAttachmentDataSources != null && streamingAttachmentDataSources.size() > 0) {
        EasyMock.expect(mockRequest.getStreamingAttachments()).andReturn(streamingAttachmentDataSources).times(2);
    } else {
        EasyMock.expect(mockRequest.getStreamingAttachments()).andReturn(null).times(2);
    }
    setResourceMethodExpectations(method, mockRequest, mockRecordTemplate, entityBody);
    Capture<StreamRequest> streamRequestCapture = new Capture<StreamRequest>();
    EasyMock.expect(mockClient.getMetadata(new URI(HOST + SERVICE_NAME))).andReturn(Collections.<String, Object>emptyMap()).once();
    mockClient.streamRequest(EasyMock.capture(streamRequestCapture), (RequestContext) EasyMock.anyObject(), (Callback<StreamResponse>) EasyMock.anyObject());
    EasyMock.expectLastCall().once();
    EasyMock.replay(mockClient, mockRequest, mockRecordTemplate);
    // do work!
    RestClient restClient;
    if (acceptContentTypePerClient) {
        // configuration per client
        restClient = new RestClient(mockClient, HOST, contentType, acceptTypes);
    } else {
        // configuration per request
        restClient = new RestClient(mockClient, HOST);
    }
    restClient.sendRequest(mockRequest);
    return streamRequestCapture.getValue();
}
Also used : StreamResponse(com.linkedin.r2.message.stream.StreamResponse) ByteString(com.linkedin.data.ByteString) URI(java.net.URI) Capture(org.easymock.Capture) StreamRequest(com.linkedin.r2.message.stream.StreamRequest) RestResponseDecoder(com.linkedin.restli.internal.client.RestResponseDecoder) RecordTemplate(com.linkedin.data.template.RecordTemplate) Client(com.linkedin.r2.transport.common.Client)

Aggregations

Test (org.testng.annotations.Test)155 RestResponse (com.linkedin.r2.message.rest.RestResponse)142 RestRequest (com.linkedin.r2.message.rest.RestRequest)101 RequestContext (com.linkedin.r2.message.RequestContext)95 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)87 URI (java.net.URI)77 StreamResponse (com.linkedin.r2.message.stream.StreamResponse)66 ByteString (com.linkedin.data.ByteString)58 StreamRequest (com.linkedin.r2.message.stream.StreamRequest)41 StreamRequestBuilder (com.linkedin.r2.message.stream.StreamRequestBuilder)40 HashMap (java.util.HashMap)39 FutureCallback (com.linkedin.common.callback.FutureCallback)36 RestException (com.linkedin.r2.message.rest.RestException)36 CountDownLatch (java.util.concurrent.CountDownLatch)35 RestResponseBuilder (com.linkedin.r2.message.rest.RestResponseBuilder)34 ExecutionException (java.util.concurrent.ExecutionException)32 TransportCallback (com.linkedin.r2.transport.common.bridge.common.TransportCallback)27 Callback (com.linkedin.common.callback.Callback)25 IOException (java.io.IOException)24 Map (java.util.Map)24