Reworked HTTP client API, removing usage of Future.

This commit is contained in:
Simone Bordet 2012-12-18 17:55:27 +01:00
parent 72cdab4934
commit c9f4513a89
46 changed files with 634 additions and 635 deletions

View File

@ -38,8 +38,10 @@ import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import javax.net.ssl.SSLEngine;
import org.eclipse.jetty.client.api.AuthenticationStore;
@ -302,10 +304,10 @@ public class HttpClient extends ContainerLifeCycle
* Performs a GET request to the specified URI.
*
* @param uri the URI to GET
* @return a future for a {@link ContentResponse}
* @return the {@link ContentResponse} for the request
* @see #GET(URI)
*/
public Future<ContentResponse> GET(String uri)
public ContentResponse GET(String uri) throws InterruptedException, ExecutionException, TimeoutException
{
return GET(URI.create(uri));
}
@ -314,10 +316,10 @@ public class HttpClient extends ContainerLifeCycle
* Performs a GET request to the specified URI.
*
* @param uri the URI to GET
* @return a future for a {@link ContentResponse}
* @return the {@link ContentResponse} for the request
* @see #newRequest(URI)
*/
public Future<ContentResponse> GET(URI uri)
public ContentResponse GET(URI uri) throws InterruptedException, ExecutionException, TimeoutException
{
return newRequest(uri).send();
}

View File

@ -28,6 +28,7 @@ import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.jetty.client.api.Authentication;
@ -142,7 +143,7 @@ public class HttpConnection extends AbstractConnection implements Connection
request.agent(client.getUserAgent());
if (request.getIdleTimeout() <= 0)
request.idleTimeout(client.getIdleTimeout());
request.idleTimeout(client.getIdleTimeout(), TimeUnit.MILLISECONDS);
HttpMethod method = request.getMethod();
HttpVersion version = request.getVersion();

View File

@ -29,14 +29,16 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicLong;
import org.eclipse.jetty.client.api.ContentProvider;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.util.BlockingResponseListener;
import org.eclipse.jetty.client.util.FutureResponseListener;
import org.eclipse.jetty.client.util.PathContentProvider;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
@ -62,6 +64,7 @@ public class HttpRequest implements Request
private HttpMethod method;
private HttpVersion version;
private long idleTimeout;
private long timeout;
private ContentProvider content;
private boolean followRedirects;
private volatile Throwable aborted;
@ -397,18 +400,46 @@ public class HttpRequest implements Request
}
@Override
public Request idleTimeout(long timeout)
public Request idleTimeout(long timeout, TimeUnit unit)
{
this.idleTimeout = timeout;
this.idleTimeout = unit.toMillis(timeout);
return this;
}
@Override
public Future<ContentResponse> send()
public long getTimeout()
{
BlockingResponseListener listener = new BlockingResponseListener(this);
return timeout;
}
@Override
public Request timeout(long timeout, TimeUnit unit)
{
this.timeout = unit.toMillis(timeout);
return this;
}
@Override
public ContentResponse send() throws InterruptedException, TimeoutException, ExecutionException
{
FutureResponseListener listener = new FutureResponseListener(this);
send(listener);
return listener;
long timeout = getTimeout();
if (timeout <= 0)
return listener.get();
try
{
return listener.get(timeout, TimeUnit.MILLISECONDS);
}
catch (InterruptedException | TimeoutException x)
{
// Differently from the Future, the semantic of this method is that if
// the send() is interrupted or times out, we abort the request.
abort(x);
throw x;
}
}
@Override

View File

@ -23,7 +23,9 @@ import java.nio.file.Path;
import java.util.EventListener;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.util.InputStreamResponseListener;
@ -192,15 +194,28 @@ public interface Request
Request agent(String agent);
/**
* @return the idle timeout for this request
* @return the idle timeout for this request, in milliseconds
*/
long getIdleTimeout();
/**
* @param timeout the idle timeout for this request
* @param unit the idle timeout unit
* @return this request object
*/
Request idleTimeout(long timeout);
Request idleTimeout(long timeout, TimeUnit unit);
/**
* @return the total timeout for this request, in milliseconds
*/
long getTimeout();
/**
* @param timeout the total timeout for the request/response conversation
* @param unit the timeout unit
* @return this request object
*/
Request timeout(long timeout, TimeUnit unit);
/**
* @return whether this request follows redirects
@ -298,21 +313,21 @@ public interface Request
Request onResponseFailure(Response.FailureListener listener);
/**
* Sends this request and returns a {@link Future} that can be used to wait for the
* request and the response to be completed (either with a success or a failure).
* Sends this request and returns the response.
* <p />
* This method should be used when a simple blocking semantic is needed, and when it is known
* that the response content can be buffered without exceeding memory constraints.
* <p />
* For example, this method is not appropriate to download big files from a server; consider using
* {@link #send(Response.CompleteListener)} instead, passing your own {@link Response.Listener} or a utility
* listener such as {@link InputStreamResponseListener}.
* <p />
* The future will return when {@link Response.Listener#onComplete(Result)} is invoked.
* The method returns when the {@link Response.CompleteListener complete event} is fired.
*
* @return a {@link Future} to wait on for request and response completion
* @see Response.Listener#onComplete(Result)
* @return a {@link ContentResponse} for this request
* @see Response.CompleteListener#onComplete(Result)
*/
Future<ContentResponse> send();
ContentResponse send() throws InterruptedException, TimeoutException, ExecutionException;
/**
* Sends this request and asynchronously notifies the given listener for response events.

View File

@ -38,12 +38,12 @@ import org.eclipse.jetty.client.api.Result;
* Typical usage is:
* <pre>
* Request request = httpClient.newRequest(...)...;
* BlockingResponseListener listener = new BlockingResponseListener(request);
* FutureResponseListener listener = new FutureResponseListener(request);
* request.send(listener); // Asynchronous send
* ContentResponse response = listener.get(5, TimeUnit.SECONDS); // Timed block
* </pre>
*/
public class BlockingResponseListener extends BufferingResponseListener implements Future<ContentResponse>
public class FutureResponseListener extends BufferingResponseListener implements Future<ContentResponse>
{
private final CountDownLatch latch = new CountDownLatch(1);
private final Request request;
@ -51,12 +51,12 @@ public class BlockingResponseListener extends BufferingResponseListener implemen
private Throwable failure;
private volatile boolean cancelled;
public BlockingResponseListener(Request request)
public FutureResponseListener(Request request)
{
this(request, 2 * 1024 * 1024);
}
public BlockingResponseListener(Request request, int maxLength)
public FutureResponseListener(Request request, int maxLength)
{
super(maxLength);
this.request = request;
@ -106,11 +106,7 @@ public class BlockingResponseListener extends BufferingResponseListener implemen
{
boolean expired = !latch.await(timeout, unit);
if (expired)
{
TimeoutException reason = new TimeoutException();
request.abort(reason);
throw reason;
}
throw new TimeoutException();
return getResult();
}

View File

@ -30,8 +30,6 @@ import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.junit.After;
import org.junit.Rule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

View File

@ -128,7 +128,7 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
// Request without Authentication causes a 401
Request request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure");
ContentResponse response = request.send().get(5, TimeUnit.SECONDS);
ContentResponse response = request.timeout(5, TimeUnit.SECONDS).send();
Assert.assertNotNull(response);
Assert.assertEquals(401, response.getStatus());
Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS));
@ -148,7 +148,7 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
client.getRequestListeners().add(requestListener);
// Request with authentication causes a 401 (no previous successful authentication) + 200
response = request.send().get(5, TimeUnit.SECONDS);
response = request.timeout(5, TimeUnit.SECONDS).send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS));
@ -168,7 +168,7 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
// Further requests do not trigger 401 because there is a previous successful authentication
// Remove existing header to be sure it's added by the implementation
request.header(HttpHeader.AUTHORIZATION.asString(), null);
response = request.send().get(5, TimeUnit.SECONDS);
response = request.timeout(5, TimeUnit.SECONDS).send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS));
@ -208,8 +208,8 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.path("/secure")
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(requests.await(5, TimeUnit.SECONDS));
@ -247,8 +247,8 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.path("/redirect")
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(requests.await(5, TimeUnit.SECONDS));
@ -277,7 +277,7 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
authenticationStore.addAuthentication(authentication);
Request request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure");
ContentResponse response = request.send().get(5, TimeUnit.SECONDS);
ContentResponse response = request.timeout(5, TimeUnit.SECONDS).send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS));
@ -286,7 +286,7 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
requests.set(new CountDownLatch(1));
request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure");
response = request.send().get(5, TimeUnit.SECONDS);
response = request.timeout(5, TimeUnit.SECONDS).send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS));
@ -297,7 +297,7 @@ public class HttpClientAuthenticationTest extends AbstractHttpClientServerTest
requests.set(new CountDownLatch(1));
request = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).path("/secure");
response = request.send().get(5, TimeUnit.SECONDS);
response = request.timeout(5, TimeUnit.SECONDS).send();
Assert.assertNotNull(response);
Assert.assertEquals(401, response.getStatus());
Assert.assertTrue(requests.get().await(5, TimeUnit.SECONDS));

View File

@ -82,8 +82,8 @@ public class HttpClientContinueTest extends AbstractHttpClientServerTest
.scheme(scheme)
.header(HttpHeader.EXPECT.asString(), HttpHeaderValue.CONTINUE.asString())
.content(new BytesContentProvider(contents))
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
@ -129,8 +129,8 @@ public class HttpClientContinueTest extends AbstractHttpClientServerTest
return -1;
}
})
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());

View File

@ -24,7 +24,7 @@ import org.eclipse.jetty.client.api.Connection;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Destination;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.util.BlockingResponseListener;
import org.eclipse.jetty.client.util.FutureResponseListener;
import org.eclipse.jetty.toolchain.test.annotation.Slow;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.Assert;
@ -46,7 +46,7 @@ public class HttpClientExplicitConnectionTest extends AbstractHttpClientServerTe
try (Connection connection = destination.newConnection().get(5, TimeUnit.SECONDS))
{
Request request = client.newRequest(destination.getHost(), destination.getPort()).scheme(scheme);
BlockingResponseListener listener = new BlockingResponseListener(request);
FutureResponseListener listener = new FutureResponseListener(request);
connection.send(request, listener);
ContentResponse response = listener.get(5, TimeUnit.SECONDS);
@ -68,7 +68,7 @@ public class HttpClientExplicitConnectionTest extends AbstractHttpClientServerTe
Destination destination = client.getDestination(scheme, "localhost", connector.getLocalPort());
Connection connection = destination.newConnection().get(5, TimeUnit.SECONDS);
Request request = client.newRequest(destination.getHost(), destination.getPort()).scheme(scheme);
BlockingResponseListener listener = new BlockingResponseListener(request);
FutureResponseListener listener = new FutureResponseListener(request);
connection.send(request, listener);
ContentResponse response = listener.get(5, TimeUnit.SECONDS);

View File

@ -60,7 +60,8 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest
Response response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.path("/303/localhost/done")
.send().get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
@ -72,7 +73,8 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest
Response response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.path("/303/localhost/302/localhost/done")
.send().get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
@ -84,7 +86,8 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest
Response response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.path("/303/127.0.0.1/302/localhost/done")
.send().get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
@ -97,7 +100,8 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest
.scheme(scheme)
.method(HttpMethod.HEAD)
.path("/301/localhost/done")
.send().get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
@ -112,7 +116,8 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest
.scheme(scheme)
.method(HttpMethod.POST)
.path("/301/localhost/done")
.send().get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
fail();
}
catch (ExecutionException x)
@ -134,7 +139,8 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest
.method(HttpMethod.POST)
.path("/307/localhost/done")
.content(new ByteBufferContentProvider(ByteBuffer.wrap(data)))
.send().get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
@ -151,7 +157,8 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.path("/303/localhost/302/localhost/done")
.send().get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
fail();
}
catch (ExecutionException x)
@ -170,7 +177,8 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest
Response response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.path("/303/localhost/done?close=true")
.send().get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
Assert.assertFalse(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));
@ -183,7 +191,8 @@ public class HttpClientRedirectTest extends AbstractHttpClientServerTest
.scheme(scheme)
.followRedirects(false)
.path("/303/localhost/done?close=true")
.send().get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(303, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(HttpHeader.LOCATION.asString()));

View File

@ -83,8 +83,8 @@ public class HttpClientStreamTest extends AbstractHttpClientServerTest
requestTime.set(System.nanoTime());
}
})
.send()
.get(10, TimeUnit.SECONDS);
.timeout(10, TimeUnit.SECONDS)
.send();
long responseTime = System.nanoTime();
Assert.assertEquals(200, response.getStatus());

View File

@ -75,7 +75,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest
String host = "localhost";
int port = connector.getLocalPort();
String path = "/";
Response response = client.GET(scheme + "://" + host + ":" + port + path).get(5, TimeUnit.SECONDS);
Response response = client.GET(scheme + "://" + host + ":" + port + path);
Assert.assertEquals(200, response.getStatus());
HttpDestination destination = (HttpDestination)client.getDestination(scheme, host, port);
@ -107,7 +107,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest
String host = "localhost";
int port = connector.getLocalPort();
client.GET(scheme + "://" + host + ":" + port).get(5, TimeUnit.SECONDS);
client.GET(scheme + "://" + host + ":" + port);
List<Destination> destinations = client.getDestinations();
Assert.assertNotNull(destinations);
@ -124,7 +124,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest
{
start(new EmptyServerHandler());
Response response = client.GET(scheme + "://localhost:" + connector.getLocalPort()).get(5, TimeUnit.SECONDS);
Response response = client.GET(scheme + "://localhost:" + connector.getLocalPort());
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
@ -144,7 +144,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest
}
});
ContentResponse response = client.GET(scheme + "://localhost:" + connector.getLocalPort()).get(5, TimeUnit.SECONDS);
ContentResponse response = client.GET(scheme + "://localhost:" + connector.getLocalPort());
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
@ -176,7 +176,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest
String value1 = "\u20AC";
String paramValue1 = URLEncoder.encode(value1, "UTF-8");
String query = paramName1 + "=" + paramValue1 + "&" + paramName2;
ContentResponse response = client.GET(scheme + "://localhost:" + connector.getLocalPort() + "/?" + query).get(5, TimeUnit.SECONDS);
ContentResponse response = client.GET(scheme + "://localhost:" + connector.getLocalPort() + "/?" + query);
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
@ -212,7 +212,7 @@ public class HttpClientTest extends AbstractHttpClientServerTest
String paramValue12 = URLEncoder.encode(value12, "UTF-8");
String paramValue2 = URLEncoder.encode(value2, "UTF-8");
String query = paramName1 + "=" + paramValue11 + "&" + paramName1 + "=" + paramValue12 + "&" + paramName2 + "=" + paramValue2;
ContentResponse response = client.GET(scheme + "://localhost:" + connector.getLocalPort() + "/?" + query).get(5, TimeUnit.SECONDS);
ContentResponse response = client.GET(scheme + "://localhost:" + connector.getLocalPort() + "/?" + query);
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
@ -242,7 +242,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest
});
ContentResponse response = client.POST(scheme + "://localhost:" + connector.getLocalPort())
.param(paramName, paramValue).send().get(5, TimeUnit.SECONDS);
.param(paramName, paramValue)
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
@ -274,7 +276,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest
ContentResponse response = client.POST(scheme + "://localhost:" + connector.getLocalPort() + "/?b=1")
.param(paramName, paramValue)
.content(new BytesContentProvider(content))
.send().get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
@ -574,8 +577,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertArrayEquals(data, response.getContent());
@ -609,8 +612,9 @@ public class HttpClientTest extends AbstractHttpClientServerTest
{
client.newRequest(host, port)
.scheme(scheme)
.idleTimeout(idleTimeout)
.send().get(3 * idleTimeout, TimeUnit.MILLISECONDS);
.idleTimeout(idleTimeout, TimeUnit.MILLISECONDS)
.timeout(3 * idleTimeout, TimeUnit.MILLISECONDS)
.send();
Assert.fail();
}
catch (ExecutionException expected)
@ -621,7 +625,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest
// Make another request without specifying the idle timeout, should not fail
ContentResponse response = client.newRequest(host, port)
.scheme(scheme)
.send().get(3 * idleTimeout, TimeUnit.MILLISECONDS);
.timeout(3 * idleTimeout, TimeUnit.MILLISECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
@ -634,8 +639,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest
ContentResponse response = client.newRequest("[::1]", connector.getLocalPort())
.scheme(scheme)
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
@ -665,8 +670,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest
return !field.getName().equals(headerName);
}
})
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
@ -692,8 +697,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.method(HttpMethod.HEAD)
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());
@ -702,8 +707,8 @@ public class HttpClientTest extends AbstractHttpClientServerTest
// Perform a normal GET request to be sure the content is now read
response = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertNotNull(response);
Assert.assertEquals(200, response.getStatus());

View File

@ -58,7 +58,8 @@ public class HttpClientTimeoutTest extends AbstractHttpClientServerTest
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.send().get(timeout, TimeUnit.MILLISECONDS);
.timeout(timeout, TimeUnit.MILLISECONDS)
.send();
}
@Slow

View File

@ -452,8 +452,8 @@ public class HttpConnectionLifecycleTest extends AbstractHttpClientServerTest
ContentResponse response = client.newRequest(host, port)
.scheme(scheme)
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());

View File

@ -22,7 +22,6 @@ import java.io.IOException;
import java.net.HttpCookie;
import java.net.URI;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
@ -61,7 +60,7 @@ public class HttpCookieTest extends AbstractHttpClientServerTest
int port = connector.getLocalPort();
String path = "/path";
String uri = scheme + "://" + host + ":" + port + path;
Response response = client.GET(uri).get(5, TimeUnit.SECONDS);
Response response = client.GET(uri);
Assert.assertEquals(200, response.getStatus());
List<HttpCookie> cookies = client.getCookieStore().get(URI.create(uri));
@ -98,7 +97,7 @@ public class HttpCookieTest extends AbstractHttpClientServerTest
HttpCookie cookie = new HttpCookie(name, value);
client.getCookieStore().add(URI.create(uri), cookie);
Response response = client.GET(scheme + "://" + host + ":" + port + path).get(5, TimeUnit.SECONDS);
Response response = client.GET(scheme + "://" + host + ":" + port + path);
Assert.assertEquals(200, response.getStatus());
}
}

View File

@ -30,7 +30,7 @@ import java.util.zip.GZIPOutputStream;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.util.BlockingResponseListener;
import org.eclipse.jetty.client.util.FutureResponseListener;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpVersion;
@ -73,7 +73,7 @@ public class HttpReceiverTest
protected HttpExchange newExchange()
{
HttpRequest request = new HttpRequest(client, URI.create("http://localhost"));
BlockingResponseListener listener = new BlockingResponseListener(request);
FutureResponseListener listener = new FutureResponseListener(request);
HttpExchange exchange = new HttpExchange(conversation, connection, request, Collections.<Response.ResponseListener>singletonList(listener));
conversation.getExchanges().offer(exchange);
connection.setExchange(exchange);
@ -90,7 +90,7 @@ public class HttpReceiverTest
"Content-length: 0\r\n" +
"\r\n");
HttpExchange exchange = newExchange();
BlockingResponseListener listener = (BlockingResponseListener)exchange.getResponseListeners().get(0);
FutureResponseListener listener = (FutureResponseListener)exchange.getResponseListeners().get(0);
exchange.receive();
Response response = listener.get(5, TimeUnit.SECONDS);
@ -114,7 +114,7 @@ public class HttpReceiverTest
"\r\n" +
content);
HttpExchange exchange = newExchange();
BlockingResponseListener listener = (BlockingResponseListener)exchange.getResponseListeners().get(0);
FutureResponseListener listener = (FutureResponseListener)exchange.getResponseListeners().get(0);
exchange.receive();
Response response = listener.get(5, TimeUnit.SECONDS);
@ -141,7 +141,7 @@ public class HttpReceiverTest
"\r\n" +
content1);
HttpExchange exchange = newExchange();
BlockingResponseListener listener = (BlockingResponseListener)exchange.getResponseListeners().get(0);
FutureResponseListener listener = (FutureResponseListener)exchange.getResponseListeners().get(0);
exchange.receive();
endPoint.setInputEOF();
exchange.receive();
@ -165,7 +165,7 @@ public class HttpReceiverTest
"Content-length: 1\r\n" +
"\r\n");
HttpExchange exchange = newExchange();
BlockingResponseListener listener = (BlockingResponseListener)exchange.getResponseListeners().get(0);
FutureResponseListener listener = (FutureResponseListener)exchange.getResponseListeners().get(0);
exchange.receive();
// Simulate an idle timeout
connection.idleTimeout();
@ -189,7 +189,7 @@ public class HttpReceiverTest
"Content-length: A\r\n" +
"\r\n");
HttpExchange exchange = newExchange();
BlockingResponseListener listener = (BlockingResponseListener)exchange.getResponseListeners().get(0);
FutureResponseListener listener = (FutureResponseListener)exchange.getResponseListeners().get(0);
exchange.receive();
try
@ -220,7 +220,7 @@ public class HttpReceiverTest
"Content-Encoding: gzip\r\n" +
"\r\n");
HttpExchange exchange = newExchange();
BlockingResponseListener listener = (BlockingResponseListener)exchange.getResponseListeners().get(0);
FutureResponseListener listener = (FutureResponseListener)exchange.getResponseListeners().get(0);
exchange.receive();
endPoint.reset();

View File

@ -23,7 +23,6 @@ import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
@ -33,6 +32,7 @@ import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.api.Result;
import org.eclipse.jetty.client.util.ByteBufferContentProvider;
import org.eclipse.jetty.server.HttpChannel;
@ -76,7 +76,8 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
begin.set(true);
}
})
.send().get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)
@ -114,7 +115,8 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
committed.countDown();
}
})
.send().get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)
@ -153,7 +155,8 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
committed.countDown();
}
})
.send().get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)
@ -188,7 +191,8 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
aborted.countDown();
}
})
.send().get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertFalse(aborted.await(1, TimeUnit.SECONDS));
}
@ -243,7 +247,8 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
return -1;
}
})
.send().get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)
@ -269,6 +274,53 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
}
}
@Slow
@Test(expected = InterruptedException.class)
public void testInterrupt() throws Exception
{
final long delay = 1000;
start(new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
try
{
baseRequest.setHandled(true);
TimeUnit.MILLISECONDS.sleep(2 * delay);
}
catch (InterruptedException x)
{
throw new ServletException(x);
}
}
});
Request request = client.newRequest("localhost", connector.getLocalPort())
.timeout(3 * delay, TimeUnit.MILLISECONDS)
.scheme(scheme);
final Thread thread = Thread.currentThread();
new Thread()
{
@Override
public void run()
{
try
{
TimeUnit.MILLISECONDS.sleep(delay);
thread.interrupt();
}
catch (InterruptedException x)
{
throw new RuntimeException(x);
}
}
}.start();
request.send();
}
@Slow
@Test
public void testAbortLongPoll() throws Exception
@ -291,18 +343,31 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
}
});
Request request = client.newRequest("localhost", connector.getLocalPort())
final Request request = client.newRequest("localhost", connector.getLocalPort())
.timeout(3 * delay, TimeUnit.MILLISECONDS)
.scheme(scheme);
Future<ContentResponse> future = request.send();
TimeUnit.MILLISECONDS.sleep(delay);
Throwable cause = new Exception();
request.abort(cause);
final Throwable cause = new Exception();
new Thread()
{
@Override
public void run()
{
try
{
TimeUnit.MILLISECONDS.sleep(delay);
request.abort(cause);
}
catch (InterruptedException x)
{
throw new RuntimeException(x);
}
}
}.start();
try
{
future.get(5, TimeUnit.SECONDS);
request.send();
}
catch (ExecutionException x)
{
@ -310,6 +375,51 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
}
}
@Slow
@Test
public void testAbortLongPollAsync() throws Exception
{
final long delay = 1000;
start(new AbstractHandler()
{
@Override
public void handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
try
{
baseRequest.setHandled(true);
TimeUnit.MILLISECONDS.sleep(2 * delay);
}
catch (InterruptedException x)
{
throw new ServletException(x);
}
}
});
final Throwable cause = new Exception();
final CountDownLatch latch = new CountDownLatch(1);
Request request = client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.timeout(3 * delay, TimeUnit.MILLISECONDS);
request.send(new Response.CompleteListener()
{
@Override
public void onComplete(Result result)
{
Assert.assertTrue(result.isFailed());
Assert.assertSame(cause, result.getFailure());
latch.countDown();
}
});
TimeUnit.MILLISECONDS.sleep(delay);
request.abort(cause);
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@Test
public void testAbortConversation() throws Exception
{
@ -343,8 +453,8 @@ public class HttpRequestAbortTest extends AbstractHttpClientServerTest
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.path("/redirect")
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)

View File

@ -19,19 +19,14 @@
package org.eclipse.jetty.client;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Response;
import org.eclipse.jetty.client.api.Result;
import org.eclipse.jetty.http.HttpField;
@ -180,36 +175,4 @@ public class HttpResponseAbortTest extends AbstractHttpClientServerTest
});
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
}
@Test(expected = CancellationException.class)
public void testCancelFuture() throws Exception
{
final CountDownLatch latch = new CountDownLatch(1);
final AtomicReference<Future<ContentResponse>> ref = new AtomicReference<>();
start(new AbstractHandler()
{
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
try
{
latch.await(5, TimeUnit.SECONDS);
baseRequest.setHandled(true);
ref.get().cancel(true);
OutputStream output = response.getOutputStream();
output.write(new byte[]{0, 1, 2, 3, 4, 5, 6, 7});
}
catch (InterruptedException x)
{
throw new InterruptedIOException();
}
}
});
Future<ContentResponse> future = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).send();
ref.set(future);
latch.countDown();
future.get(5, TimeUnit.SECONDS);
}
}

View File

@ -24,13 +24,12 @@ import java.net.HttpCookie;
import java.net.URI;
import java.nio.file.Paths;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.util.BasicAuthentication;
import org.eclipse.jetty.client.util.BlockingResponseListener;
import org.eclipse.jetty.client.util.FutureResponseListener;
import org.eclipse.jetty.client.util.InputStreamContentProvider;
import org.eclipse.jetty.client.util.InputStreamResponseListener;
import org.eclipse.jetty.http.HttpMethod;
@ -48,9 +47,8 @@ public class Usage
HttpClient client = new HttpClient();
client.start();
Future<ContentResponse> responseFuture = client.GET("http://localhost:8080/foo");
// Block to get the response
Response response = responseFuture.get();
ContentResponse response = client.GET("http://localhost:8080/foo");
// Verify response status code
Assert.assertEquals(200, response.getStatus());
@ -74,12 +72,10 @@ public class Usage
.param("a", "b")
.header("X-Header", "Y-value")
.agent("Jetty HTTP Client")
.idleTimeout(5000L);
Future<ContentResponse> responseFuture = request.send();
// Block to get the response
Response response = responseFuture.get();
.idleTimeout(5000, TimeUnit.MILLISECONDS)
.timeout(20, TimeUnit.SECONDS);
ContentResponse response = request.send();
Assert.assertEquals(200, response.getStatus());
}
@ -99,7 +95,7 @@ public class Usage
@Override
public void onComplete(Result result)
{
if (!result.isFailed())
if (result.isSucceeded())
{
responseRef.set(result.getResponse());
latch.countDown();
@ -137,7 +133,7 @@ public class Usage
public void onSuccess(Request request)
{
}
}).send().get(5, TimeUnit.SECONDS);
}).send();
Assert.assertEquals(200, response.getStatus());
}
@ -152,8 +148,8 @@ public class Usage
{
Request request = client.newRequest("localhost", 8080);
// Asynchronous send but using BlockingResponseListener
BlockingResponseListener listener = new BlockingResponseListener(request);
// Asynchronous send but using FutureResponseListener
FutureResponseListener listener = new FutureResponseListener(request);
connection.send(request, listener);
// Wait for the response on the listener
Response response = listener.get(5, TimeUnit.SECONDS);
@ -170,7 +166,7 @@ public class Usage
client.start();
// One liner to upload files
Response response = client.newRequest("localhost", 8080).file(Paths.get("file_to_upload.txt")).send().get();
Response response = client.newRequest("localhost", 8080).file(Paths.get("file_to_upload.txt")).send();
Assert.assertEquals(200, response.getStatus());
}
@ -185,7 +181,7 @@ public class Usage
client.getCookieStore().add(URI.create("http://host:8080/path"), new HttpCookie("name", "value"));
// Send a request for the cookie's domain
Response response = client.newRequest("host", 8080).send().get();
Response response = client.newRequest("host", 8080).send();
Assert.assertEquals(200, response.getStatus());
}
@ -202,7 +198,7 @@ public class Usage
client.getAuthenticationStore().addAuthentication(new BasicAuthentication(uri, "TestRealm", "username", "password"));
// One liner to send the request
ContentResponse response = client.newRequest(uri).send().get(5, TimeUnit.SECONDS);
ContentResponse response = client.newRequest(uri).timeout(5, TimeUnit.SECONDS).send();
Assert.assertEquals(200, response.getStatus());
}
@ -219,8 +215,8 @@ public class Usage
ContentResponse response = client.newRequest("localhost", 8080)
// Follow redirects for this request only
.followRedirects(true)
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
}
@ -270,8 +266,7 @@ public class Usage
ContentResponse response = client.newRequest("localhost", 8080)
// Provide the content as InputStream
.content(new InputStreamContentProvider(input))
.send()
.get(5, TimeUnit.SECONDS);
.send();
Assert.assertEquals(200, response.getStatus());
}

View File

@ -22,7 +22,6 @@ import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -103,9 +102,9 @@ public class AbstractTestOSGi
{
diagnoseNonActiveOrNonResolvedBundle(b);
}
Assert.assertTrue("Bundle: " + b + " (state should be " +
"ACTIVE[" + Bundle.ACTIVE + "] or RESOLVED[" + Bundle.RESOLVED + "]" +
", but was [" + b.getState() + "])",
Assert.assertTrue("Bundle: " + b + " (state should be " +
"ACTIVE[" + Bundle.ACTIVE + "] or RESOLVED[" + Bundle.RESOLVED + "]" +
", but was [" + b.getState() + "])",
(b.getState() == Bundle.ACTIVE) || (b.getState() == Bundle.RESOLVED));
}
}
@ -179,7 +178,7 @@ public class AbstractTestOSGi
try
{
client.start();
ContentResponse response = client.GET(protocol+"://127.0.0.1:"+port+"/greetings").get(5, TimeUnit.SECONDS);;
ContentResponse response = client.GET(protocol+"://127.0.0.1:"+port+"/greetings");
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
String content = new String(response.getContent());

View File

@ -22,7 +22,6 @@ import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import junit.framework.Assert;
@ -158,7 +157,7 @@ public class TestJettyOSGiBootWithJsp extends AbstractTestOSGi
{
client.start();
ContentResponse response = client.GET("http://127.0.0.1:"+
TestJettyOSGiBootCore.DEFAULT_JETTY_HTTP_PORT+"/jsp/dump.jsp").get(5, TimeUnit.SECONDS);
TestJettyOSGiBootCore.DEFAULT_JETTY_HTTP_PORT+"/jsp/dump.jsp");
Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
String content = new String(response.getContent());

View File

@ -115,8 +115,8 @@ public class BalancerServletTest
{
ContentResponse response = client.newRequest("localhost", getServerPort(balancer))
.path(CONTEXT_PATH + SERVLET_PATH + path)
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
return response.getContent();
}

View File

@ -140,8 +140,8 @@ public class ProxyServletTest
try
{
client.newRequest("localhost", serverConnector.getLocalPort())
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.fail();
}
catch (ExecutionException x)
@ -161,8 +161,8 @@ public class ProxyServletTest
server.stop();
ContentResponse response = client.newRequest("localhost", serverPort)
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(502, response.getStatus());
}
@ -181,8 +181,8 @@ public class ProxyServletTest
});
ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort())
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(500, response.getStatus());
}
@ -202,8 +202,8 @@ public class ProxyServletTest
});
ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort())
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
@ -228,8 +228,8 @@ public class ProxyServletTest
// Request is for the target server
ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort())
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
@ -256,8 +256,8 @@ public class ProxyServletTest
ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort())
.method(HttpMethod.POST)
.content(new BytesContentProvider(content))
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
@ -282,8 +282,8 @@ public class ProxyServletTest
ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort())
.method(HttpMethod.POST)
.content(new BytesContentProvider(content))
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
@ -311,8 +311,8 @@ public class ProxyServletTest
ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort())
.method(HttpMethod.POST)
.content(new BytesContentProvider(content))
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
@ -395,8 +395,8 @@ public class ProxyServletTest
});
ContentResponse response = client.newRequest("http://localhost:" + serverConnector.getLocalPort() + "/?" + query)
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertEquals(query, response.getContentAsString());
}
@ -446,8 +446,8 @@ public class ProxyServletTest
});
Response response = client.newRequest("localhost", serverConnector.getLocalPort())
.send()
.get(2 * timeout, TimeUnit.MILLISECONDS);
.timeout(2 * timeout, TimeUnit.MILLISECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
}
@ -478,8 +478,8 @@ public class ProxyServletTest
});
Response response = client.newRequest("localhost", serverConnector.getLocalPort())
.send()
.get(3 * timeout, TimeUnit.MILLISECONDS);
.timeout(3 * timeout, TimeUnit.MILLISECONDS)
.send();
Assert.assertEquals(504, response.getStatus());
Assert.assertFalse(response.getHeaders().containsKey(PROXIED_HEADER));
}
@ -510,8 +510,8 @@ public class ProxyServletTest
});
client.newRequest("localhost", serverConnector.getLocalPort())
.send()
.get(timeout, TimeUnit.MILLISECONDS);
.timeout(timeout, TimeUnit.MILLISECONDS)
.send();
Assert.fail();
}
@ -530,7 +530,7 @@ public class ProxyServletTest
}
});
ContentResponse response = client.GET("http://localhost:" + serverConnector.getLocalPort()).get(5, TimeUnit.SECONDS);
ContentResponse response = client.GET("http://localhost:" + serverConnector.getLocalPort());
Assert.assertThat("Response expected to contain content of X-Forwarded-Host Header from the request",
response.getContentAsString(),
Matchers.equalTo("localhost:" + serverConnector.getLocalPort()));
@ -546,14 +546,14 @@ public class ProxyServletTest
// Try with the wrong host
ContentResponse response = client.newRequest("localhost", port)
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(403, response.getStatus());
// Try again with the right host
response = client.newRequest("127.0.0.1", port)
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
}
@ -567,14 +567,14 @@ public class ProxyServletTest
// Try with the wrong host
ContentResponse response = client.newRequest("localhost", port)
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(403, response.getStatus());
// Try again with the right host
response = client.newRequest("127.0.0.1", port)
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
}
@ -596,15 +596,15 @@ public class ProxyServletTest
// Try with a proxied host
ContentResponse response = client.newRequest("localhost", port)
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
// Try again with an excluded host
response = client.newRequest("127.0.0.1", port)
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertFalse(response.getHeaders().containsKey(PROXIED_HEADER));
}
@ -632,8 +632,8 @@ public class ProxyServletTest
// Make the request to the proxy, it should transparently forward to the server
ContentResponse response = client.newRequest("localhost", proxyConnector.getLocalPort())
.path(prefix + target)
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
}
@ -706,16 +706,16 @@ public class ProxyServletTest
// First request
ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort())
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
Assert.assertArrayEquals(content, response.getContent());
// Second request should be cached
response = client.newRequest("localhost", serverConnector.getLocalPort())
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(cacheHeader));
Assert.assertArrayEquals(content, response.getContent());
@ -739,8 +739,8 @@ public class ProxyServletTest
client.setFollowRedirects(false);
ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort())
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(302, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
}
@ -766,8 +766,8 @@ public class ProxyServletTest
});
ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort())
.send()
.get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
Assert.assertArrayEquals(content, response.getContent());

View File

@ -141,7 +141,8 @@ public class PushStrategyBenchmarkTest extends AbstractHTTPSPDYTest
++result;
ContentResponse response = httpClient.newRequest("localhost", connector.getLocalPort())
.path(primaryPath)
.send().get(5, TimeUnit.SECONDS);
.timeout(5, TimeUnit.SECONDS)
.send();
Assert.assertEquals(200, response.getStatus());
for (int i = 0; i < cssResources.length; ++i)

View File

@ -412,7 +412,7 @@
<module>jetty-nosql</module>
<module>examples</module>
<module>tests</module>
<module>aggregates/jetty-all</module>
<!--<module>aggregates/jetty-all</module>-->
<module>jetty-distribution</module>
<module>jetty-runner</module>

View File

@ -18,26 +18,19 @@
package org.eclipse.jetty;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashSet;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Future;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
@ -45,17 +38,13 @@ import javax.servlet.http.HttpServletResponse;
import org.apache.derby.tools.ij;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.HttpRequest;
import org.eclipse.jetty.client.api.AuthenticationStore;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.util.BasicAuthentication;
import org.eclipse.jetty.client.util.ByteBufferContentProvider;
import org.eclipse.jetty.client.util.BytesContentProvider;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.util.security.Constraint;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.eclipse.jetty.io.EofException;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
@ -72,13 +61,18 @@ import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.Loader;
import org.eclipse.jetty.util.security.Constraint;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class JdbcLoginServiceTest
{
{
private static String _content =
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In quis felis nunc. "+
"Quisque suscipit mauris et ante auctor ornare rhoncus lacus aliquet. Pellentesque "+
@ -100,7 +94,7 @@ public class JdbcLoginServiceTest
private static String _protocol;
private static String _baseUrl;
private static String _requestContent;
protected static boolean createDB(String homeDir, String fileName, String dbUrl)
{
FileInputStream fileStream = null;
@ -108,10 +102,10 @@ public class JdbcLoginServiceTest
{
File scriptFile = new File(fileName);
fileStream = new FileInputStream(scriptFile);
Loader.loadClass(fileStream.getClass(), "org.apache.derby.jdbc.EmbeddedDriver").newInstance();
Connection connection = DriverManager.getConnection(dbUrl, "", "");
OutputStream out = new ByteArrayOutputStream();
int result = ij.runScript(connection, fileStream, "UTF-8", out, "UTF-8");
@ -139,7 +133,7 @@ public class JdbcLoginServiceTest
setProtocol("http");
LoginService loginService = new JDBCLoginService(__realm, "./src/test/resources/jdbcrealm.properties");
server.addBean(loginService);
server.addBean(loginService);
ConstraintSecurityHandler security = new ConstraintSecurityHandler();
server.setHandler(security);
@ -153,29 +147,29 @@ public class JdbcLoginServiceTest
mapping.setPathSpec( "/*" );
mapping.setConstraint( constraint );
Set<String> knownRoles = new HashSet<String>();
Set<String> knownRoles = new HashSet<>();
knownRoles.add("user");
knownRoles.add("admin");
security.setConstraintMappings(Collections.singletonList(mapping), knownRoles);
security.setAuthenticator(new BasicAuthenticator());
security.setLoginService(loginService);
security.setStrict(false);
ServletContextHandler root = new ServletContextHandler();
root.setContextPath("/");
root.setResourceBase(getBasePath());
ServletHolder servletHolder = new ServletHolder( new DefaultServlet() );
servletHolder.setInitParameter( "gzip", "true" );
root.addServlet( servletHolder, "/*" );
root.addServlet( servletHolder, "/*" );
Handler handler = new TestHandler(getBasePath());
Handler handler = new TestHandler(getBasePath());
HandlerCollection handlers = new HandlerCollection();
handlers.setHandlers(new Handler[]{handler, root});
security.setHandler(handlers);
}
@BeforeClass
public static void setUp()
throws Exception
@ -183,7 +177,7 @@ public class JdbcLoginServiceTest
_docRoot = new File("target/test-output/docroot/");
_docRoot.mkdirs();
_docRoot.deleteOnExit();
File content = new File(_docRoot,"input.txt");
FileOutputStream out = new FileOutputStream(content);
out.write(_content.getBytes("utf-8"));
@ -197,17 +191,17 @@ public class JdbcLoginServiceTest
dbRoot.mkdirs();
createDB(dbPath, "src/test/resources/createdb.sql", "jdbc:derby:jdbcrealm;create=true");
}
_server = new Server(0);
configureServer(_server);
_server.start();
int port = ((NetworkConnector)_server.getConnectors()[0]).getLocalPort();
_baseUrl = _protocol+"://localhost:"+port+ "/";
}
@AfterClass
public static void tearDown()
throws Exception
@ -229,8 +223,7 @@ public class JdbcLoginServiceTest
Request request = _client.newRequest(getBaseUrl() + "output.txt");
request.method(HttpMethod.PUT);
request.content(new BytesContentProvider(_content.getBytes()));
Future<ContentResponse> future = request.send();
ContentResponse response = future.get();
ContentResponse response = request.send();
int responseStatus = response.getStatus();
boolean statusOk = (responseStatus == 200 || responseStatus == 201);
assertTrue(statusOk);
@ -242,7 +235,7 @@ public class JdbcLoginServiceTest
stopClient();
}
}
@Test
public void testGet() throws Exception
{
@ -250,12 +243,11 @@ public class JdbcLoginServiceTest
{
startClient();
Future<ContentResponse> future = _client.GET(getBaseUrl() + "input.txt");
ContentResponse response = future.get();
ContentResponse response = _client.GET(getBaseUrl() + "input.txt");
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
assertEquals(_content, response.getContentAsString());
}
finally
finally
{
stopClient();
}
@ -271,8 +263,7 @@ public class JdbcLoginServiceTest
Request request = _client.newRequest(getBaseUrl() + "input.txt");
request.method(HttpMethod.HEAD);
Future<ContentResponse> future = request.send();
ContentResponse response = future.get();
ContentResponse response = request.send();
int responseStatus = response.getStatus();
assertEquals(HttpStatus.OK_200,responseStatus);
}
@ -292,8 +283,7 @@ public class JdbcLoginServiceTest
Request request = _client.newRequest(getBaseUrl() + "test");
request.method(HttpMethod.POST);
request.content(new BytesContentProvider(_content.getBytes()));
Future<ContentResponse> future = request.send();
ContentResponse response = future.get();
ContentResponse response = request.send();
assertEquals(HttpStatus.OK_200,response.getStatus());
assertEquals(_content,_requestContent);
}
@ -302,7 +292,7 @@ public class JdbcLoginServiceTest
stopClient();
}
}
protected void startClient()
throws Exception
{
@ -314,7 +304,7 @@ public class JdbcLoginServiceTest
authStore.addAuthentication(new BasicAuthentication(_baseUrl, __realm, "jetty", "jetty"));
_client.start();
}
protected void stopClient()
throws Exception
{
@ -324,35 +314,35 @@ public class JdbcLoginServiceTest
_client = null;
}
}
protected static String getBasePath()
{
return _docRoot.getAbsolutePath();
}
protected String getBaseUrl()
{
return _baseUrl;
}
protected HttpClient getClient()
{
return _client;
}
protected String getContent()
{
return _content;
}
protected static void setProtocol(String protocol)
{
_protocol = protocol;
}
public static void copyStream(InputStream in, OutputStream out)
{
try
@ -391,7 +381,7 @@ public class JdbcLoginServiceTest
}
OutputStream out = null;
if (baseRequest.getMethod().equals("PUT"))
{
baseRequest.setHandled(true);
@ -399,12 +389,12 @@ public class JdbcLoginServiceTest
File file = new File(resourcePath, URLDecoder.decode(request.getPathInfo()));
file.getParentFile().mkdirs();
file.deleteOnExit();
out = new FileOutputStream(file);
response.setStatus(HttpServletResponse.SC_CREATED);
}
if (baseRequest.getMethod().equals("POST"))
{
baseRequest.setHandled(true);
@ -412,24 +402,22 @@ public class JdbcLoginServiceTest
response.setStatus(HttpServletResponse.SC_OK);
}
if (out != null)
{
ServletInputStream in = request.getInputStream();
try
try (ServletInputStream in = request.getInputStream())
{
copyStream( in, out );
copyStream(in, out);
}
finally
{
in.close();
out.close();
}
if (!(out instanceof FileOutputStream))
_requestContent = out.toString();
}
}
}
}

View File

@ -18,14 +18,8 @@
package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.Future;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -41,6 +35,10 @@ import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.IO;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* IdleSessionTest
@ -55,12 +53,6 @@ public class IdleSessionTest
private int _idlePeriod;
private File _storeDir;
/**
* @param port
* @param maxInactivePeriod
* @param scavengePeriod
* @param idlePeriod
*/
public IdleHashTestServer(int port, int maxInactivePeriod, int scavengePeriod, int idlePeriod, File storeDir)
{
super(port, maxInactivePeriod, scavengePeriod);
@ -83,11 +75,10 @@ public class IdleSessionTest
public HashTestServer createServer(int port, int max, int scavenge, int idle, File storeDir)
{
HashTestServer server = new IdleHashTestServer(port, max, scavenge, idle, storeDir);
return server;
return new IdleHashTestServer(port, max, scavenge, idle, storeDir);
}
public void pause (int sec)
{
@ -128,8 +119,7 @@ public class IdleSessionTest
String url = "http://localhost:" + port1 + contextPath + servletMapping;
//make a request to set up a session on the server
Future<ContentResponse> future = client.GET(url + "?action=init");
ContentResponse response = future.get();
ContentResponse response = client.GET(url + "?action=init");
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
String sessionCookie = response.getHeaders().getStringField("Set-Cookie");
assertTrue(sessionCookie != null);
@ -145,8 +135,7 @@ public class IdleSessionTest
//make another request to de-idle the session
Request request = client.newRequest(url + "?action=test");
request.getHeaders().add("Cookie", sessionCookie);
future = request.send();
ContentResponse response2 = future.get();
ContentResponse response2 = request.send();
assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
//check session de-idled
@ -184,8 +173,6 @@ public class IdleSessionTest
public static class TestServlet extends HttpServlet
{
public String originalId = null;
public String testId = null;
public String checkId = null;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException

View File

@ -18,15 +18,10 @@
package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.Future;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -40,6 +35,9 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* MaxInactiveMigrationTest
@ -47,7 +45,7 @@ import org.junit.Test;
* Test
*/
public class MaxInactiveMigrationTest
{
{
private JdbcTestServer testServer1;
private JdbcTestServer testServer2;
private HttpClient client;
@ -82,11 +80,11 @@ public class MaxInactiveMigrationTest
testServer1.stop();
testServer2.stop();
client.stop();
try
try
{
DriverManager.getConnection( "jdbc:derby:sessions;shutdown=true" );
}
catch( SQLException expected )
}
catch( SQLException expected )
{
}
}
@ -101,8 +99,7 @@ public class MaxInactiveMigrationTest
Request request = client.newRequest("http://localhost:" + port + "" + "/test");
if (sessionCookie != null)
request.header("Cookie", sessionCookie);
Future<ContentResponse> future = request.send();
ContentResponse response = future.get();
ContentResponse response = request.send();
assertEquals(HttpServletResponse.SC_OK, response.getStatus());
sessionCookie = response.getHeaders().getStringField("Set-Cookie");
@ -125,12 +122,12 @@ public class MaxInactiveMigrationTest
HttpSession session = request.getSession( true );
Integer counter = ( Integer )session.getAttribute( ATTR_COUNTER );
if( counter == null ) {
counter = new Integer( 0 );
counter = 0;
}
counter = new Integer( counter.intValue() + 1 );
counter = counter + 1;
session.setAttribute( ATTR_COUNTER, counter );
PrintWriter writer = response.getWriter();
writer.write( "Hello World " + counter.intValue() );
writer.write( "Hello World " + counter);
writer.flush();
}

View File

@ -18,12 +18,7 @@
package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.concurrent.Future;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -37,6 +32,9 @@ import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* AbstractClientCrossContextSessionTest
@ -63,7 +61,7 @@ public abstract class AbstractClientCrossContextSessionTest
ctxB.addServlet(holderB, servletMapping);
server.start();
int port = server.getPort();
try
{
HttpClient client = new HttpClient();
@ -71,8 +69,7 @@ public abstract class AbstractClientCrossContextSessionTest
try
{
// Perform a request to contextA
Future<ContentResponse> future = client.GET("http://localhost:" + port + contextA + servletMapping);
ContentResponse response = future.get();
ContentResponse response = client.GET("http://localhost:" + port + contextA + servletMapping);
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
String sessionCookie = response.getHeaders().getStringField("Set-Cookie");
@ -83,8 +80,7 @@ public abstract class AbstractClientCrossContextSessionTest
// Perform a request to contextB with the same session cookie
Request request = client.newRequest("http://localhost:" + port + contextB + servletMapping);
request.header("Cookie", sessionCookie);
future = request.send();
ContentResponse responseB = future.get();
ContentResponse responseB = request.send();
assertEquals(HttpServletResponse.SC_OK,responseB.getStatus());
assertEquals(servletA.sessionId, servletB.sessionId);
}
@ -102,7 +98,7 @@ public abstract class AbstractClientCrossContextSessionTest
public static class TestServletA extends HttpServlet
{
public String sessionId;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
@ -125,7 +121,7 @@ public abstract class AbstractClientCrossContextSessionTest
public static class TestServletB extends HttpServlet
{
public String sessionId;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException
{

View File

@ -18,13 +18,8 @@
package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.Future;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -36,6 +31,9 @@ import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* AbstractImmortalSessionTest
@ -55,16 +53,15 @@ public abstract class AbstractImmortalSessionTest
server.addContext(contextPath).addServlet(TestServlet.class, servletMapping);
server.start();
int port=server.getPort();
try
{
HttpClient client = new HttpClient();
client.start();
try
{
int value = 42;
Future<ContentResponse> future = client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=set&value=" + value);
ContentResponse response = future.get();
int value = 42;
ContentResponse response = client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=set&value=" + value);
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
String sessionCookie = response.getHeaders().getStringField("Set-Cookie");
assertTrue(sessionCookie != null);
@ -77,11 +74,10 @@ public abstract class AbstractImmortalSessionTest
// Let's wait for the scavenger to run, waiting 2.5 times the scavenger period
Thread.sleep(scavengePeriod * 2500L);
// Be sure the session is still there
// Be sure the session is still there
Request request = client.newRequest("http://localhost:" + port + contextPath + servletMapping + "?action=get");
request.header("Cookie", sessionCookie);
future = request.send();
response = future.get();
response = request.send();
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
resp = response.getContentAsString();
assertEquals(String.valueOf(value),resp.trim());

View File

@ -18,12 +18,7 @@
package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.concurrent.Future;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -36,6 +31,9 @@ import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* AbstractInvalidationSessionTest
* Goal of the test is to be sure that invalidating a session on one node
@ -76,9 +74,8 @@ public abstract class AbstractInvalidationSessionTest
urls[1] = "http://localhost:" + port2 + contextPath + servletMapping;
// Create the session on node1
Future<ContentResponse> future = client.GET(urls[0] + "?action=init");
ContentResponse response1 = future.get();
ContentResponse response1 = client.GET(urls[0] + "?action=init");
assertEquals(HttpServletResponse.SC_OK,response1.getStatus());
String sessionCookie = response1.getHeaders().getStringField("Set-Cookie");
assertTrue(sessionCookie != null);
@ -86,26 +83,24 @@ public abstract class AbstractInvalidationSessionTest
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
// Be sure the session is also present in node2
Request request2 = client.newRequest(urls[1] + "?action=increment");
request2.header("Cookie", sessionCookie);
future = request2.send();
ContentResponse response2 = future.get();
request2.header("Cookie", sessionCookie);
ContentResponse response2 = request2.send();
assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
// Invalidate on node1
Request request1 = client.newRequest(urls[0] + "?action=invalidate");
request1.header("Cookie", sessionCookie);
future = request1.send();
response1 = request1.send();
assertEquals(HttpServletResponse.SC_OK, response1.getStatus());
pause();
// Be sure on node2 we don't see the session anymore
request2 = client.newRequest(urls[1] + "?action=test");
request2.header("Cookie", sessionCookie);
future = request2.send();
response2 = future.get();
response2 = request2.send();
assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
}
finally

View File

@ -18,13 +18,8 @@
package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.Future;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -40,12 +35,16 @@ import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* AbstractLastAccessTimeTest
*
* This test checks that a session can migrate from node A to node B, kept in use in node B
* past the time at which it would have expired due to inactivity on node A but is NOT
*
* This test checks that a session can migrate from node A to node B, kept in use in node B
* past the time at which it would have expired due to inactivity on node A but is NOT
* scavenged by node A. In other words, it tests that a session that migrates from one node
* to another is not timed out on the original node.
*/
@ -82,8 +81,7 @@ public abstract class AbstractLastAccessTimeTest
try
{
// Perform one request to server1 to create a session
Future<ContentResponse> future = client.GET("http://localhost:" + port1 + contextPath + servletMapping + "?action=init");
ContentResponse response1 = future.get();
ContentResponse response1 = client.GET("http://localhost:" + port1 + contextPath + servletMapping + "?action=init");
assertEquals(HttpServletResponse.SC_OK, response1.getStatus());
assertEquals("test", response1.getContentAsString());
String sessionCookie = response1.getHeaders().getStringField("Set-Cookie");
@ -101,15 +99,14 @@ public abstract class AbstractLastAccessTimeTest
{
Request request = client.newRequest("http://localhost:" + port2 + contextPath + servletMapping);
request.header("Cookie", sessionCookie);
future = request.send();
ContentResponse response2 = future.get();
ContentResponse response2 = request.send();
assertEquals(HttpServletResponse.SC_OK , response2.getStatus());
assertEquals("test", response2.getContentAsString());
String setCookie = response2.getHeaders().getStringField("Set-Cookie");
if (setCookie!=null)
if (setCookie!=null)
sessionCookie = setCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
Thread.sleep(requestInterval);
}
@ -118,7 +115,7 @@ public abstract class AbstractLastAccessTimeTest
Thread.sleep(scavengePeriod * 2500L);
//check that the session was not scavenged over on server1 by ensuring that the SessionListener destroy method wasn't called
assertTrue (listener1.destroyed == false);
assertFalse(listener1.destroyed);
}
finally
{
@ -140,26 +137,26 @@ public abstract class AbstractLastAccessTimeTest
{
public boolean destroyed = false;
public boolean created = false;
@Override
public void sessionDestroyed(HttpSessionEvent se)
{
destroyed = true;
}
@Override
public void sessionCreated(HttpSessionEvent se)
{
created = true;
}
}
public static class TestServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException
{
@ -179,16 +176,16 @@ public abstract class AbstractLastAccessTimeTest
sendResult(session, httpServletResponse.getWriter());
if (session!=null)
{
{
session.setAttribute("test", "test");
}
}
}
private void sendResult(HttpSession session, PrintWriter writer)
{
if (session != null)
{
{
writer.print(session.getAttribute("test"));
}
else

View File

@ -18,18 +18,13 @@
package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -41,6 +36,9 @@ import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* AbstractLightLoadTest
@ -79,8 +77,7 @@ public abstract class AbstractLightLoadTest
urls[0] = "http://localhost:" + port1 + contextPath + servletMapping;
urls[1] = "http://localhost:" + port2 + contextPath + servletMapping;
Future<ContentResponse> future = client.GET( urls[0] + "?action=init" );
ContentResponse response1 = future.get();
ContentResponse response1 = client.GET(urls[0] + "?action=init");
assertEquals(HttpServletResponse.SC_OK,response1.getStatus());
String sessionCookie = response1.getHeaders().getStringField( "Set-Cookie" );
assertTrue(sessionCookie != null);
@ -115,8 +112,7 @@ public abstract class AbstractLightLoadTest
// Perform one request to get the result
Request request = client.newRequest( urls[0] + "?action=result" );
request.header("Cookie", sessionCookie);
future = request.send();
ContentResponse response2 = future.get();
ContentResponse response2 = request.send();
assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
String response = response2.getContentAsString();
System.out.println( "get = " + response );
@ -151,7 +147,7 @@ public abstract class AbstractLightLoadTest
private final String sessionCookie;
private final String[] urls;
public Worker( CyclicBarrier barrier, int requestsCount, String sessionCookie, String[] urls )
{
@ -182,14 +178,13 @@ public abstract class AbstractLightLoadTest
barrier.await();
Random random = new Random( System.nanoTime() );
for ( int i = 0; i < requestsCount; ++i )
{
int urlIndex = random.nextInt( urls.length );
Request request = client.newRequest(urls[urlIndex] + "?action=increment");
request.header("Cookie", sessionCookie);
Future<ContentResponse> future = request.send();
ContentResponse response = future.get();
ContentResponse response = request.send();
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
}

View File

@ -18,12 +18,7 @@
package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.concurrent.Future;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -36,6 +31,9 @@ import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.SessionManager;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* AbstractLocalSessionScavengingTest
*/
@ -54,7 +52,7 @@ public abstract class AbstractLocalSessionScavengingTest
e.printStackTrace();
}
}
@Test
public void testLocalSessionsScavenging() throws Exception
{
@ -83,30 +81,27 @@ public abstract class AbstractLocalSessionScavengingTest
urls[1] = "http://localhost:" + port2 + contextPath + servletMapping;
// Create the session on node1
Future<ContentResponse> future = client.GET(urls[0] + "?action=init");
ContentResponse response1 = future.get();
ContentResponse response1 = client.GET(urls[0] + "?action=init");
assertEquals(HttpServletResponse.SC_OK,response1.getStatus());
String sessionCookie = response1.getHeaders().getStringField("Set-Cookie");
assertTrue(sessionCookie != null);
// Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
// Be sure the session is also present in node2
// Be sure the session is also present in node2
org.eclipse.jetty.client.api.Request request = client.newRequest(urls[1] + "?action=test");
request.header("Cookie", sessionCookie);
future = request.send();
ContentResponse response2 = future.get();
ContentResponse response2 = request.send();
assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
// Wait for the scavenger to run on node1, waiting 2.5 times the scavenger period
pause(scavengePeriod);
// Check that node1 does not have any local session cached
request = client.newRequest(urls[0] + "?action=check");
request.header("Cookie", sessionCookie);
future = request.send();
response1 = future.get();
response1 = request.send();
assertEquals(HttpServletResponse.SC_OK,response1.getStatus());
@ -117,8 +112,7 @@ public abstract class AbstractLocalSessionScavengingTest
// Check that node2 does not have any local session cached
request = client.newRequest(urls[1] + "?action=check");
request.header("Cookie", sessionCookie);
future = request.send();
response2 = future.get();
response2 = request.send();
assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
}
finally

View File

@ -18,12 +18,7 @@
package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.concurrent.Future;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -36,6 +31,9 @@ import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* AbstractNewSessionTest
*/
@ -54,7 +52,7 @@ public abstract class AbstractNewSessionTest
e.printStackTrace();
}
}
@Test
public void testNewSession() throws Exception
{
@ -72,8 +70,7 @@ public abstract class AbstractNewSessionTest
client.start();
try
{
Future<ContentResponse> future = client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=create");
ContentResponse response = future.get();
ContentResponse response = client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=create");
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
String sessionCookie = response.getHeaders().getStringField("Set-Cookie");
assertTrue(sessionCookie != null);
@ -87,8 +84,7 @@ public abstract class AbstractNewSessionTest
// The server creates a new session, we must ensure we released all locks
Request request = client.newRequest("http://localhost:" + port + contextPath + servletMapping + "?action=old-create");
request.header("Cookie", sessionCookie);
future = request.send();
response = future.get();
response = request.send();
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
}
finally

View File

@ -18,13 +18,8 @@
package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -36,6 +31,9 @@ import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* AbstractOrphanedSessionTest
*/
@ -73,8 +71,7 @@ public abstract class AbstractOrphanedSessionTest
try
{
// Connect to server1 to create a session and get its session cookie
Future<ContentResponse> future = client.GET("http://localhost:" + port1 + contextPath + servletMapping + "?action=init");
ContentResponse response1 = future.get();
ContentResponse response1 = client.GET("http://localhost:" + port1 + contextPath + servletMapping + "?action=init");
assertEquals(HttpServletResponse.SC_OK,response1.getStatus());
String sessionCookie = response1.getHeaders().getStringField("Set-Cookie");
assertTrue(sessionCookie != null);
@ -89,8 +86,7 @@ public abstract class AbstractOrphanedSessionTest
// Perform one request to server2 to be sure that the session has been expired
Request request = client.newRequest("http://localhost:" + port2 + contextPath + servletMapping + "?action=check");
request.header("Cookie", sessionCookie);
future = request.send();
ContentResponse response2 = future.get();
ContentResponse response2 = request.send();
assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
}
finally

View File

@ -18,12 +18,7 @@
package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.concurrent.Future;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -34,6 +29,9 @@ import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* AbstractReentrantRequestSessionTest
@ -57,8 +55,7 @@ public abstract class AbstractReentrantRequestSessionTest
client.start();
try
{
Future<ContentResponse> future = client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=reenter&port=" + port + "&path=" + contextPath + servletMapping);
ContentResponse response = future.get();
ContentResponse response = client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=reenter&port=" + port + "&path=" + contextPath + servletMapping);
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
}
finally
@ -88,12 +85,12 @@ public abstract class AbstractReentrantRequestSessionTest
String action = request.getParameter("action");
if ("reenter".equals(action))
{
if (session == null)
if (session == null)
session = request.getSession(true);
int port = Integer.parseInt(request.getParameter("port"));
String path = request.getParameter("path");
// We want to make another request
// We want to make another request
// while this request is still pending, to see if the locking is
// fine grained (per session at least).
try
@ -102,8 +99,7 @@ public abstract class AbstractReentrantRequestSessionTest
client.start();
try
{
Future<ContentResponse> future = client.GET("http://localhost:" + port + path + ";jsessionid="+session.getId()+"?action=none");
ContentResponse resp = future.get();
ContentResponse resp = client.GET("http://localhost:" + port + path + ";jsessionid="+session.getId()+"?action=none");
assertEquals(HttpServletResponse.SC_OK,resp.getStatus());
assertEquals("true",session.getAttribute("reentrant"));
}

View File

@ -18,14 +18,7 @@
package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.concurrent.Future;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -36,17 +29,20 @@ import javax.servlet.http.HttpSessionListener;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Destination;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.http.HttpCookie;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public abstract class AbstractRemoveSessionTest
{
public abstract AbstractTestServer createServer(int port, int max, int scavenge);
@Test
public void testRemoveSession() throws Exception
{
@ -66,8 +62,7 @@ public abstract class AbstractRemoveSessionTest
client.start();
try
{
Future<ContentResponse> future = client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=create");
ContentResponse response = future.get();
ContentResponse response = client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=create");
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
String sessionCookie = response.getHeaders().getStringField("Set-Cookie");
assertTrue(sessionCookie != null);
@ -76,22 +71,20 @@ public abstract class AbstractRemoveSessionTest
//ensure sessionCreated listener is called
assertTrue (testListener.isCreated());
//now delete the session
//now delete the session
Request request = client.newRequest("http://localhost:" + port + contextPath + servletMapping + "?action=delete");
request.header("Cookie", sessionCookie);
future = request.send();
response = future.get();
response = request.send();
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
//ensure sessionDestroyed listener is called
assertTrue(testListener.isDestroyed());
// The session is not there anymore, but we present an old cookie
// The server creates a new session, we must ensure we released all locks
request = client.newRequest("http://localhost:" + port + contextPath + servletMapping + "?action=check");
request.header("Cookie", sessionCookie);
future = request.send();
response = future.get();
response = request.send();
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
}
finally
@ -129,7 +122,7 @@ public abstract class AbstractRemoveSessionTest
}
}
}
public static class TestEventListener implements HttpSessionListener
{
boolean wasCreated;
@ -157,5 +150,5 @@ public abstract class AbstractRemoveSessionTest
}
}
}

View File

@ -18,13 +18,8 @@
package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.Collections;
import java.util.concurrent.Future;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
@ -38,6 +33,9 @@ import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* AbstractServerCrossContextSessionTest
*/
@ -45,7 +43,7 @@ public abstract class AbstractServerCrossContextSessionTest
{
public abstract AbstractTestServer createServer(int port);
@Test
public void testCrossContextDispatch() throws Exception
{
@ -66,8 +64,7 @@ public abstract class AbstractServerCrossContextSessionTest
try
{
// Perform a request, on server side a cross context dispatch will be done
Future<ContentResponse> future = client.GET("http://localhost:" + port + contextA + servletMapping);
ContentResponse response = future.get();
ContentResponse response = client.GET("http://localhost:" + port + contextA + servletMapping);
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
}
finally

View File

@ -19,9 +19,6 @@
package org.eclipse.jetty.server.session;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.Future;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -29,16 +26,13 @@ import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import junit.framework.Assert;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Destination;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.http.HttpCookie;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@ -60,7 +54,7 @@ public abstract class AbstractSessionCookieTest
e.printStackTrace();
}
}
@Test
@Ignore("failing because an http cookie with null value is coming over as \"null\"")
public void testSessionCookie() throws Exception
@ -79,29 +73,26 @@ public abstract class AbstractSessionCookieTest
client.start();
try
{
Future<ContentResponse> future = client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=create");
ContentResponse response = future.get();
ContentResponse response = client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=create");
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
String sessionCookie = response.getHeaders().getStringField("Set-Cookie");
assertTrue(sessionCookie != null);
// Mangle the cookie, replacing Path with $Path, etc.
//sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
// Let's wait for the scavenger to run, waiting 2.5 times the scavenger period
//pause(scavengePeriod);
//pause(scavengePeriod);
Request request = client.newRequest("http://localhost:" + port + contextPath + servletMapping + "?action=check-cookie");
request.header("Cookie", sessionCookie);
future = request.send();
response = future.get();
response = request.send();
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
request = client.newRequest("http://localhost:" + port + contextPath + servletMapping + "?action=null-cookie");
request.header("Cookie", sessionCookie);
future = request.send();
response = future.get();
response = request.send();
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
}
finally
@ -129,21 +120,21 @@ public abstract class AbstractSessionCookieTest
else if ("check-cookie".equals(action))
{
HttpSession session = request.getSession(false);
assertTrue(session != null);
//request.getSession(true);
}
else if ("null-cookie".equals(action))
{
HttpSession session = request.getSession(false);
assertEquals(1, request.getCookies().length);
Assert.assertFalse("null".equals(request.getCookies()[0].getValue()));
assertTrue(session == null);
}
else
{

View File

@ -18,12 +18,7 @@
package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.concurrent.Future;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -36,14 +31,9 @@ import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* AbstractSessionExpiryTest
*
*
*
*/
public abstract class AbstractSessionExpiryTest
{
public abstract AbstractTestServer createServer(int port, int max, int scavenge);
@ -59,7 +49,7 @@ public abstract class AbstractSessionExpiryTest
e.printStackTrace();
}
}
@Test
public void testSessionNotExpired() throws Exception
{
@ -81,27 +71,25 @@ public abstract class AbstractSessionExpiryTest
String url = "http://localhost:" + port1 + contextPath + servletMapping;
//make a request to set up a session on the server
Future<ContentResponse> future = client.GET(url + "?action=init");
ContentResponse response = future.get();
ContentResponse response = client.GET(url + "?action=init");
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
String sessionCookie = response.getHeaders().getStringField("Set-Cookie");
assertTrue(sessionCookie != null);
// Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
//now stop the server
server1.stop();
//start the server again, before the session times out
server1.start();
server1.start();
port1 = server1.getPort();
url = "http://localhost:" + port1 + contextPath + servletMapping;
//make another request, the session should not have expired
//make another request, the session should not have expired
Request request = client.newRequest(url + "?action=notexpired");
request.getHeaders().add("Cookie", sessionCookie);
future = request.send();
ContentResponse response2 = future.get();
ContentResponse response2 = request.send();
assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
}
@ -132,30 +120,28 @@ public abstract class AbstractSessionExpiryTest
String url = "http://localhost:" + port1 + contextPath + servletMapping;
//make a request to set up a session on the server
Future<ContentResponse> future = client.GET(url + "?action=init");
ContentResponse response1 = future.get();
ContentResponse response1 = client.GET(url + "?action=init");
assertEquals(HttpServletResponse.SC_OK,response1.getStatus());
String sessionCookie = response1.getHeaders().getStringField("Set-Cookie");
assertTrue(sessionCookie != null);
// Mangle the cookie, replacing Path with $Path, etc.
sessionCookie = sessionCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
//now stop the server
server1.stop();
//and wait until the expiry time has passed
pause(inactivePeriod);
//restart the server
server1.start();
server1.start();
port1 = server1.getPort();
url = "http://localhost:" + port1 + contextPath + servletMapping;
//make another request, the session should have expired
Request request = client.newRequest(url + "?action=test");
request.getHeaders().add("Cookie", sessionCookie);
future = request.send();
ContentResponse response2 = future.get();
ContentResponse response2 = request.send();
assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
}
finally
@ -167,8 +153,6 @@ public abstract class AbstractSessionExpiryTest
public static class TestServlet extends HttpServlet
{
public String originalId = null;
public String testId = null;
public String checkId = null;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException
@ -192,7 +176,7 @@ public abstract class AbstractSessionExpiryTest
assertTrue(session != null);
assertTrue(originalId.equals(session.getId()));
}
}
}
}

View File

@ -18,14 +18,9 @@
package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -43,11 +38,14 @@ import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* AbstractSessionInvalidateAndCreateTest
*
* This test verifies that invalidating an existing session and creating
* a new session within the scope of a single request will expire the
*
* This test verifies that invalidating an existing session and creating
* a new session within the scope of a single request will expire the
* newly created session correctly (removed from the server and session listeners called).
* See https://bugs.eclipse.org/bugs/show_bug.cgi?id=377610
*/
@ -56,24 +54,24 @@ public abstract class AbstractSessionInvalidateAndCreateTest
public class MySessionListener implements HttpSessionListener
{
List<String> destroys;
public void sessionCreated(HttpSessionEvent e)
{
}
public void sessionDestroyed(HttpSessionEvent e)
{
if (destroys == null)
destroys = new ArrayList<String>();
destroys = new ArrayList<>();
destroys.add((String)e.getSession().getAttribute("identity"));
}
}
public abstract AbstractTestServer createServer(int port, int max, int scavenge);
public void pause(int scavengePeriod)
{
@ -86,7 +84,7 @@ public abstract class AbstractSessionInvalidateAndCreateTest
e.printStackTrace();
}
}
@Test
public void testSessionScavenge() throws Exception
{
@ -113,8 +111,7 @@ public abstract class AbstractSessionInvalidateAndCreateTest
// Create the session
Future<ContentResponse> future = client.GET(url + "?action=init");
ContentResponse response1 = future.get();
ContentResponse response1 = client.GET(url + "?action=init");
assertEquals(HttpServletResponse.SC_OK,response1.getStatus());
String sessionCookie = response1.getHeaders().getStringField("Set-Cookie");
assertTrue(sessionCookie != null);
@ -125,8 +122,7 @@ public abstract class AbstractSessionInvalidateAndCreateTest
// Make a request which will invalidate the existing session and create a new one
Request request2 = client.newRequest(url + "?action=test");
request2.header("Cookie", sessionCookie);
future = request2.send();
ContentResponse response2 = future.get();
ContentResponse response2 = request2.send();
assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
// Wait for the scavenger to run, waiting 2.5 times the scavenger period
@ -169,21 +165,21 @@ public abstract class AbstractSessionInvalidateAndCreateTest
if (session != null)
{
session.invalidate();
//now make a new session
session = request.getSession(true);
session.setAttribute("identity", "session2");
session.setAttribute("listener", new HttpSessionBindingListener()
{
public void valueUnbound(HttpSessionBindingEvent event)
{
unbound = true;
}
public void valueBound(HttpSessionBindingEvent event)
{
}
});
}

View File

@ -20,22 +20,17 @@ package org.eclipse.jetty.server.session;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.Future;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Destination;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.http.HttpCookie;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@ -70,8 +65,7 @@ public abstract class AbstractSessionMigrationTest
// Perform one request to server1 to create a session
int value = 1;
Request request1 = client.POST("http://localhost:" + port1 + contextPath + servletMapping + "?action=set&value=" + value);
Future<ContentResponse> future = request1.send();
ContentResponse response1 = future.get();
ContentResponse response1 = request1.send();
assertEquals(HttpServletResponse.SC_OK,response1.getStatus());
String sessionCookie = response1.getHeaders().getStringField("Set-Cookie");
assertTrue(sessionCookie != null);
@ -82,8 +76,7 @@ public abstract class AbstractSessionMigrationTest
// This should migrate the session from server1 to server2.
Request request2 = client.newRequest("http://localhost:" + port2 + contextPath + servletMapping + "?action=get");
request2.header("Cookie", sessionCookie);
future = request2.send();
ContentResponse response2 = future.get();
ContentResponse response2 = request2.send();
assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
String response = response2.getContentAsString();
assertEquals(response.trim(),String.valueOf(value)); }
@ -129,7 +122,7 @@ public abstract class AbstractSessionMigrationTest
else if ("get".equals(action))
{
int value = (Integer)session.getAttribute("value");
int x = ((AbstractSession)session).getMaxInactiveInterval();
int x = session.getMaxInactiveInterval();
assertTrue(x > 0);
PrintWriter writer = response.getWriter();
writer.println(value);

View File

@ -19,8 +19,6 @@
package org.eclipse.jetty.server.session;
import java.io.IOException;
import java.util.concurrent.Future;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -32,18 +30,18 @@ import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.servlet.ServletContextHandler;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
public abstract class AbstractSessionRenewTest
{
public abstract AbstractTestServer createServer(int port, int max, int scavenge);
public void testSessionRenewal() throws Exception
{
String contextPath = "";
@ -61,8 +59,7 @@ public abstract class AbstractSessionRenewTest
client.start();
//make a request to create a session
Future<ContentResponse> future = client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=create");
ContentResponse response = future.get();
ContentResponse response = client.GET("http://localhost:" + port + contextPath + servletMapping + "?action=create");
assertEquals(HttpServletResponse.SC_OK,response.getStatus());
String sessionCookie = response.getHeaders().getStringField("Set-Cookie");
@ -71,20 +68,19 @@ public abstract class AbstractSessionRenewTest
//make a request to change the sessionid
Request request = client.newRequest("http://localhost:" + port + contextPath + servletMapping + "?action=renew");
request.header("Cookie", sessionCookie);
future = request.send();
ContentResponse renewResponse = future.get();
ContentResponse renewResponse = request.send();
assertEquals(HttpServletResponse.SC_OK,renewResponse.getStatus());
String renewSessionCookie = renewResponse.getHeaders().getStringField("Set-Cookie");
assertNotNull(renewSessionCookie);
assertNotSame(sessionCookie, renewSessionCookie);
}
finally
finally
{
client.stop();
}
}
public static class TestServlet extends HttpServlet
{
@Override
@ -99,30 +95,30 @@ public abstract class AbstractSessionRenewTest
else if ("renew".equals(action))
{
HttpSession beforeSession = request.getSession(false);
String beforeSessionId = beforeSession.getId();
assertTrue(beforeSession != null);
String beforeSessionId = beforeSession.getId();
((AbstractSession)beforeSession).renewId(request);
HttpSession afterSession = request.getSession(false);
String afterSessionId = afterSession.getId();
assertTrue(afterSession != null);
String afterSessionId = afterSession.getId();
assertTrue(beforeSession==afterSession);
assertTrue(beforeSessionId != afterSessionId);
assertFalse(beforeSessionId.equals(afterSessionId));
AbstractSessionManager sessionManager = (AbstractSessionManager)((AbstractSession)afterSession).getSessionManager();
AbstractSessionIdManager sessionIdManager = (AbstractSessionIdManager)sessionManager.getSessionIdManager();
assertTrue(sessionIdManager.idInUse(afterSessionId));
assertFalse(sessionIdManager.idInUse(beforeSessionId));
HttpSession session = sessionManager.getSession(afterSessionId);
assertNotNull(session);
session = sessionManager.getSession(beforeSessionId);
assertNull(session);
if (((AbstractSession)afterSession).isIdChanged())
{
((org.eclipse.jetty.server.Response)response).addCookie(sessionManager.getSessionCookie(afterSession, request.getContextPath(), request.isSecure()));
@ -130,5 +126,5 @@ public abstract class AbstractSessionRenewTest
}
}
}
}

View File

@ -18,13 +18,8 @@
package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.Future;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@ -36,6 +31,9 @@ import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* AbstractLastAccessTimeTest
@ -43,7 +41,7 @@ import org.junit.Test;
public abstract class AbstractSessionValueSavingTest
{
public abstract AbstractTestServer createServer(int port, int max, int scavenge);
@Test
public void testSessionValueSaving() throws Exception
{
@ -57,7 +55,7 @@ public abstract class AbstractSessionValueSavingTest
int port1=server1.getPort();
try
{
HttpClient client = new HttpClient();
client.start();
try
@ -65,14 +63,13 @@ public abstract class AbstractSessionValueSavingTest
long sessionTestValue = 0;
// Perform one request to server1 to create a session
Future<ContentResponse> future = client.GET("http://localhost:" + port1 + contextPath + servletMapping + "?action=init");
ContentResponse response1 = future.get();
assertEquals(HttpServletResponse.SC_OK, response1.getStatus());
ContentResponse response1 = client.GET("http://localhost:" + port1 + contextPath + servletMapping + "?action=init");
assertEquals(HttpServletResponse.SC_OK, response1.getStatus());
assertTrue(sessionTestValue < Long.parseLong(response1.getContentAsString()));
sessionTestValue = Long.parseLong(response1.getContentAsString());
String sessionCookie = response1.getHeaders().getStringField("Set-Cookie");
assertTrue( sessionCookie != null );
// Mangle the cookie, replacing Path with $Path, etc.
@ -84,23 +81,22 @@ public abstract class AbstractSessionValueSavingTest
// We want to test that optimizations done to the saving of the shared lastAccessTime
// do not break the correct working
int requestInterval = 500;
for (int i = 0; i < 10; ++i)
{
Request request2 = client.newRequest("http://localhost:" + port1 + contextPath + servletMapping);
request2.header("Cookie", sessionCookie);
future = request2.send();
ContentResponse response2 = future.get();
assertEquals(HttpServletResponse.SC_OK , response2.getStatus());
ContentResponse response2 = request2.send();
assertEquals(HttpServletResponse.SC_OK , response2.getStatus());
assertTrue(sessionTestValue < Long.parseLong(response2.getContentAsString()));
sessionTestValue = Long.parseLong(response2.getContentAsString());
String setCookie = response1.getHeaders().getStringField("Set-Cookie");
if (setCookie!=null)
if (setCookie!=null)
sessionCookie = setCookie.replaceFirst("(\\W)(P|p)ath=", "$1\\$Path=");
Thread.sleep(requestInterval);
}
@ -126,7 +122,7 @@ public abstract class AbstractSessionValueSavingTest
{
HttpSession session = request.getSession(true);
session.setAttribute("test", System.currentTimeMillis());
sendResult(session, httpServletResponse.getWriter());
}
else
@ -138,16 +134,16 @@ public abstract class AbstractSessionValueSavingTest
long value = System.currentTimeMillis();
System.out.println("Setting test to : " + value);
session.setAttribute("test", value);
}
sendResult(session, httpServletResponse.getWriter());
}
}
private void sendResult(HttpSession session, PrintWriter writer)
{
if (session != null)
@ -159,6 +155,6 @@ public abstract class AbstractSessionValueSavingTest
writer.print(0);
}
}
}
}

View File

@ -18,14 +18,9 @@
package org.eclipse.jetty.server.session;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.util.concurrent.Future;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.client.HttpClient;
@ -36,6 +31,9 @@ import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.resource.Resource;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* AbstractWebAppObjectInSessionTest
*
@ -114,9 +112,8 @@ public abstract class AbstractWebAppObjectInSessionTest
// Perform one request to server1 to create a session
Request request = client.newRequest("http://localhost:" + port1 + contextPath + servletMapping + "?action=set");
request.method(HttpMethod.GET);
Future<ContentResponse> future = request.send();
ContentResponse response = future.get();
ContentResponse response = request.send();
assertEquals( HttpServletResponse.SC_OK, response.getStatus());
String sessionCookie = response.getHeaders().getStringField("Set-Cookie");
assertTrue(sessionCookie != null);
@ -127,8 +124,7 @@ public abstract class AbstractWebAppObjectInSessionTest
Request request2 = client.newRequest("http://localhost:" + port2 + contextPath + servletMapping + "?action=get");
request2.method(HttpMethod.GET);
request2.header("Cookie", sessionCookie);
future = request2.send();
ContentResponse response2 = future.get();
ContentResponse response2 = request2.send();
assertEquals(HttpServletResponse.SC_OK,response2.getStatus());
}