Search in sources :

Example 61 with Server

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

the class SyncIOHandler method loop.

public void loop() throws ServletException, IOException {
    final long startTime = System.currentTimeMillis();
    byte[] buf = new byte[DEFAULT_DATA_CHUNK_SIZE];
    while (shouldContinue() && !_forceExit) {
        Event event;
        try {
            long timeSpent = System.currentTimeMillis() - startTime;
            long maxWaitTime = timeSpent < _timeout ? _timeout - timeSpent : 0;
            event = _eventQueue.poll(maxWaitTime, TimeUnit.MILLISECONDS);
            if (event == null) {
                throw new TimeoutException("Timeout after " + _timeout + " milliseconds.");
            }
        } catch (Exception ex) {
            throw new ServletException(ex);
        }
        switch(event.getEventType()) {
            case ResponseDataAvailable:
                {
                    ByteString data = (ByteString) event.getData();
                    data.write(_os);
                    _rh.request(1);
                    break;
                }
            case WriteRequestPossible:
                {
                    while (_wh.remaining() > 0) {
                        int actualLen = _is.read(buf);
                        if (actualLen < 0) {
                            _wh.done();
                            _requestReadFinished = true;
                            break;
                        }
                        _wh.write(ByteString.copy(buf, 0, actualLen));
                    }
                    break;
                }
            case FullResponseReceived:
                {
                    _os.close();
                    _responseWriteFinished = true;
                    break;
                }
            case ResponseDataError:
                {
                    _os.close();
                    _responseWriteFinished = true;
                    break;
                }
            case WriteRequestAborted:
                {
                    if (event.getData() instanceof AbortedException) {
                        // reader cancels, we'll drain the stream on behalf of reader
                        // we don't directly drain it here because we'd like to give other events
                        // some opportunities to be executed; e.g. return an error response
                        _eventQueue.add(Event.DrainRequestEvent);
                    } else {
                        // TODO: do we want to be smarter and return server error response?
                        throw new ServletException((Throwable) event.getData());
                    }
                    break;
                }
            case DrainRequest:
                {
                    for (int i = 0; i < 10; i++) {
                        int actualLen = _is.read(buf);
                        if (actualLen < 0) {
                            _requestReadFinished = true;
                            break;
                        }
                    }
                    if (!_requestReadFinished) {
                        // add self back to event queue and give others a chance to run
                        _eventQueue.add(Event.DrainRequestEvent);
                    }
                    break;
                }
            case ForceExit:
                {
                    _forceExit = true;
                    break;
                }
            default:
                throw new IllegalStateException("Unknown event type:" + event.getEventType());
        }
    }
}
Also used : ServletException(javax.servlet.ServletException) ByteString(com.linkedin.data.ByteString) AbortedException(com.linkedin.r2.message.stream.entitystream.AbortedException) ServletException(javax.servlet.ServletException) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) AbortedException(com.linkedin.r2.message.stream.entitystream.AbortedException) TimeoutException(java.util.concurrent.TimeoutException)

Example 62 with Server

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

the class TestHttpClient method testClient.

@Test(dataProvider = "configs")
public void testClient(Server server, Client client) throws Exception {
    try {
        server.start();
        RestRequestBuilder rb = new RestRequestBuilder(REQUEST_URI);
        rb.setMethod("GET");
        RestRequest request = rb.build();
        Future<RestResponse> f = client.restRequest(request);
        // This will block
        RestResponse response = f.get();
        final ByteString entity = response.getEntity();
        if (entity != null) {
            System.out.println(entity.asString("UTF-8"));
        } else {
            System.out.println("NOTHING!");
        }
        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) ByteString(com.linkedin.data.ByteString) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) None(com.linkedin.common.util.None) FutureCallback(com.linkedin.common.callback.FutureCallback) Test(org.testng.annotations.Test)

Example 63 with Server

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

the class TestHttpsEcho method createClient.

@Override
protected Client createClient(FilterChain filters) throws Exception {
    final Map<String, Object> properties = new HashMap<String, Object>();
    //load the keystore
    KeyStore certKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    certKeyStore.load(new FileInputStream(keyStore), keyStorePassword.toCharArray());
    //set KeyManger to use X509
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(certKeyStore, keyStorePassword.toCharArray());
    //use a standard trust manager and load server certificate
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(certKeyStore);
    //set context to TLS and initialize it
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    properties.put(HttpClientFactory.HTTP_SSL_CONTEXT, context);
    properties.put(HttpClientFactory.HTTP_SSL_PARAMS, context.getDefaultSSLParameters());
    final TransportClient client = new HttpClientFactory.Builder().setFilterChain(filters).build().getClient(properties);
    return new TransportClientAdapter(client, _clientROS);
}
Also used : TransportClient(com.linkedin.r2.transport.common.bridge.client.TransportClient) HashMap(java.util.HashMap) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) TransportClientAdapter(com.linkedin.r2.transport.common.bridge.client.TransportClientAdapter) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) HttpClientFactory(com.linkedin.r2.transport.http.client.HttpClientFactory)

Example 64 with Server

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

the class AbstractEchoServiceTest method testFilterChain.

@Test
public void testFilterChain() throws Exception {
    final EchoService client = getEchoClient(_client, Bootstrap.getEchoURI());
    final String msg = "This is a simple echo message";
    final FutureCallback<String> callback = new FutureCallback<String>();
    client.echo(msg, callback);
    callback.get();
    // Make sure the server got its wire attribute
    Assert.assertEquals(_serverCaptureFilter.getRequest().get(_toServerKey), _toServerValue);
    Assert.assertEquals(_serverCaptureFilter.getResponse().get(_toClientKey), _toClientValue);
    // Make sure the client got its wire attribute, but not the server's wire attribute
    Assert.assertEquals(_clientCaptureFilter.getResponse().get(_toClientKey), _toClientValue);
    Assert.assertNull(_clientCaptureFilter.getResponse().get(_toServerKey));
}
Also used : EchoService(com.linkedin.r2.sample.echo.EchoService) FutureCallback(com.linkedin.common.callback.FutureCallback) Test(org.testng.annotations.Test)

Example 65 with Server

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

the class TestServerTimeout method testFilterNotCancelButShouldNotTimeout.

@Test
public void testFilterNotCancelButShouldNotTimeout() throws Exception {
    RestRequest request = new RestRequestBuilder(Bootstrap.createHttpURI(PORT, STREAM_EXCEPTION_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(SERVER_IOHANDLER_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("StreamException in filter."));
    }
}
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)

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