Search in sources :

Example 66 with Server

use of com.linkedin.r2.transport.common.Server in project rest.li by linkedin.

the class TestServerTimeoutAsyncEvent method testServerTimeoutAfterResponding.

@Test
public void testServerTimeoutAfterResponding() throws Exception {
    Future<RestResponse> futureResponse = _client.restRequest(new RestRequestBuilder(Bootstrap.createHttpURI(PORT, TIMEOUT_AFTER_SENDING_RESPONSE_SERVER_URI)).build());
    // server should timeout so get should succeed
    RestResponse response = futureResponse.get(ASYNC_EVENT_TIMEOUT * 2, TimeUnit.MILLISECONDS);
    Assert.assertEquals(response.getStatus(), RestStatus.OK);
    Assert.assertEquals(response.getEntity().length(), RESPONSE_SIZE_WRITTEN_SO_FAR);
}
Also used : RestResponse(com.linkedin.r2.message.rest.RestResponse) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) Test(org.testng.annotations.Test)

Example 67 with Server

use of com.linkedin.r2.transport.common.Server in project rest.li by linkedin.

the class TestServerTimeoutAsyncEvent method testFilterThrowButShouldNotTimeout.

@Test
public void testFilterThrowButShouldNotTimeout() throws Exception {
    RestRequest request = new RestRequestBuilder(Bootstrap.createHttpURI(PORT, BUGGY_FILTER_URI)).setEntity(new byte[10240]).build();
    _client.restRequest(request);
    Future<RestResponse> futureResponse = _client.restRequest(request);
    // if server times out, our second request would fail with TimeoutException because it's blocked by first one
    try {
        futureResponse.get(ASYNC_EVENT_TIMEOUT / 2, TimeUnit.MILLISECONDS);
        Assert.fail("Should fail with ExecutionException");
    } catch (ExecutionException ex) {
        Assert.assertTrue(ex.getCause() instanceof RestException);
        RestException restException = (RestException) ex.getCause();
        Assert.assertTrue(restException.getResponse().getEntity().asString("UTF8").contains("Buggy filter throws."));
    }
}
Also used : RestRequest(com.linkedin.r2.message.rest.RestRequest) RestResponse(com.linkedin.r2.message.rest.RestResponse) RestException(com.linkedin.r2.message.rest.RestException) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) ExecutionException(java.util.concurrent.ExecutionException) Test(org.testng.annotations.Test)

Example 68 with Server

use of com.linkedin.r2.transport.common.Server in project rest.li by linkedin.

the class TestParseqTraceDebugRequestHandler method testErrorStreamingAbsorbRequestAbortResponse.

@Test
public void testErrorStreamingAbsorbRequestAbortResponse() throws Exception {
    //This test verifies that in the face of an error, the ParseqTraceDebugRequestHandler aborts any potential outgoing
    //response attachments and absorbs and drops on the ground any incoming request attachments.
    final URI uri = URI.create("http://host/abc/12/__debug/parseqtrace/raw");
    ParseqTraceDebugRequestHandler requestHandler = new ParseqTraceDebugRequestHandler();
    RestRequestBuilder requestBuilder = new RestRequestBuilder(uri);
    RestRequest request = requestBuilder.build();
    RequestContext requestContext = new RequestContext();
    final RequestExecutionCallback<RestResponse> callback = new RequestExecutionCallback<RestResponse>() {

        @Override
        public void onError(Throwable e, RequestExecutionReport executionReport, RestLiAttachmentReader requestAttachmentReader, RestLiResponseAttachments responseAttachments) {
            //Even though we call callback.onError() below to simulate a failed rest.li request execution, the
            //ParseqTraceDebugRequestHandler eventually treats this as a success.
            Assert.fail("Request execution passed unexpectedly.");
        }

        @Override
        public void onSuccess(RestResponse result, RequestExecutionReport executionReport, RestLiResponseAttachments responseAttachments) {
        }
    };
    //Create request and response attachments. This is not the wire protocol for rest.li streaming, but
    //makes this test easier to write and understand.
    //Response attachment.
    final RestLiTestAttachmentDataSource responseDataSource = RestLiTestAttachmentDataSource.createWithRandomPayload("1");
    final RestLiResponseAttachments responseAttachments = new RestLiResponseAttachments.Builder().appendSingleAttachment(responseDataSource).build();
    //Request attachment. We need to create a reader here.
    final RestLiTestAttachmentDataSource requestAttachment = RestLiTestAttachmentDataSource.createWithRandomPayload("2");
    final MultiPartMIMEWriter.Builder builder = new MultiPartMIMEWriter.Builder();
    AttachmentUtils.appendSingleAttachmentToBuilder(builder, requestAttachment);
    final ByteStringWriter byteStringWriter = new ByteStringWriter(ByteString.copyString("Normal rest.li request payload", Charset.defaultCharset()));
    final MultiPartMIMEWriter writer = AttachmentUtils.createMultiPartMIMEWriter(byteStringWriter, "application/json", builder);
    final StreamRequest streamRequest = MultiPartMIMEStreamRequestFactory.generateMultiPartMIMEStreamRequest(new URI(""), "related", writer);
    final MultiPartMIMEReader reader = MultiPartMIMEReader.createAndAcquireStream(streamRequest);
    final RestLiAttachmentReader attachmentReader = new RestLiAttachmentReader(reader);
    //Absorb the first part as rest.li server does and then give the beginning of the next part to the
    //ParseqTraceDebugRequestHandler.
    final MultiPartMIMEReaderCallback multiPartMIMEReaderCallback = new MultiPartMIMEReaderCallback() {

        int partCounter = 0;

        @Override
        public void onNewPart(MultiPartMIMEReader.SinglePartMIMEReader singlePartMIMEReader) {
            if (partCounter == 0) {
                singlePartMIMEReader.drainPart();
                partCounter++;
            } else {
                //When the first part is read in, at the beginning of the 2nd part, we move to the debug request handler.
                requestHandler.handleRequest(request, requestContext, new RestLiDebugRequestHandler.ResourceDebugRequestHandler() {

                    @Override
                    public void handleRequest(RestRequest request, RequestContext requestContext, RequestExecutionCallback<RestResponse> callback) {
                        callback.onError(RestException.forError(500, "An error has occurred"), new RequestExecutionReportBuilder().build(), attachmentReader, responseAttachments);
                    }
                }, attachmentReader, callback);
            }
        }

        @Override
        public void onFinished() {
            Assert.fail();
        }

        @Override
        public void onDrainComplete() {
        //Eventually this should occur.
        }

        @Override
        public void onStreamError(Throwable throwable) {
            Assert.fail();
        }
    };
    reader.registerReaderCallback(multiPartMIMEReaderCallback);
    //The response data source should have been aborted.
    Assert.assertTrue(responseDataSource.dataSourceAborted());
    //The request attachment should have been absorbed and finished.
    Assert.assertTrue(requestAttachment.finished());
}
Also used : RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) URI(java.net.URI) MultiPartMIMEReaderCallback(com.linkedin.multipart.MultiPartMIMEReaderCallback) RequestContext(com.linkedin.r2.message.RequestContext) RestLiTestAttachmentDataSource(com.linkedin.restli.internal.testutils.RestLiTestAttachmentDataSource) MultiPartMIMEWriter(com.linkedin.multipart.MultiPartMIMEWriter) RestResponse(com.linkedin.r2.message.rest.RestResponse) MultiPartMIMEReader(com.linkedin.multipart.MultiPartMIMEReader) StreamRequest(com.linkedin.r2.message.stream.StreamRequest) RestRequest(com.linkedin.r2.message.rest.RestRequest) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) RestLiAttachmentReader(com.linkedin.restli.common.attachments.RestLiAttachmentReader) ByteStringWriter(com.linkedin.r2.message.stream.entitystream.ByteStringWriter) Test(org.testng.annotations.Test)

Example 69 with Server

use of com.linkedin.r2.transport.common.Server in project rest.li by linkedin.

the class TestCharacterEncoding method testQueryParamValueEncoding.

@Test(dataProvider = TestConstants.RESTLI_PROTOCOL_1_2_PREFIX + "protocolVersions")
public void testQueryParamValueEncoding(ProtocolVersion protocolVersion) {
    RestLiConfig config = new RestLiConfig();
    config.setResourcePackageNames(QueryParamMockCollection.class.getPackage().getName());
    RestLiServer server = new RestLiServer(config, new PrototypeResourceFactory(), null);
    for (char c = 0; c < 256; ++c) {
        final String testValue = String.valueOf(c);
        GetRequest<EmptyRecord> req = new GetRequestBuilder<String, EmptyRecord>(QueryParamMockCollection.RESOURCE_NAME, EmptyRecord.class, new ResourceSpecImpl(Collections.<ResourceMethod>emptySet(), Collections.<String, DynamicRecordMetadata>emptyMap(), Collections.<String, DynamicRecordMetadata>emptyMap(), String.class, null, null, EmptyRecord.class, Collections.<String, CompoundKey.TypeInfo>emptyMap()), RestliRequestOptions.DEFAULT_OPTIONS).id("dummy").setParam(QueryParamMockCollection.VALUE_KEY, testValue).build();
        RestRequest restRequest = new RestRequestBuilder(RestliUriBuilderUtil.createUriBuilder(req, protocolVersion).build()).setMethod(req.getMethod().getHttpMethod().toString()).build();
        // N.B. since QueryParamMockCollection is implemented using the synchronous rest.li interface,
        // RestLiServer.handleRequest() will invoke the application resource *and* the callback
        // *synchronously*, ensuring that the all instances of the callback are invoked before the
        // loop terminates.
        server.handleRequest(restRequest, new RequestContext(), new Callback<RestResponse>() {

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

            @Override
            public void onSuccess(RestResponse result) {
                try {
                    DataMap data = new JacksonDataCodec().readMap(result.getEntity().asInputStream());
                    Assert.assertEquals(data.get(QueryParamMockCollection.VALUE_KEY), testValue);
                    Assert.assertEquals(QueryParamMockCollection._lastQueryParamValue, testValue);
                } catch (IOException e) {
                    Assert.fail();
                }
            }
        });
    }
}
Also used : EmptyRecord(com.linkedin.restli.common.EmptyRecord) JacksonDataCodec(com.linkedin.data.codec.JacksonDataCodec) RestLiServer(com.linkedin.restli.server.RestLiServer) CompoundKey(com.linkedin.restli.common.CompoundKey) RestResponse(com.linkedin.r2.message.rest.RestResponse) IOException(java.io.IOException) DataMap(com.linkedin.data.DataMap) RestRequest(com.linkedin.r2.message.rest.RestRequest) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) RequestContext(com.linkedin.r2.message.RequestContext) PrototypeResourceFactory(com.linkedin.restli.server.resources.PrototypeResourceFactory) ResourceSpecImpl(com.linkedin.restli.common.ResourceSpecImpl) RestLiConfig(com.linkedin.restli.server.RestLiConfig) Test(org.testng.annotations.Test)

Example 70 with Server

use of com.linkedin.r2.transport.common.Server in project voldemort by voldemort.

the class RestServerAPITest method oneTimeSetUp.

@BeforeClass
public static void oneTimeSetUp() {
    voldemortConfig = VoldemortConfig.loadFromVoldemortHome("config/single_node_rest_server/");
    key = new ByteArray("key1".getBytes());
    vectorClock = new VectorClock();
    vectorClock.incrementVersion(voldemortConfig.getNodeId(), System.currentTimeMillis());
    value = new Versioned<byte[]>("value1".getBytes(), vectorClock);
    server = new VoldemortServer(voldemortConfig);
    if (!server.isStarted())
        server.start();
    logger.info("********************Starting REST Server********************");
    restClientConfig = new RESTClientConfig();
    restClientConfig.setHttpBootstrapURL("http://localhost:8085").setTimeoutMs(1500, TimeUnit.MILLISECONDS).setMaxR2ConnectionPoolSize(100);
    clientFactory = new HttpClientFactory();
    Map<String, String> properties = new HashMap<String, String>();
    properties.put(HttpClientFactory.HTTP_POOL_SIZE, Integer.toString(restClientConfig.getMaxR2ConnectionPoolSize()));
    transportClient = clientFactory.getClient(properties);
    r2store = new R2Store("test", restClientConfig.getHttpBootstrapURL(), "2", transportClient, restClientConfig, 0);
    store = r2store;
    deleteCreatedKeys(key);
}
Also used : RESTClientConfig(voldemort.restclient.RESTClientConfig) HashMap(java.util.HashMap) VectorClock(voldemort.versioning.VectorClock) R2Store(voldemort.restclient.R2Store) ByteArray(voldemort.utils.ByteArray) VoldemortServer(voldemort.server.VoldemortServer) HttpClientFactory(com.linkedin.r2.transport.http.client.HttpClientFactory) BeforeClass(org.junit.BeforeClass)

Aggregations

Test (org.testng.annotations.Test)82 RestRequest (com.linkedin.r2.message.rest.RestRequest)52 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)50 RequestContext (com.linkedin.r2.message.RequestContext)49 URI (java.net.URI)43 RestResponse (com.linkedin.r2.message.rest.RestResponse)41 StreamRequest (com.linkedin.r2.message.stream.StreamRequest)32 FutureCallback (com.linkedin.common.callback.FutureCallback)30 StreamResponse (com.linkedin.r2.message.stream.StreamResponse)30 CountDownLatch (java.util.concurrent.CountDownLatch)24 StreamRequestBuilder (com.linkedin.r2.message.stream.StreamRequestBuilder)23 RestException (com.linkedin.r2.message.rest.RestException)21 ExecutionException (java.util.concurrent.ExecutionException)21 None (com.linkedin.common.util.None)20 Server (org.eclipse.jetty.server.Server)20 ByteString (com.linkedin.data.ByteString)19 HttpServerBuilder (com.linkedin.r2.testutils.server.HttpServerBuilder)19 HashMap (java.util.HashMap)15 RemoteInvocationException (com.linkedin.r2.RemoteInvocationException)13 ArrayList (java.util.ArrayList)13