Merge remote-tracking branch 'origin/master' into jetty-9-alpn

This commit is contained in:
Greg Wilkins 2014-03-31 09:59:52 +11:00
commit 28445fc629
49 changed files with 1319 additions and 1072 deletions

View File

@ -105,7 +105,6 @@ public class HttpClient extends ContainerLifeCycle
private static final Logger LOG = Log.getLogger(HttpClient.class);
private final ConcurrentMap<Origin, HttpDestination> destinations = new ConcurrentHashMap<>();
private final ConcurrentMap<Long, HttpConversation> conversations = new ConcurrentHashMap<>();
private final List<ProtocolHandler> handlers = new ArrayList<>();
private final List<Request.Listener> requestListeners = new ArrayList<>();
private final AuthenticationStore authenticationStore = new HttpAuthenticationStore();
@ -237,7 +236,6 @@ public class HttpClient extends ContainerLifeCycle
destination.close();
destinations.clear();
conversations.clear();
requestListeners.clear();
authenticationStore.clearAuthentications();
authenticationStore.clearAuthenticationResults();

View File

@ -43,7 +43,6 @@ public class HttpExchange
private final HttpResponse response;
private volatile Throwable requestFailure;
private volatile Throwable responseFailure;
public HttpExchange(HttpDestination destination, HttpRequest request, List<Response.ResponseListener> listeners)
{
@ -205,6 +204,7 @@ public class HttpExchange
{
if (update(0b0101, cause) == 0b0101)
{
LOG.debug("Failing {}: {}", this, cause);
destination.getRequestNotifier().notifyFailure(request, cause);
List<Response.ResponseListener> listeners = getConversation().getResponseListeners();
ResponseNotifier responseNotifier = destination.getResponseNotifier();

View File

@ -791,17 +791,8 @@ public abstract class HttpSender implements AsyncContentProvider.Listener
sendContent(exchange, content, this);
return Action.SCHEDULED;
}
else if (consumed)
{
sendContent(exchange, content, lastCallback);
return Action.IDLE;
}
else
{
throw new IllegalStateException();
}
}
break;
throw new IllegalStateException();
}
default:
{

View File

@ -102,9 +102,11 @@ public abstract class MultiplexHttpDestination<C extends Connection> extends Htt
Throwable cause = request.getAbortCause();
if (cause != null)
{
// If we have a non-null abort cause, it means that someone
// else has already aborted and notified, nothing do to here.
LOG.debug("Aborted before processing {}: {}", exchange, cause);
// It may happen that the request is aborted before the exchange
// is created. Aborting the exchange a second time will result in
// a no-operation, so we just abort here to cover that edge case.
exchange.abort(cause);
}
else
{

View File

@ -96,9 +96,6 @@ public abstract class PoolingHttpDestination<C extends Connection> extends HttpD
LOG.debug("Processing exchange {} on connection {}", exchange, connection);
if (exchange == null)
{
// TODO: review this part... may not be 100% correct
// TODO: e.g. is client is not running, there should be no need to close the connection
if (!connectionPool.release(connection))
connection.close();
@ -114,9 +111,11 @@ public abstract class PoolingHttpDestination<C extends Connection> extends HttpD
Throwable cause = request.getAbortCause();
if (cause != null)
{
// If we have a non-null abort cause, it means that someone
// else has already aborted and notified, nothing do to here.
LOG.debug("Aborted before processing {}: {}", exchange, cause);
// It may happen that the request is aborted before the exchange
// is created. Aborting the exchange a second time will result in
// a no-operation, so we just abort here to cover that edge case.
exchange.abort(cause);
}
else
{

View File

@ -58,13 +58,14 @@ public class TimeoutCompleteListener implements Response.CompleteListener, Runna
Scheduler.Task task = scheduler.schedule(this, timeout, TimeUnit.MILLISECONDS);
if (this.task.getAndSet(task) != null)
throw new IllegalStateException();
LOG.debug("Scheduled timeout task {} in {} ms", task, timeout);
LOG.debug("Scheduled timeout task {} in {} ms for {}", task, timeout, request);
return true;
}
@Override
public void run()
{
LOG.debug("Executing timeout task {} for {}", task, request);
request.abort(new TimeoutException("Total timeout elapsed"));
}
}

View File

@ -34,14 +34,12 @@ import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static junit.framework.Assert.fail;
import static org.hamcrest.Matchers.instanceOf;
import static org.junit.Assert.assertThat;
/**
* This test class runs tests to make sure that hostname verification (http://www.ietf.org/rfc/rfc2818.txt
* section 3.1) is configurable in SslContextFactory and works as expected.
@ -106,7 +104,7 @@ public class HostnameVerificationTest
try
{
client.GET(uri);
fail("sending request to client should have failed with an Exception!");
Assert.fail("sending request to client should have failed with an Exception!");
}
catch (ExecutionException x)
{
@ -119,9 +117,9 @@ public class HostnameVerificationTest
// ExecutionException wraps an SSLHandshakeException
Throwable cause = x.getCause();
if (cause instanceof SSLHandshakeException)
assertThat(cause.getCause().getCause(), instanceOf(CertificateException.class));
Assert.assertThat(cause.getCause().getCause(), Matchers.instanceOf(CertificateException.class));
else
assertThat(cause.getCause(), instanceOf(ClosedChannelException.class));
Assert.assertThat(cause.getCause(), Matchers.instanceOf(ClosedChannelException.class));
}
}
@ -142,7 +140,7 @@ public class HostnameVerificationTest
}
catch (ExecutionException e)
{
fail("SSLHandshake should work just fine as hostname verification is disabled! " + e.getMessage());
Assert.fail("SSLHandshake should work just fine as hostname verification is disabled! " + e.getMessage());
}
}
@ -163,7 +161,7 @@ public class HostnameVerificationTest
}
catch (ExecutionException e)
{
fail("SSLHandshake should work just fine as hostname verification is disabled! " + e.getMessage());
Assert.fail("SSLHandshake should work just fine as hostname verification is disabled! " + e.getMessage());
}
}
}

View File

@ -364,6 +364,27 @@ public class HttpClientTimeoutTest extends AbstractHttpClientServerTest
Assert.assertNotNull(request.getAbortCause());
}
@Test
public void testVeryShortTimeout() throws Exception
{
start(new EmptyServerHandler());
final CountDownLatch latch = new CountDownLatch(1);
client.newRequest("localhost", connector.getLocalPort())
.scheme(scheme)
.timeout(1, TimeUnit.MILLISECONDS) // Very short timeout
.send(new Response.CompleteListener()
{
@Override
public void onComplete(Result result)
{
latch.countDown();
}
});
Assert.assertTrue(latch.await(5, TimeUnit.SECONDS));
}
private void assumeConnectTimeout(String host, int port, int connectTimeout) throws IOException
{
try (Socket socket = new Socket())

View File

@ -18,20 +18,15 @@
package org.eclipse.jetty.http;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.matchers.JUnitMatchers.containsString;
import java.nio.ByteBuffer;
import org.eclipse.jetty.util.BufferUtil;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
public class HttpGeneratorClientTest
{
public final static String CONTENT="The quick brown fox jumped over the lazy dog.\nNow is the time for all good men to come to the aid of the party\nThe moon is blue to a fish in love.\n";
public final static String[] connect={null,"keep-alive","close"};
class Info extends HttpGenerator.RequestInfo
@ -55,33 +50,33 @@ public class HttpGeneratorClientTest
HttpGenerator.Result
result=gen.generateRequest(null,null,null,null, true);
assertEquals(HttpGenerator.Result.NEED_INFO,result);
assertEquals(HttpGenerator.State.START,gen.getState());
Assert.assertEquals(HttpGenerator.Result.NEED_INFO, result);
Assert.assertEquals(HttpGenerator.State.START, gen.getState());
Info info = new Info("GET","/index.html");
info.getHttpFields().add("Host","something");
info.getHttpFields().add("User-Agent","test");
assertTrue(!gen.isChunking());
Assert.assertTrue(!gen.isChunking());
result=gen.generateRequest(info,null,null,null, true);
assertEquals(HttpGenerator.Result.NEED_HEADER,result);
assertEquals(HttpGenerator.State.START,gen.getState());
Assert.assertEquals(HttpGenerator.Result.NEED_HEADER, result);
Assert.assertEquals(HttpGenerator.State.START, gen.getState());
result=gen.generateRequest(info,header,null,null, true);
assertEquals(HttpGenerator.Result.FLUSH,result);
assertEquals(HttpGenerator.State.COMPLETING,gen.getState());
assertTrue(!gen.isChunking());
Assert.assertEquals(HttpGenerator.Result.FLUSH, result);
Assert.assertEquals(HttpGenerator.State.COMPLETING, gen.getState());
Assert.assertTrue(!gen.isChunking());
String out = BufferUtil.toString(header);
BufferUtil.clear(header);
result=gen.generateResponse(null,null,null,null, false);
assertEquals(HttpGenerator.Result.DONE,result);
assertEquals(HttpGenerator.State.END,gen.getState());
assertTrue(!gen.isChunking());
Assert.assertEquals(HttpGenerator.Result.DONE, result);
Assert.assertEquals(HttpGenerator.State.END, gen.getState());
Assert.assertTrue(!gen.isChunking());
assertEquals(0,gen.getContentPrepared());
assertThat(out,containsString("GET /index.html HTTP/1.1"));
assertThat(out,not(containsString("Content-Length")));
Assert.assertEquals(0, gen.getContentPrepared());
Assert.assertThat(out, Matchers.containsString("GET /index.html HTTP/1.1"));
Assert.assertThat(out, Matchers.not(Matchers.containsString("Content-Length")));
}
@ -95,38 +90,38 @@ public class HttpGeneratorClientTest
HttpGenerator.Result
result=gen.generateRequest(null,null,null,content0, true);
assertEquals(HttpGenerator.Result.NEED_INFO,result);
assertEquals(HttpGenerator.State.START,gen.getState());
Assert.assertEquals(HttpGenerator.Result.NEED_INFO, result);
Assert.assertEquals(HttpGenerator.State.START, gen.getState());
Info info = new Info("POST","/index.html");
info.getHttpFields().add("Host","something");
info.getHttpFields().add("User-Agent","test");
result=gen.generateRequest(info,null,null,content0, true);
assertEquals(HttpGenerator.Result.NEED_HEADER,result);
assertEquals(HttpGenerator.State.START,gen.getState());
Assert.assertEquals(HttpGenerator.Result.NEED_HEADER, result);
Assert.assertEquals(HttpGenerator.State.START, gen.getState());
result=gen.generateRequest(info,header,null,content0, true);
assertEquals(HttpGenerator.Result.FLUSH,result);
assertEquals(HttpGenerator.State.COMPLETING,gen.getState());
assertTrue(!gen.isChunking());
Assert.assertEquals(HttpGenerator.Result.FLUSH, result);
Assert.assertEquals(HttpGenerator.State.COMPLETING, gen.getState());
Assert.assertTrue(!gen.isChunking());
out = BufferUtil.toString(header);
BufferUtil.clear(header);
out+=BufferUtil.toString(content0);
BufferUtil.clear(content0);
result=gen.generateResponse(null,null,null,null, false);
assertEquals(HttpGenerator.Result.DONE,result);
assertEquals(HttpGenerator.State.END,gen.getState());
assertTrue(!gen.isChunking());
Assert.assertEquals(HttpGenerator.Result.DONE, result);
Assert.assertEquals(HttpGenerator.State.END, gen.getState());
Assert.assertTrue(!gen.isChunking());
assertThat(out,containsString("POST /index.html HTTP/1.1"));
assertThat(out,containsString("Host: something"));
assertThat(out,containsString("Content-Length: 58"));
assertThat(out,containsString("Hello World. The quick brown fox jumped over the lazy dog."));
Assert.assertThat(out, Matchers.containsString("POST /index.html HTTP/1.1"));
Assert.assertThat(out, Matchers.containsString("Host: something"));
Assert.assertThat(out, Matchers.containsString("Content-Length: 58"));
Assert.assertThat(out, Matchers.containsString("Hello World. The quick brown fox jumped over the lazy dog."));
assertEquals(58,gen.getContentPrepared());
Assert.assertEquals(58, gen.getContentPrepared());
}
@Test
@ -141,63 +136,63 @@ public class HttpGeneratorClientTest
HttpGenerator.Result
result=gen.generateRequest(null,null,null,content0, false);
assertEquals(HttpGenerator.Result.NEED_INFO,result);
assertEquals(HttpGenerator.State.START,gen.getState());
Assert.assertEquals(HttpGenerator.Result.NEED_INFO, result);
Assert.assertEquals(HttpGenerator.State.START, gen.getState());
Info info = new Info("POST","/index.html");
info.getHttpFields().add("Host","something");
info.getHttpFields().add("User-Agent","test");
result=gen.generateRequest(info,null,null,content0, false);
assertEquals(HttpGenerator.Result.NEED_HEADER,result);
assertEquals(HttpGenerator.State.START,gen.getState());
Assert.assertEquals(HttpGenerator.Result.NEED_HEADER, result);
Assert.assertEquals(HttpGenerator.State.START, gen.getState());
result=gen.generateRequest(info,header,null,content0, false);
assertEquals(HttpGenerator.Result.FLUSH,result);
assertEquals(HttpGenerator.State.COMMITTED,gen.getState());
assertTrue(gen.isChunking());
Assert.assertEquals(HttpGenerator.Result.FLUSH, result);
Assert.assertEquals(HttpGenerator.State.COMMITTED, gen.getState());
Assert.assertTrue(gen.isChunking());
out = BufferUtil.toString(header);
BufferUtil.clear(header);
out+=BufferUtil.toString(content0);
BufferUtil.clear(content0);
result=gen.generateRequest(null,header,null,content1, false);
assertEquals(HttpGenerator.Result.NEED_CHUNK,result);
assertEquals(HttpGenerator.State.COMMITTED,gen.getState());
Assert.assertEquals(HttpGenerator.Result.NEED_CHUNK, result);
Assert.assertEquals(HttpGenerator.State.COMMITTED, gen.getState());
result=gen.generateRequest(null,null,chunk,content1, false);
assertEquals(HttpGenerator.Result.FLUSH,result);
assertEquals(HttpGenerator.State.COMMITTED,gen.getState());
assertTrue(gen.isChunking());
Assert.assertEquals(HttpGenerator.Result.FLUSH, result);
Assert.assertEquals(HttpGenerator.State.COMMITTED, gen.getState());
Assert.assertTrue(gen.isChunking());
out+=BufferUtil.toString(chunk);
BufferUtil.clear(chunk);
out+=BufferUtil.toString(content1);
BufferUtil.clear(content1);
result=gen.generateResponse(null,null,chunk,null, true);
assertEquals(HttpGenerator.Result.CONTINUE,result);
assertEquals(HttpGenerator.State.COMPLETING,gen.getState());
assertTrue(gen.isChunking());
Assert.assertEquals(HttpGenerator.Result.CONTINUE, result);
Assert.assertEquals(HttpGenerator.State.COMPLETING, gen.getState());
Assert.assertTrue(gen.isChunking());
result=gen.generateResponse(null,null,chunk,null, true);
assertEquals(HttpGenerator.Result.FLUSH,result);
assertEquals(HttpGenerator.State.COMPLETING,gen.getState());
Assert.assertEquals(HttpGenerator.Result.FLUSH, result);
Assert.assertEquals(HttpGenerator.State.COMPLETING, gen.getState());
out+=BufferUtil.toString(chunk);
BufferUtil.clear(chunk);
assertTrue(!gen.isChunking());
Assert.assertTrue(!gen.isChunking());
result=gen.generateResponse(null,null,chunk,null, true);
assertEquals(HttpGenerator.Result.DONE,result);
assertEquals(HttpGenerator.State.END,gen.getState());
Assert.assertEquals(HttpGenerator.Result.DONE, result);
Assert.assertEquals(HttpGenerator.State.END, gen.getState());
assertThat(out,containsString("POST /index.html HTTP/1.1"));
assertThat(out,containsString("Host: something"));
assertThat(out,containsString("Transfer-Encoding: chunked"));
assertThat(out,containsString("\r\nD\r\nHello World. \r\n"));
assertThat(out,containsString("\r\n2D\r\nThe quick brown fox jumped over the lazy dog.\r\n"));
assertThat(out,containsString("\r\n0\r\n\r\n"));
Assert.assertThat(out, Matchers.containsString("POST /index.html HTTP/1.1"));
Assert.assertThat(out, Matchers.containsString("Host: something"));
Assert.assertThat(out, Matchers.containsString("Transfer-Encoding: chunked"));
Assert.assertThat(out, Matchers.containsString("\r\nD\r\nHello World. \r\n"));
Assert.assertThat(out, Matchers.containsString("\r\n2D\r\nThe quick brown fox jumped over the lazy dog.\r\n"));
Assert.assertThat(out, Matchers.containsString("\r\n0\r\n\r\n"));
assertEquals(58,gen.getContentPrepared());
Assert.assertEquals(58, gen.getContentPrepared());
}
@ -213,50 +208,50 @@ public class HttpGeneratorClientTest
HttpGenerator.Result
result=gen.generateRequest(null,null,null,content0, false);
assertEquals(HttpGenerator.Result.NEED_INFO,result);
assertEquals(HttpGenerator.State.START,gen.getState());
Assert.assertEquals(HttpGenerator.Result.NEED_INFO, result);
Assert.assertEquals(HttpGenerator.State.START, gen.getState());
Info info = new Info("POST","/index.html",58);
info.getHttpFields().add("Host","something");
info.getHttpFields().add("User-Agent","test");
result=gen.generateRequest(info,null,null,content0, false);
assertEquals(HttpGenerator.Result.NEED_HEADER,result);
assertEquals(HttpGenerator.State.START,gen.getState());
Assert.assertEquals(HttpGenerator.Result.NEED_HEADER, result);
Assert.assertEquals(HttpGenerator.State.START, gen.getState());
result=gen.generateRequest(info,header,null,content0, false);
assertEquals(HttpGenerator.Result.FLUSH,result);
assertEquals(HttpGenerator.State.COMMITTED,gen.getState());
assertTrue(!gen.isChunking());
Assert.assertEquals(HttpGenerator.Result.FLUSH, result);
Assert.assertEquals(HttpGenerator.State.COMMITTED, gen.getState());
Assert.assertTrue(!gen.isChunking());
out = BufferUtil.toString(header);
BufferUtil.clear(header);
out+=BufferUtil.toString(content0);
BufferUtil.clear(content0);
result=gen.generateRequest(null,null,null,content1, false);
assertEquals(HttpGenerator.Result.FLUSH,result);
assertEquals(HttpGenerator.State.COMMITTED,gen.getState());
assertTrue(!gen.isChunking());
Assert.assertEquals(HttpGenerator.Result.FLUSH, result);
Assert.assertEquals(HttpGenerator.State.COMMITTED, gen.getState());
Assert.assertTrue(!gen.isChunking());
out+=BufferUtil.toString(content1);
BufferUtil.clear(content1);
result=gen.generateResponse(null,null,null,null, true);
assertEquals(HttpGenerator.Result.CONTINUE,result);
assertEquals(HttpGenerator.State.COMPLETING,gen.getState());
assertTrue(!gen.isChunking());
Assert.assertEquals(HttpGenerator.Result.CONTINUE, result);
Assert.assertEquals(HttpGenerator.State.COMPLETING, gen.getState());
Assert.assertTrue(!gen.isChunking());
result=gen.generateResponse(null,null,null,null, true);
assertEquals(HttpGenerator.Result.DONE,result);
assertEquals(HttpGenerator.State.END,gen.getState());
Assert.assertEquals(HttpGenerator.Result.DONE, result);
Assert.assertEquals(HttpGenerator.State.END, gen.getState());
out+=BufferUtil.toString(chunk);
BufferUtil.clear(chunk);
assertThat(out,containsString("POST /index.html HTTP/1.1"));
assertThat(out,containsString("Host: something"));
assertThat(out,containsString("Content-Length: 58"));
assertThat(out,containsString("\r\n\r\nHello World. The quick brown fox jumped over the lazy dog."));
Assert.assertThat(out, Matchers.containsString("POST /index.html HTTP/1.1"));
Assert.assertThat(out, Matchers.containsString("Host: something"));
Assert.assertThat(out, Matchers.containsString("Content-Length: 58"));
Assert.assertThat(out, Matchers.containsString("\r\n\r\nHello World. The quick brown fox jumped over the lazy dog."));
assertEquals(58,gen.getContentPrepared());
Assert.assertEquals(58, gen.getContentPrepared());
}

View File

@ -21,12 +21,14 @@ package org.eclipse.jetty.io;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.thread.NonBlockingThread;
/**
* <p>A convenience base implementation of {@link Connection}.</p>
@ -87,6 +89,33 @@ public abstract class AbstractConnection implements Connection
return _executor;
}
protected void failedCallback(final Callback callback, final Throwable x)
{
if (NonBlockingThread.isNonBlockingThread())
{
try
{
getExecutor().execute(new Runnable()
{
@Override
public void run()
{
callback.failed(x);
}
});
}
catch(RejectedExecutionException e)
{
LOG.debug(e);
callback.failed(x);
}
}
else
{
callback.failed(x);
}
}
/**
* <p>Utility method to be called to register read interest.</p>
* <p>After a call to this method, {@link #onFillable()} or {@link #onFillInterestedFailed(Throwable)}

View File

@ -143,9 +143,10 @@ public abstract class AbstractEndPoint extends IdleTimeout implements EndPoint
protected void onIdleExpired(TimeoutException timeout)
{
boolean output_shutdown=isOutputShutdown();
boolean input_shutdown=isInputShutdown();
_fillInterest.onFail(timeout);
_writeFlusher.onFail(timeout);
if (output_shutdown)
if (isOpen() && output_shutdown || input_shutdown)
close();
}

View File

@ -46,6 +46,7 @@ import org.eclipse.jetty.util.component.ContainerLifeCycle;
import org.eclipse.jetty.util.component.Dumpable;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.thread.NonBlockingThread;
import org.eclipse.jetty.util.thread.Scheduler;
/**
@ -66,7 +67,7 @@ public abstract class SelectorManager extends AbstractLifeCycle implements Dumpa
private final ManagedSelector[] _selectors;
private long _connectTimeout = DEFAULT_CONNECT_TIMEOUT;
private long _selectorIndex;
protected SelectorManager(Executor executor, Scheduler scheduler)
{
this(executor, scheduler, (Runtime.getRuntime().availableProcessors() + 1) / 2);
@ -203,7 +204,7 @@ public abstract class SelectorManager extends AbstractLifeCycle implements Dumpa
ManagedSelector selector = newSelector(i);
_selectors[i] = selector;
selector.start();
execute(selector);
execute(new NonBlockingThread(selector));
}
}

View File

@ -23,6 +23,7 @@ import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.util.Arrays;
import java.util.concurrent.Executor;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
@ -300,17 +301,22 @@ public class SslConnection extends AbstractConnection
final boolean filler_failed=fail_filler;
getExecutor().execute(new Runnable()
failedCallback(new Callback()
{
@Override
public void run()
{
public void succeeded()
{
}
@Override
public void failed(Throwable x)
{
if (filler_failed)
getFillInterest().onFail(x);
getWriteFlusher().onFail(x);
}
});
},x);
}
};

View File

@ -26,7 +26,7 @@ import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.eclipse.jetty.toolchain.test.annotation.Slow;
import org.eclipse.jetty.util.Callback;
@ -64,11 +64,7 @@ public class SelectorManagerTest
server.bind(new InetSocketAddress("localhost", 0));
SocketAddress address = server.getLocalAddress();
SocketChannel client = SocketChannel.open();
client.configureBlocking(false);
client.connect(address);
final AtomicBoolean timeoutConnection = new AtomicBoolean();
final AtomicLong timeoutConnection = new AtomicLong();
final long connectTimeout = 1000;
SelectorManager selectorManager = new SelectorManager(executor, scheduler)
{
@ -83,8 +79,9 @@ public class SelectorManagerTest
{
try
{
if (timeoutConnection.get())
TimeUnit.MILLISECONDS.sleep(connectTimeout * 2);
long timeout = timeoutConnection.get();
if (timeout > 0)
TimeUnit.MILLISECONDS.sleep(timeout);
return super.finishConnect(channel);
}
catch (InterruptedException e)
@ -96,6 +93,7 @@ public class SelectorManagerTest
@Override
public Connection newConnection(SocketChannel channel, EndPoint endpoint, Object attachment) throws IOException
{
((Callback)attachment).succeeded();
return new AbstractConnection(endpoint, executor)
{
@Override
@ -116,9 +114,13 @@ public class SelectorManagerTest
try
{
timeoutConnection.set(true);
SocketChannel client1 = SocketChannel.open();
client1.configureBlocking(false);
client1.connect(address);
long timeout = connectTimeout * 2;
timeoutConnection.set(timeout);
final CountDownLatch latch1 = new CountDownLatch(1);
selectorManager.connect(client, new Callback.Adapter()
selectorManager.connect(client1, new Callback.Adapter()
{
@Override
public void failed(Throwable x)
@ -127,19 +129,29 @@ public class SelectorManagerTest
}
});
Assert.assertTrue(latch1.await(connectTimeout * 3, TimeUnit.MILLISECONDS));
Assert.assertFalse(client1.isOpen());
// Verify that after the failure we can connect successfully
timeoutConnection.set(false);
final CountDownLatch latch2 = new CountDownLatch(1);
selectorManager.connect(client, new Callback.Adapter()
// Wait for the first connect to finish, as the selector thread is waiting in finishConnect().
Thread.sleep(timeout);
// Verify that after the failure we can connect successfully.
try (SocketChannel client2 = SocketChannel.open())
{
@Override
public void failed(Throwable x)
client2.configureBlocking(false);
client2.connect(address);
timeoutConnection.set(0);
final CountDownLatch latch2 = new CountDownLatch(1);
selectorManager.connect(client2, new Callback.Adapter()
{
latch2.countDown();
}
});
Assert.assertTrue(latch2.await(connectTimeout, TimeUnit.MILLISECONDS));
@Override
public void succeeded()
{
latch2.countDown();
}
});
Assert.assertTrue(latch2.await(connectTimeout * 5, TimeUnit.MILLISECONDS));
Assert.assertTrue(client2.isOpen());
}
}
finally
{

View File

@ -18,12 +18,8 @@
package org.eclipse.jetty.security;
import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.containsString;
import java.io.IOException;
import java.util.Arrays;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -42,13 +38,12 @@ import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.util.security.Constraint;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* @version $Revision: 1441 $ $Date: 2010-04-02 12:28:17 +0200 (Fri, 02 Apr 2010) $
*/
public class DataConstraintsTest
{
private Server _server;
@ -134,15 +129,15 @@ public class DataConstraintsTest
String response;
response = _connector.getResponses("GET /ctx/some/thing HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 404 Not Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found"));
response = _connector.getResponses("GET /ctx/integral/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 302 Found"));
assertThat(response, containsString("Location: BWTP://"));
assertThat(response, containsString(":9999"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 302 Found"));
Assert.assertThat(response, Matchers.containsString("Location: BWTP://"));
Assert.assertThat(response, Matchers.containsString(":9999"));
response = _connectorS.getResponses("GET /ctx/integral/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 404 Not Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found"));
}
@ -166,15 +161,15 @@ public class DataConstraintsTest
String response;
response = _connector.getResponses("GET /ctx/some/thing HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 404 Not Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found"));
response = _connector.getResponses("GET /ctx/confid/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 302 Found"));
assertThat(response, containsString("Location: BWTP://"));
assertThat(response, containsString(":9999"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 302 Found"));
Assert.assertThat(response, Matchers.containsString("Location: BWTP://"));
Assert.assertThat(response, Matchers.containsString(":9999"));
response = _connectorS.getResponses("GET /ctx/confid/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 404 Not Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found"));
}
@ -198,10 +193,10 @@ public class DataConstraintsTest
String response;
response = _connector.getResponses("GET /ctx/confid/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 302 Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 302 Found"));
response = _connectorS.getResponses("GET /ctx/confid/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 404 Not Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found"));
}
@ -226,16 +221,16 @@ public class DataConstraintsTest
String response;
response = _connector.getResponses("GET /ctx/confid/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 404 Not Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found"));
response = _connectorS.getResponses("GET /ctx/confid/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 404 Not Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found"));
response = _connector.getResponses("POST /ctx/confid/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 302 Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 302 Found"));
response = _connectorS.getResponses("POST /ctx/confid/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 404 Not Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found"));
}
@Test
@ -260,16 +255,16 @@ public class DataConstraintsTest
String response;
response = _connector.getResponses("GET /ctx/confid/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 404 Not Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found"));
response = _connectorS.getResponses("GET /ctx/confid/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 404 Not Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found"));
response = _connector.getResponses("POST /ctx/confid/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 302 Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 302 Found"));
response = _connectorS.getResponses("POST /ctx/confid/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 404 Not Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found"));
}
@ -299,25 +294,25 @@ public class DataConstraintsTest
String response;
response = _connector.getResponses("GET /ctx/confid/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 404 Not Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found"));
response = _connectorS.getResponses("GET /ctx/confid/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 404 Not Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found"));
response = _connector.getResponses("POST /ctx/confid/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 302 Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 302 Found"));
response = _connectorS.getResponses("POST /ctx/confid/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 401 Unauthorized"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 401 Unauthorized"));
response = _connector.getResponses("GET /ctx/confid/info HTTP/1.0\r\nAuthorization: Basic YWRtaW46cGFzc3dvcmQ=\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 404 Not Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found"));
response = _connector.getResponses("POST /ctx/confid/info HTTP/1.0\r\nAuthorization: Basic YWRtaW46cGFzc3dvcmQ=\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 302 Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 302 Found"));
response = _connectorS.getResponses("POST /ctx/confid/info HTTP/1.0\r\nAuthorization: Basic YWRtaW46cGFzc3dvcmQ=\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 404 Not Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found"));
}
@ -341,16 +336,16 @@ public class DataConstraintsTest
String response;
response = _connector.getResponses("GET /ctx/restricted/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 403 Forbidden"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden"));
response = _connectorS.getResponses("GET /ctx/restricted/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 403 Forbidden"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden"));
response = _connector.getResponses("GET /ctx/restricted/info HTTP/1.0\r\nAuthorization: Basic YWRtaW46cGFzc3dvcmQ=\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 403 Forbidden"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden"));
response = _connectorS.getResponses("GET /ctx/restricted/info HTTP/1.0\r\nAuthorization: Basic YWRtaW46cGFzc3dvcmQ=\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 403 Forbidden"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden"));
}
@ -375,16 +370,16 @@ public class DataConstraintsTest
String response;
response = _connector.getResponses("GET /ctx/restricted/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 403 Forbidden"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden"));
response = _connectorS.getResponses("GET /ctx/restricted/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 403 Forbidden"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden"));
response = _connector.getResponses("GET /ctx/restricted/info HTTP/1.0\r\n Authorization: Basic YWRtaW46cGFzc3dvcmQ=\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 403 Forbidden"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden"));
response = _connectorS.getResponses("GET /ctx/restricted/info HTTP/1.0\r\n Authorization: Basic YWRtaW46cGFzc3dvcmQ=\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 403 Forbidden"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 403 Forbidden"));
}
@ -413,16 +408,16 @@ public class DataConstraintsTest
String response;
response = _connector.getResponses("GET /ctx/restricted/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 401 Unauthorized"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 401 Unauthorized"));
response = _connectorS.getResponses("GET /ctx/restricted/info HTTP/1.0\r\n\r\n");
assertThat(response, containsString("HTTP/1.1 401 Unauthorized"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 401 Unauthorized"));
response = _connector.getResponses("GET /ctx/restricted/info HTTP/1.0\nAuthorization: Basic YWRtaW46cGFzc3dvcmQ=\n\n");
assertThat(response, containsString("HTTP/1.1 404 Not Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found"));
response = _connectorS.getResponses("GET /ctx/restricted/info HTTP/1.0\nAuthorization: Basic YWRtaW46cGFzc3dvcmQ=\n\n");
assertThat(response, containsString("HTTP/1.1 404 Not Found"));
Assert.assertThat(response, Matchers.containsString("HTTP/1.1 404 Not Found"));
}

View File

@ -20,7 +20,6 @@ package org.eclipse.jetty.server;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

View File

@ -49,9 +49,8 @@ import org.eclipse.jetty.io.EofException;
import org.eclipse.jetty.server.HttpChannelState.Action;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.util.BlockingCallback;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.SharedBlockingCallback.Blocker;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
@ -728,10 +727,12 @@ public class HttpChannel<T> implements HttpParser.RequestHandler<T>, Runnable
protected boolean sendResponse(ResponseInfo info, ByteBuffer content, boolean complete) throws IOException
{
BlockingCallback writeBlock = _response.getHttpOutput().acquireWriteBlockingCallback();
boolean committing=sendResponse(info,content,complete,writeBlock);
writeBlock.block();
return committing;
try(Blocker blocker = _response.getHttpOutput().acquireWriteBlockingCallback())
{
boolean committing = sendResponse(info,content,complete,blocker);
blocker.block();
return committing;
}
}
public boolean isCommitted()

View File

@ -609,22 +609,7 @@ public class HttpConnection extends AbstractConnection implements Runnable, Http
public void failed(final Throwable x)
{
super.failed(x);
try
{
getExecutor().execute(new Runnable()
{
@Override
public void run()
{
_callback.failed(x);
}
});
}
catch(RejectedExecutionException e)
{
LOG.debug(e);
_callback.failed(x);
}
failedCallback(_callback,x);
}
}
@ -720,22 +705,7 @@ public class HttpConnection extends AbstractConnection implements Runnable, Http
public void failed(final Throwable x)
{
super.failed(x);
try
{
getExecutor().execute(new Runnable()
{
@Override
public void run()
{
_callback.failed(x);
}
});
}
catch (RejectedExecutionException e)
{
LOG.debug(e);
_callback.failed(x);
}
failedCallback(_callback,x);
}
}

View File

@ -20,6 +20,7 @@ package org.eclipse.jetty.server;
import java.io.IOException;
import java.util.Objects;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;

View File

@ -24,6 +24,7 @@ import java.nio.ByteBuffer;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.SharedBlockingCallback;
import org.eclipse.jetty.util.SharedBlockingCallback.Blocker;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
@ -57,10 +58,12 @@ public class HttpInputOverHTTP extends HttpInput<ByteBuffer> implements Callback
{
while(true)
{
_readBlocker.acquire();
_httpConnection.fillInterested(_readBlocker);
LOG.debug("{} block readable on {}",this,_readBlocker);
_readBlocker.block();
try (Blocker blocker=_readBlocker.acquire())
{
_httpConnection.fillInterested(blocker);
LOG.debug("{} block readable on {}",this,blocker);
blocker.block();
}
Object content=getNextContent();
if (content!=null || isFinished())

View File

@ -33,12 +33,12 @@ import javax.servlet.WriteListener;
import org.eclipse.jetty.http.HttpContent;
import org.eclipse.jetty.io.EofException;
import org.eclipse.jetty.util.BlockingCallback;
import org.eclipse.jetty.util.SharedBlockingCallback;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.IteratingCallback;
import org.eclipse.jetty.util.IteratingNestedCallback;
import org.eclipse.jetty.util.SharedBlockingCallback;
import org.eclipse.jetty.util.SharedBlockingCallback.Blocker;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
@ -116,17 +116,18 @@ public class HttpOutput extends ServletOutputStream implements Runnable
return _channel.getResponse().isAllContentWritten(_written);
}
protected BlockingCallback acquireWriteBlockingCallback() throws IOException
protected Blocker acquireWriteBlockingCallback() throws IOException
{
_writeblock.acquire();
return _writeblock;
return _writeblock.acquire();
}
protected void write(ByteBuffer content, boolean complete) throws IOException
{
_writeblock.acquire();
write(content,complete,_writeblock);
_writeblock.block();
try (Blocker blocker=_writeblock.acquire())
{
write(content,complete,blocker);
blocker.block();
}
}
protected void write(ByteBuffer content, boolean complete, Callback callback)
@ -439,9 +440,11 @@ public class HttpOutput extends ServletOutputStream implements Runnable
// Check if all written or full
if (complete || BufferUtil.isFull(_aggregate))
{
_writeblock.acquire();
write(_aggregate, complete, _writeblock);
_writeblock.block();
try(Blocker blocker=_writeblock.acquire())
{
write(_aggregate, complete, blocker);
blocker.block();
}
if (complete)
closed();
}
@ -497,9 +500,11 @@ public class HttpOutput extends ServletOutputStream implements Runnable
*/
public void sendContent(ByteBuffer content) throws IOException
{
_writeblock.acquire();
write(content,true,_writeblock);
_writeblock.block();
try(Blocker blocker=_writeblock.acquire())
{
write(content,true,blocker);
blocker.block();
}
}
/* ------------------------------------------------------------ */
@ -509,9 +514,11 @@ public class HttpOutput extends ServletOutputStream implements Runnable
*/
public void sendContent(InputStream in) throws IOException
{
_writeblock.acquire();
new InputStreamWritingCB(in,_writeblock).iterate();
_writeblock.block();
try(Blocker blocker=_writeblock.acquire())
{
new InputStreamWritingCB(in,blocker).iterate();
blocker.block();
}
}
/* ------------------------------------------------------------ */
@ -521,9 +528,11 @@ public class HttpOutput extends ServletOutputStream implements Runnable
*/
public void sendContent(ReadableByteChannel in) throws IOException
{
_writeblock.acquire();
new ReadableByteChannelWritingCB(in,_writeblock).iterate();
_writeblock.block();
try(Blocker blocker=_writeblock.acquire())
{
new ReadableByteChannelWritingCB(in,blocker).iterate();
blocker.block();
}
}
@ -534,9 +543,11 @@ public class HttpOutput extends ServletOutputStream implements Runnable
*/
public void sendContent(HttpContent content) throws IOException
{
_writeblock.acquire();
sendContent(content,_writeblock);
_writeblock.block();
try(Blocker blocker=_writeblock.acquire())
{
sendContent(content,blocker);
blocker.block();
}
}
/* ------------------------------------------------------------ */

View File

@ -46,14 +46,12 @@ import org.eclipse.jetty.http.HttpGenerator;
import org.eclipse.jetty.http.HttpGenerator.ResponseInfo;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpHeaderValue;
import org.eclipse.jetty.http.HttpParser;
import org.eclipse.jetty.http.HttpScheme;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.io.RuntimeIOException;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ErrorHandler;
import org.eclipse.jetty.util.ByteArrayISO8859Writer;
import org.eclipse.jetty.util.QuotedStringTokenizer;

View File

@ -21,7 +21,6 @@ package org.eclipse.jetty.server.handler;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URI;

View File

@ -27,8 +27,6 @@ import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;

View File

@ -33,8 +33,6 @@ import java.util.HashSet;
import java.util.Locale;
import java.util.Random;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import javax.naming.InitialContext;

View File

@ -18,11 +18,6 @@
package org.eclipse.jetty.server;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.matchers.JUnitMatchers.containsString;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@ -40,6 +35,7 @@ import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.ssl.SslConnection;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.IO;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
@ -64,7 +60,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort());
client.setSoTimeout(10000);
assertFalse(client.isClosed());
Assert.assertFalse(client.isClosed());
OutputStream os=client.getOutputStream();
InputStream is=client.getInputStream();
@ -80,10 +76,10 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
IO.toString(is);
Thread.sleep(sleepTime);
assertEquals(-1, is.read());
Assert.assertEquals(-1, is.read());
Assert.assertTrue(System.currentTimeMillis()-start>minimumTestRuntime);
Assert.assertTrue(System.currentTimeMillis()-start<maximumTestRuntime);
Assert.assertTrue(System.currentTimeMillis() - start > minimumTestRuntime);
Assert.assertTrue(System.currentTimeMillis() - start < maximumTestRuntime);
}
@Test
@ -93,7 +89,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort());
client.setSoTimeout(10000);
assertFalse(client.isClosed());
Assert.assertFalse(client.isClosed());
OutputStream os=client.getOutputStream();
InputStream is=client.getInputStream();
@ -113,10 +109,10 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
IO.toString(is);
Thread.sleep(sleepTime);
assertEquals(-1, is.read());
Assert.assertEquals(-1, is.read());
Assert.assertTrue(System.currentTimeMillis()-start>minimumTestRuntime);
Assert.assertTrue(System.currentTimeMillis()-start<maximumTestRuntime);
Assert.assertTrue(System.currentTimeMillis() - start > minimumTestRuntime);
Assert.assertTrue(System.currentTimeMillis() - start < maximumTestRuntime);
}
@Test
@ -144,7 +140,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort());
client.setSoTimeout(10000);
assertFalse(client.isClosed());
Assert.assertFalse(client.isClosed());
OutputStream os=client.getOutputStream();
InputStream is=client.getInputStream();
@ -163,10 +159,10 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
// read the response
String result=IO.toString(is);
Assert.assertThat("OK",result,containsString("200 OK"));
Assert.assertThat("OK",result, Matchers.containsString("200 OK"));
// check client reads EOF
assertEquals(-1, is.read());
Assert.assertEquals(-1, is.read());
// wait for idle timeout
TimeUnit.MILLISECONDS.sleep(3 * MAX_IDLE_TIME);
@ -218,7 +214,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort());
client.setSoTimeout(10000);
assertFalse(client.isClosed());
Assert.assertFalse(client.isClosed());
OutputStream os=client.getOutputStream();
InputStream is=client.getInputStream();
@ -237,11 +233,11 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
// read the response
String result=IO.toString(is);
Assert.assertThat("OK",result,containsString("200 OK"));
Assert.assertThat("OK",result, Matchers.containsString("200 OK"));
// check client reads EOF
assertEquals(-1, is.read());
assertTrue(endPoint.isOutputShutdown());
Assert.assertEquals(-1, is.read());
Assert.assertTrue(endPoint.isOutputShutdown());
Thread.sleep(2 * MAX_IDLE_TIME);
@ -294,7 +290,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort());
client.setSoTimeout(10000);
assertFalse(client.isClosed());
Assert.assertFalse(client.isClosed());
OutputStream os=client.getOutputStream();
InputStream is=client.getInputStream();
@ -318,7 +314,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
IO.toString(is);
// check client reads EOF
assertEquals(-1, is.read());
Assert.assertEquals(-1, is.read());
TimeUnit.MILLISECONDS.sleep(3*MAX_IDLE_TIME);
@ -353,14 +349,14 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort());
client.setSoTimeout(10000);
InputStream is=client.getInputStream();
assertFalse(client.isClosed());
Assert.assertFalse(client.isClosed());
Thread.sleep(sleepTime);
long start = System.currentTimeMillis();
try
{
IO.toString(is);
assertEquals(-1, is.read());
Assert.assertEquals(-1, is.read());
}
catch(SSLException e)
{
@ -370,7 +366,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
{
e.printStackTrace();
}
Assert.assertTrue(System.currentTimeMillis()-start<maximumTestRuntime);
Assert.assertTrue(System.currentTimeMillis() - start < maximumTestRuntime);
}
@ -381,7 +377,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort());
client.setSoTimeout(10000);
assertFalse(client.isClosed());
Assert.assertFalse(client.isClosed());
OutputStream os=client.getOutputStream();
InputStream is=client.getInputStream();
@ -410,7 +406,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
for (int i =0;i<20;i++)
{
offset=in.indexOf("Wibble",offset+1);
Assert.assertTrue(""+i,offset>0);
Assert.assertTrue("" + i, offset > 0);
}
}
@ -421,7 +417,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort());
client.setSoTimeout(10000);
assertFalse(client.isClosed());
Assert.assertFalse(client.isClosed());
OutputStream os=client.getOutputStream();
InputStream is=client.getInputStream();
@ -439,7 +435,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
for (int i =0;i<20;i++)
{
offset=in.indexOf("Hello World",offset+1);
Assert.assertTrue(""+i,offset>0);
Assert.assertTrue("" + i, offset > 0);
}
}
@ -450,7 +446,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
Socket client=newSocket(_serverURI.getHost(),_serverURI.getPort());
client.setSoTimeout(10000);
assertFalse(client.isClosed());
Assert.assertFalse(client.isClosed());
OutputStream os=client.getOutputStream();
InputStream is=client.getInputStream();
@ -465,7 +461,7 @@ public abstract class ConnectorTimeoutTest extends HttpServerTestFixture
String in = IO.toString(is);
int offset=in.indexOf("Hello World");
Assert.assertTrue(offset>0);
Assert.assertTrue(offset > 0);
}
protected static class SlowResponseHandler extends AbstractHandler

View File

@ -36,7 +36,6 @@ import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.SelectChannelEndPoint;
import org.eclipse.jetty.io.SelectorManager.ManagedSelector;
import org.eclipse.jetty.server.HttpServerTestFixture.HelloWorldHandler;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.thread.Scheduler;
import org.hamcrest.Matchers;

View File

@ -36,12 +36,12 @@ import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Assert;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.resource.Resource;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

View File

@ -25,13 +25,13 @@ import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.HandlerWrapper;

View File

@ -18,6 +18,9 @@
package org.eclipse.jetty.server;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
@ -28,6 +31,7 @@ import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
@ -40,9 +44,6 @@ import org.junit.After;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
@Ignore
public class NetworkTrafficListenerTest
{

View File

@ -18,11 +18,6 @@
package org.eclipse.jetty.server.handler;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
@ -43,9 +38,6 @@ import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
/**
* @version $Revision$
*/
public class ContextHandlerTest
{
@Test
@ -97,9 +89,9 @@ public class ContextHandlerTest
server.start();
connector.getResponses("GET / HTTP/1.0\n" + "Host: www.example.com.\n\n");
assertTrue(handlerA.isHandled());
assertFalse(handlerB.isHandled());
assertFalse(handlerC.isHandled());
Assert.assertTrue(handlerA.isHandled());
Assert.assertFalse(handlerB.isHandled());
Assert.assertFalse(handlerC.isHandled());
handlerA.reset();
handlerB.reset();
@ -107,9 +99,9 @@ public class ContextHandlerTest
connector.getResponses("GET / HTTP/1.0\n" + "Host: www.example2.com\n\n");
assertFalse(handlerA.isHandled());
assertTrue(handlerB.isHandled());
assertFalse(handlerC.isHandled());
Assert.assertFalse(handlerA.isHandled());
Assert.assertTrue(handlerB.isHandled());
Assert.assertFalse(handlerC.isHandled());
}
finally
@ -153,33 +145,33 @@ public class ContextHandlerTest
try
{
connector.getResponses("GET / HTTP/1.0\n" + "Host: www.example.com.\n\n");
assertTrue(handlerA.isHandled());
assertFalse(handlerB.isHandled());
assertFalse(handlerC.isHandled());
Assert.assertTrue(handlerA.isHandled());
Assert.assertFalse(handlerB.isHandled());
Assert.assertFalse(handlerC.isHandled());
handlerA.reset();
handlerB.reset();
handlerC.reset();
connector.getResponses("GET / HTTP/1.0\n" + "Host: localhost\n\n");
assertFalse(handlerA.isHandled());
assertFalse(handlerB.isHandled());
assertTrue(handlerC.isHandled());
Assert.assertFalse(handlerA.isHandled());
Assert.assertFalse(handlerB.isHandled());
Assert.assertTrue(handlerC.isHandled());
handlerA.reset();
handlerB.reset();
handlerC.reset();
connectorN.getResponses("GET / HTTP/1.0\n" + "Host: www.example.com.\n\n");
assertTrue(handlerA.isHandled());
assertFalse(handlerB.isHandled());
assertFalse(handlerC.isHandled());
Assert.assertTrue(handlerA.isHandled());
Assert.assertFalse(handlerB.isHandled());
Assert.assertFalse(handlerC.isHandled());
handlerA.reset();
handlerB.reset();
handlerC.reset();
connectorN.getResponses("GET / HTTP/1.0\n" + "Host: localhost\n\n");
assertFalse(handlerA.isHandled());
assertTrue(handlerB.isHandled());
assertFalse(handlerC.isHandled());
Assert.assertFalse(handlerA.isHandled());
Assert.assertTrue(handlerB.isHandled());
Assert.assertFalse(handlerC.isHandled());
handlerA.reset();
handlerB.reset();
handlerC.reset();
@ -209,19 +201,19 @@ public class ContextHandlerTest
// System.err.println(server.dump());
Assert.assertEquals(rootA._scontext,rootA._scontext.getContext("/"));
Assert.assertEquals(fooA._scontext,rootA._scontext.getContext("/foo"));
Assert.assertEquals(foobarA._scontext,rootA._scontext.getContext("/foo/bar"));
Assert.assertEquals(foobarA._scontext,rootA._scontext.getContext("/foo/bar/bob.jsp"));
Assert.assertEquals(rootA._scontext,rootA._scontext.getContext("/other"));
Assert.assertEquals(fooA._scontext,rootA._scontext.getContext("/foo/other"));
Assert.assertEquals(rootA._scontext, rootA._scontext.getContext("/"));
Assert.assertEquals(fooA._scontext, rootA._scontext.getContext("/foo"));
Assert.assertEquals(foobarA._scontext, rootA._scontext.getContext("/foo/bar"));
Assert.assertEquals(foobarA._scontext, rootA._scontext.getContext("/foo/bar/bob.jsp"));
Assert.assertEquals(rootA._scontext, rootA._scontext.getContext("/other"));
Assert.assertEquals(fooA._scontext, rootA._scontext.getContext("/foo/other"));
Assert.assertEquals(rootA._scontext,foobarA._scontext.getContext("/"));
Assert.assertEquals(fooA._scontext,foobarA._scontext.getContext("/foo"));
Assert.assertEquals(foobarA._scontext,foobarA._scontext.getContext("/foo/bar"));
Assert.assertEquals(foobarA._scontext,foobarA._scontext.getContext("/foo/bar/bob.jsp"));
Assert.assertEquals(rootA._scontext,foobarA._scontext.getContext("/other"));
Assert.assertEquals(fooA._scontext,foobarA._scontext.getContext("/foo/other"));
Assert.assertEquals(rootA._scontext, foobarA._scontext.getContext("/"));
Assert.assertEquals(fooA._scontext, foobarA._scontext.getContext("/foo"));
Assert.assertEquals(foobarA._scontext, foobarA._scontext.getContext("/foo/bar"));
Assert.assertEquals(foobarA._scontext, foobarA._scontext.getContext("/foo/bar/bob.jsp"));
Assert.assertEquals(rootA._scontext, foobarA._scontext.getContext("/other"));
Assert.assertEquals(fooA._scontext, foobarA._scontext.getContext("/foo/other"));
}
@Test
@ -242,39 +234,39 @@ public class ContextHandlerTest
// check that all contexts start normally
server.start();
assertThat(connector.getResponses("GET / HTTP/1.0\n\n"),Matchers.containsString("ctx=''"));
assertThat(connector.getResponses("GET /foo/xxx HTTP/1.0\n\n"),Matchers.containsString("ctx='/foo'"));
assertThat(connector.getResponses("GET /foo/bar/xxx HTTP/1.0\n\n"),Matchers.containsString("ctx='/foo/bar'"));
Assert.assertThat(connector.getResponses("GET / HTTP/1.0\n\n"), Matchers.containsString("ctx=''"));
Assert.assertThat(connector.getResponses("GET /foo/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo'"));
Assert.assertThat(connector.getResponses("GET /foo/bar/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo/bar'"));
// If we stop foobar, then requests will be handled by foo
foobar.stop();
assertThat(connector.getResponses("GET / HTTP/1.0\n\n"),Matchers.containsString("ctx=''"));
assertThat(connector.getResponses("GET /foo/xxx HTTP/1.0\n\n"),Matchers.containsString("ctx='/foo'"));
assertThat(connector.getResponses("GET /foo/bar/xxx HTTP/1.0\n\n"),Matchers.containsString("ctx='/foo'"));
Assert.assertThat(connector.getResponses("GET / HTTP/1.0\n\n"), Matchers.containsString("ctx=''"));
Assert.assertThat(connector.getResponses("GET /foo/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo'"));
Assert.assertThat(connector.getResponses("GET /foo/bar/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo'"));
// If we shutdown foo then requests will be 503'd
foo.shutdown().get();
assertThat(connector.getResponses("GET / HTTP/1.0\n\n"),Matchers.containsString("ctx=''"));
assertThat(connector.getResponses("GET /foo/xxx HTTP/1.0\n\n"),Matchers.containsString("503"));
assertThat(connector.getResponses("GET /foo/bar/xxx HTTP/1.0\n\n"),Matchers.containsString("503"));
Assert.assertThat(connector.getResponses("GET / HTTP/1.0\n\n"), Matchers.containsString("ctx=''"));
Assert.assertThat(connector.getResponses("GET /foo/xxx HTTP/1.0\n\n"), Matchers.containsString("503"));
Assert.assertThat(connector.getResponses("GET /foo/bar/xxx HTTP/1.0\n\n"), Matchers.containsString("503"));
// If we stop foo then requests will be handled by root
foo.stop();
assertThat(connector.getResponses("GET / HTTP/1.0\n\n"),Matchers.containsString("ctx=''"));
assertThat(connector.getResponses("GET /foo/xxx HTTP/1.0\n\n"),Matchers.containsString("ctx=''"));
assertThat(connector.getResponses("GET /foo/bar/xxx HTTP/1.0\n\n"),Matchers.containsString("ctx=''"));
Assert.assertThat(connector.getResponses("GET / HTTP/1.0\n\n"), Matchers.containsString("ctx=''"));
Assert.assertThat(connector.getResponses("GET /foo/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx=''"));
Assert.assertThat(connector.getResponses("GET /foo/bar/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx=''"));
// If we start foo then foobar requests will be handled by foo
foo.start();
assertThat(connector.getResponses("GET / HTTP/1.0\n\n"),Matchers.containsString("ctx=''"));
assertThat(connector.getResponses("GET /foo/xxx HTTP/1.0\n\n"),Matchers.containsString("ctx='/foo'"));
assertThat(connector.getResponses("GET /foo/bar/xxx HTTP/1.0\n\n"),Matchers.containsString("ctx='/foo'"));
Assert.assertThat(connector.getResponses("GET / HTTP/1.0\n\n"), Matchers.containsString("ctx=''"));
Assert.assertThat(connector.getResponses("GET /foo/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo'"));
Assert.assertThat(connector.getResponses("GET /foo/bar/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo'"));
// If we start foobar then foobar requests will be handled by foobar
foobar.start();
assertThat(connector.getResponses("GET / HTTP/1.0\n\n"),Matchers.containsString("ctx=''"));
assertThat(connector.getResponses("GET /foo/xxx HTTP/1.0\n\n"),Matchers.containsString("ctx='/foo'"));
assertThat(connector.getResponses("GET /foo/bar/xxx HTTP/1.0\n\n"),Matchers.containsString("ctx='/foo/bar'"));
Assert.assertThat(connector.getResponses("GET / HTTP/1.0\n\n"), Matchers.containsString("ctx=''"));
Assert.assertThat(connector.getResponses("GET /foo/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo'"));
Assert.assertThat(connector.getResponses("GET /foo/bar/xxx HTTP/1.0\n\n"), Matchers.containsString("ctx='/foo/bar'"));
}
@ -311,17 +303,17 @@ public class ContextHandlerTest
// System.err.println(server.dump());
Assert.assertEquals(rootA._scontext,rootA._scontext.getContext("/"));
Assert.assertEquals(fooA._scontext,rootA._scontext.getContext("/foo"));
Assert.assertEquals(foobarA._scontext,rootA._scontext.getContext("/foo/bar"));
Assert.assertEquals(foobarA._scontext,rootA._scontext.getContext("/foo/bar/bob"));
Assert.assertEquals(rootA._scontext, rootA._scontext.getContext("/"));
Assert.assertEquals(fooA._scontext, rootA._scontext.getContext("/foo"));
Assert.assertEquals(foobarA._scontext, rootA._scontext.getContext("/foo/bar"));
Assert.assertEquals(foobarA._scontext, rootA._scontext.getContext("/foo/bar/bob"));
Assert.assertEquals(rootA._scontext,rootA._scontext.getContext("/other"));
Assert.assertEquals(rootB._scontext,rootB._scontext.getContext("/other"));
Assert.assertEquals(rootC._scontext,rootC._scontext.getContext("/other"));
Assert.assertEquals(rootA._scontext, rootA._scontext.getContext("/other"));
Assert.assertEquals(rootB._scontext, rootB._scontext.getContext("/other"));
Assert.assertEquals(rootC._scontext, rootC._scontext.getContext("/other"));
Assert.assertEquals(fooB._scontext,rootB._scontext.getContext("/foo/other"));
Assert.assertEquals(rootC._scontext,rootC._scontext.getContext("/foo/other"));
Assert.assertEquals(fooB._scontext, rootB._scontext.getContext("/foo/other"));
Assert.assertEquals(rootC._scontext, rootC._scontext.getContext("/foo/other"));
}
@ -371,27 +363,27 @@ public class ContextHandlerTest
// test singular
context.setVirtualHosts(new String[] { "www.example.com"} );
Assert.assertEquals(1,context.getVirtualHosts().length);
Assert.assertEquals(1, context.getVirtualHosts().length);
// test adding two more
context.addVirtualHosts(new String[] { "www.example2.com", "www.example3.com"});
Assert.assertEquals(3,context.getVirtualHosts().length);
Assert.assertEquals(3, context.getVirtualHosts().length);
// test adding existing context
context.addVirtualHosts(new String[] { "www.example.com" });
Assert.assertEquals(3,context.getVirtualHosts().length);
Assert.assertEquals(3, context.getVirtualHosts().length);
// test removing existing
context.removeVirtualHosts(new String[] { "www.example3.com" });
Assert.assertEquals(2,context.getVirtualHosts().length);
Assert.assertEquals(2, context.getVirtualHosts().length);
// test removing non-existent
context.removeVirtualHosts(new String[] { "www.example3.com" });
Assert.assertEquals(2,context.getVirtualHosts().length);
Assert.assertEquals(2, context.getVirtualHosts().length);
// test removing all remaining and resets to null
context.removeVirtualHosts(new String[] { "www.example.com", "www.example2.com" });
Assert.assertEquals(null,context.getVirtualHosts());
Assert.assertArrayEquals(null, context.getVirtualHosts());
}
@ -401,31 +393,31 @@ public class ContextHandlerTest
ContextHandler handler = new ContextHandler();
handler.setServer(new Server());
handler.setAttribute("aaa","111");
assertEquals("111",handler.getServletContext().getAttribute("aaa"));
assertEquals(null,handler.getAttribute("bbb"));
Assert.assertEquals("111", handler.getServletContext().getAttribute("aaa"));
Assert.assertEquals(null, handler.getAttribute("bbb"));
handler.start();
handler.getServletContext().setAttribute("aaa","000");
handler.setAttribute("ccc","333");
handler.getServletContext().setAttribute("ddd","444");
assertEquals("111",handler.getServletContext().getAttribute("aaa"));
assertEquals(null,handler.getServletContext().getAttribute("bbb"));
Assert.assertEquals("111", handler.getServletContext().getAttribute("aaa"));
Assert.assertEquals(null, handler.getServletContext().getAttribute("bbb"));
handler.getServletContext().setAttribute("bbb","222");
assertEquals("333",handler.getServletContext().getAttribute("ccc"));
assertEquals("444",handler.getServletContext().getAttribute("ddd"));
Assert.assertEquals("333", handler.getServletContext().getAttribute("ccc"));
Assert.assertEquals("444", handler.getServletContext().getAttribute("ddd"));
assertEquals("111",handler.getAttribute("aaa"));
assertEquals(null,handler.getAttribute("bbb"));
assertEquals("333",handler.getAttribute("ccc"));
assertEquals(null,handler.getAttribute("ddd"));
Assert.assertEquals("111", handler.getAttribute("aaa"));
Assert.assertEquals(null, handler.getAttribute("bbb"));
Assert.assertEquals("333", handler.getAttribute("ccc"));
Assert.assertEquals(null, handler.getAttribute("ddd"));
handler.stop();
assertEquals("111",handler.getServletContext().getAttribute("aaa"));
assertEquals(null,handler.getServletContext().getAttribute("bbb"));
assertEquals("333",handler.getServletContext().getAttribute("ccc"));
assertEquals(null,handler.getServletContext().getAttribute("ddd"));
Assert.assertEquals("111", handler.getServletContext().getAttribute("aaa"));
Assert.assertEquals(null, handler.getServletContext().getAttribute("bbb"));
Assert.assertEquals("333", handler.getServletContext().getAttribute("ccc"));
Assert.assertEquals(null, handler.getServletContext().getAttribute("ddd"));
}
@Test
@ -435,10 +427,10 @@ public class ContextHandlerTest
String[] protectedTargets = {"/foo-inf", "/bar-inf"};
handler.setProtectedTargets(protectedTargets);
assertTrue(handler.isProtectedTarget("/foo-inf/x/y/z"));
assertFalse(handler.isProtectedTarget("/foo/x/y/z"));
assertTrue(handler.isProtectedTarget("/foo-inf?x=y&z=1"));
assertFalse(handler.isProtectedTarget("/foo-inf-bar"));
Assert.assertTrue(handler.isProtectedTarget("/foo-inf/x/y/z"));
Assert.assertFalse(handler.isProtectedTarget("/foo/x/y/z"));
Assert.assertTrue(handler.isProtectedTarget("/foo-inf?x=y&z=1"));
Assert.assertFalse(handler.isProtectedTarget("/foo-inf-bar"));
protectedTargets = new String[4];
System.arraycopy(handler.getProtectedTargets(), 0, protectedTargets, 0, 2);
@ -446,13 +438,13 @@ public class ContextHandlerTest
protectedTargets[3] = "/def";
handler.setProtectedTargets(protectedTargets);
assertTrue(handler.isProtectedTarget("/foo-inf/x/y/z"));
assertFalse(handler.isProtectedTarget("/foo/x/y/z"));
assertTrue(handler.isProtectedTarget("/foo-inf?x=y&z=1"));
assertTrue(handler.isProtectedTarget("/abc/124"));
assertTrue(handler.isProtectedTarget("//def"));
Assert.assertTrue(handler.isProtectedTarget("/foo-inf/x/y/z"));
Assert.assertFalse(handler.isProtectedTarget("/foo/x/y/z"));
Assert.assertTrue(handler.isProtectedTarget("/foo-inf?x=y&z=1"));
Assert.assertTrue(handler.isProtectedTarget("/abc/124"));
Assert.assertTrue(handler.isProtectedTarget("//def"));
assertTrue(handler.isProtectedTarget("/ABC/7777"));
Assert.assertTrue(handler.isProtectedTarget("/ABC/7777"));
}
@ -463,15 +455,15 @@ public class ContextHandlerTest
ContextHandler handler = new ContextHandler();
assertTrue("Not a directory " + testDirectory,testDirectory.isDirectory());
Assert.assertTrue("Not a directory " + testDirectory, testDirectory.isDirectory());
handler.setBaseResource(Resource.newResource(Resource.toURL(testDirectory)));
List<String> paths = new ArrayList<String>(handler.getResourcePaths(root));
assertEquals(2,paths.size());
List<String> paths = new ArrayList<>(handler.getResourcePaths(root));
Assert.assertEquals(2, paths.size());
Collections.sort(paths);
assertEquals("/WEB-INF/jsp/",paths.get(0));
assertEquals("/WEB-INF/web.xml",paths.get(1));
Assert.assertEquals("/WEB-INF/jsp/", paths.get(0));
Assert.assertEquals("/WEB-INF/web.xml", paths.get(1));
}
private File setupTestDirectory() throws IOException
@ -479,19 +471,19 @@ public class ContextHandlerTest
File tmpDir = new File( System.getProperty( "basedir",".") + "/target/tmp/ContextHandlerTest" );
tmpDir=tmpDir.getCanonicalFile();
if (!tmpDir.exists())
assertTrue(tmpDir.mkdirs());
Assert.assertTrue(tmpDir.mkdirs());
File tmp = File.createTempFile("cht",null, tmpDir );
assertTrue(tmp.delete());
assertTrue(tmp.mkdir());
Assert.assertTrue(tmp.delete());
Assert.assertTrue(tmp.mkdir());
tmp.deleteOnExit();
File root = new File(tmp,getClass().getName());
assertTrue(root.mkdir());
Assert.assertTrue(root.mkdir());
File webInf = new File(root,"WEB-INF");
assertTrue(webInf.mkdir());
Assert.assertTrue(webInf.mkdir());
assertTrue(new File(webInf,"jsp").mkdir());
assertTrue(new File(webInf,"web.xml").createNewFile());
Assert.assertTrue(new File(webInf, "jsp").mkdir());
Assert.assertTrue(new File(webInf, "web.xml").createNewFile());
return root;
}
@ -507,9 +499,9 @@ public class ContextHandlerTest
{
connector.getResponses("GET / HTTP/1.1\n" + "Host: "+host+"\nConnection:close\n\n");
if(succeed)
assertTrue("'"+host+"' should have been handled.",handler.isHandled());
Assert.assertTrue("'" + host + "' should have been handled.", handler.isHandled());
else
assertFalse("'"+host + "' should not have been handled.", handler.isHandled());
Assert.assertFalse("'" + host + "' should not have been handled.", handler.isHandled());
handler.reset();
}

View File

@ -20,20 +20,18 @@ package org.eclipse.jetty.server.session;
import java.io.File;
import junit.framework.Assert;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.StdErrLog;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class HashSessionManagerTest
{
@After
public void enableStacks()
{
@ -61,7 +59,7 @@ public class HashSessionManagerTest
File testDir = MavenTestingUtils.getTargetTestingDir("hashes");
testDir.mkdirs();
manager.setStoreDirectory(testDir);
MavenTestingUtils.getTargetFile("dangerFile.session").createNewFile();
Assert.assertTrue("File should exist!", MavenTestingUtils.getTargetFile("dangerFile.session").exists());
@ -81,8 +79,8 @@ public class HashSessionManagerTest
File testDir = MavenTestingUtils.getTargetTestingDir("hashes");
testDir.mkdirs();
manager.setStoreDirectory(testDir);
new File(testDir, "validFile.session").createNewFile();
Assert.assertTrue(new File(testDir, "validFile.session").createNewFile());
Assert.assertTrue("File should exist!", new File(testDir, "validFile.session").exists());

View File

@ -34,9 +34,13 @@ import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.DispatcherType;
import javax.servlet.ServletException;
import javax.servlet.ServletRequestWrapper;
import javax.servlet.ServletResponseWrapper;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Request;
@ -91,6 +95,9 @@ public class AsyncServletTest
ServletHolder holder=new ServletHolder(_servlet);
holder.setAsyncSupported(true);
_servletHandler.addServletWithMapping(holder,"/path/*");
_servletHandler.addServletWithMapping(holder,"/path1/*");
_servletHandler.addServletWithMapping(holder,"/path2/*");
_servletHandler.addServletWithMapping(new ServletHolder(new FwdServlet()),"/fwd/*");
_server.start();
_port=_connector.getLocalPort();
}
@ -109,7 +116,7 @@ public class AsyncServletTest
String response=process(null,null);
assertEquals("HTTP/1.1 200 OK",response.substring(0,15));
assertContains(
"history: REQUEST\r\n"+
"history: REQUEST /path\r\n"+
"history: initial\r\n",response);
assertContains("NORMAL",response);
assertNotContains("history: onTimeout",response);
@ -122,7 +129,7 @@ public class AsyncServletTest
String response=process("sleep=200",null);
assertEquals("HTTP/1.1 200 OK",response.substring(0,15));
assertContains(
"history: REQUEST\r\n"+
"history: REQUEST /path\r\n"+
"history: initial\r\n",response);
assertContains("SLEPT",response);
assertNotContains("history: onTimeout",response);
@ -136,11 +143,11 @@ public class AsyncServletTest
String response=process("suspend=200",null);
assertEquals("HTTP/1.1 500 Async Timeout",response.substring(0,26));
assertContains(
"history: REQUEST\r\n"+
"history: REQUEST /path\r\n"+
"history: initial\r\n"+
"history: suspend\r\n"+
"history: onTimeout\r\n"+
"history: ERROR\r\n"+
"history: ERROR /path\r\n"+
"history: !initial\r\n"+
"history: onComplete\r\n",response);
@ -153,12 +160,12 @@ public class AsyncServletTest
String response=process("suspend=200&timeout=dispatch",null);
assertEquals("HTTP/1.1 200 OK",response.substring(0,15));
assertContains(
"history: REQUEST\r\n"+
"history: REQUEST /path\r\n"+
"history: initial\r\n"+
"history: suspend\r\n"+
"history: onTimeout\r\n"+
"history: dispatch\r\n"+
"history: ASYNC\r\n"+
"history: ASYNC /path\r\n"+
"history: !initial\r\n"+
"history: onComplete\r\n",response);
@ -171,7 +178,7 @@ public class AsyncServletTest
String response=process("suspend=200&timeout=complete",null);
assertEquals("HTTP/1.1 200 OK",response.substring(0,15));
assertContains(
"history: REQUEST\r\n"+
"history: REQUEST /path\r\n"+
"history: initial\r\n"+
"history: suspend\r\n"+
"history: onTimeout\r\n"+
@ -187,11 +194,11 @@ public class AsyncServletTest
String response=process("suspend=200&resume=10",null);
assertEquals("HTTP/1.1 200 OK",response.substring(0,15));
assertContains(
"history: REQUEST\r\n"+
"history: REQUEST /path\r\n"+
"history: initial\r\n"+
"history: suspend\r\n"+
"history: resume\r\n"+
"history: ASYNC\r\n"+
"history: ASYNC /path\r\n"+
"history: !initial\r\n"+
"history: onComplete\r\n",response);
assertNotContains("history: onTimeout",response);
@ -203,11 +210,11 @@ public class AsyncServletTest
String response=process("suspend=200&resume=0",null);
assertEquals("HTTP/1.1 200 OK",response.substring(0,15));
assertContains(
"history: REQUEST\r\n"+
"history: REQUEST /path\r\n"+
"history: initial\r\n"+
"history: suspend\r\n"+
"history: resume\r\n"+
"history: ASYNC\r\n"+
"history: ASYNC /path\r\n"+
"history: !initial\r\n"+
"history: onComplete\r\n",response);
assertContains("history: onComplete",response);
@ -219,7 +226,7 @@ public class AsyncServletTest
String response=process("suspend=200&complete=50",null);
assertEquals("HTTP/1.1 200 OK",response.substring(0,15));
assertContains(
"history: REQUEST\r\n"+
"history: REQUEST /path\r\n"+
"history: initial\r\n"+
"history: suspend\r\n"+
"history: complete\r\n"+
@ -235,7 +242,7 @@ public class AsyncServletTest
String response=process("suspend=200&complete=0",null);
assertEquals("HTTP/1.1 200 OK",response.substring(0,15));
assertContains(
"history: REQUEST\r\n"+
"history: REQUEST /path\r\n"+
"history: initial\r\n"+
"history: suspend\r\n"+
"history: complete\r\n"+
@ -251,15 +258,15 @@ public class AsyncServletTest
String response=process("suspend=1000&resume=10&suspend2=1000&resume2=10",null);
assertEquals("HTTP/1.1 200 OK",response.substring(0,15));
assertContains(
"history: REQUEST\r\n"+
"history: REQUEST /path\r\n"+
"history: initial\r\n"+
"history: suspend\r\n"+
"history: resume\r\n"+
"history: ASYNC\r\n"+
"history: ASYNC /path\r\n"+
"history: !initial\r\n"+
"history: suspend\r\n"+
"history: resume\r\n"+
"history: ASYNC\r\n"+
"history: ASYNC /path\r\n"+
"history: !initial\r\n"+
"history: onComplete\r\n",response);
assertContains("DISPATCHED",response);
@ -271,11 +278,11 @@ public class AsyncServletTest
String response=process("suspend=1000&resume=10&suspend2=1000&complete2=10",null);
assertEquals("HTTP/1.1 200 OK",response.substring(0,15));
assertContains(
"history: REQUEST\r\n"+
"history: REQUEST /path\r\n"+
"history: initial\r\n"+
"history: suspend\r\n"+
"history: resume\r\n"+
"history: ASYNC\r\n"+
"history: ASYNC /path\r\n"+
"history: !initial\r\n"+
"history: suspend\r\n"+
"history: complete\r\n"+
@ -290,15 +297,15 @@ public class AsyncServletTest
String response=process("suspend=1000&resume=10&suspend2=10",null);
assertEquals("HTTP/1.1 500 Async Timeout",response.substring(0,26));
assertContains(
"history: REQUEST\r\n"+
"history: REQUEST /path\r\n"+
"history: initial\r\n"+
"history: suspend\r\n"+
"history: resume\r\n"+
"history: ASYNC\r\n"+
"history: ASYNC /path\r\n"+
"history: !initial\r\n"+
"history: suspend\r\n"+
"history: onTimeout\r\n"+
"history: ERROR\r\n"+
"history: ERROR /path\r\n"+
"history: !initial\r\n"+
"history: onComplete\r\n",response);
assertContains("ERROR: /ctx/path/info",response);
@ -310,15 +317,15 @@ public class AsyncServletTest
String response=process("suspend=10&suspend2=1000&resume2=10",null);
assertEquals("HTTP/1.1 200 OK",response.substring(0,15));
assertContains(
"history: REQUEST\r\n"+
"history: REQUEST /path\r\n"+
"history: initial\r\n"+
"history: suspend\r\n"+
"history: onTimeout\r\n"+
"history: ERROR\r\n"+
"history: ERROR /path\r\n"+
"history: !initial\r\n"+
"history: suspend\r\n"+
"history: resume\r\n"+
"history: ASYNC\r\n"+
"history: ASYNC /path\r\n"+
"history: !initial\r\n"+
"history: onComplete\r\n",response);
assertContains("DISPATCHED",response);
@ -330,11 +337,11 @@ public class AsyncServletTest
String response=process("suspend=10&suspend2=1000&complete2=10",null);
assertEquals("HTTP/1.1 200 OK",response.substring(0,15));
assertContains(
"history: REQUEST\r\n"+
"history: REQUEST /path\r\n"+
"history: initial\r\n"+
"history: suspend\r\n"+
"history: onTimeout\r\n"+
"history: ERROR\r\n"+
"history: ERROR /path\r\n"+
"history: !initial\r\n"+
"history: suspend\r\n"+
"history: complete\r\n"+
@ -348,20 +355,109 @@ public class AsyncServletTest
_expectedCode="500 ";
String response=process("suspend=10&suspend2=10",null);
assertContains(
"history: REQUEST\r\n"+
"history: REQUEST /path\r\n"+
"history: initial\r\n"+
"history: suspend\r\n"+
"history: onTimeout\r\n"+
"history: ERROR\r\n"+
"history: ERROR /path\r\n"+
"history: !initial\r\n"+
"history: suspend\r\n"+
"history: onTimeout\r\n"+
"history: ERROR\r\n"+
"history: ERROR /path\r\n"+
"history: !initial\r\n"+
"history: onComplete\r\n",response);
assertContains("ERROR: /ctx/path/info",response);
}
@Test
public void testWrapStartDispatch() throws Exception
{
String response=process("wrap=true&suspend=200&resume=20",null);
assertEquals("HTTP/1.1 200 OK",response.substring(0,15));
assertContains(
"history: REQUEST /path\r\n"+
"history: initial\r\n"+
"history: suspend\r\n"+
"history: resume\r\n"+
"history: ASYNC /path\r\n"+
"history: wrapped REQ RSP\r\n"+
"history: !initial\r\n"+
"history: onComplete\r\n",response);
assertContains("DISPATCHED",response);
}
@Test
public void testFwdStartDispatch() throws Exception
{
String response=process("fwd","suspend=200&resume=20",null);
assertEquals("HTTP/1.1 200 OK",response.substring(0,15));
assertContains(
"history: FWD REQUEST /fwd\r\n"+
"history: FORWARD /path1\r\n"+
"history: initial\r\n"+
"history: suspend\r\n"+
"history: resume\r\n"+
"history: FWD ASYNC /fwd\r\n"+
"history: FORWARD /path1\r\n"+
"history: !initial\r\n"+
"history: onComplete\r\n",response);
assertContains("DISPATCHED",response);
}
@Test
public void testFwdStartDispatchPath() throws Exception
{
String response=process("fwd","suspend=200&resume=20&path=/path2",null);
assertEquals("HTTP/1.1 200 OK",response.substring(0,15));
assertContains(
"history: FWD REQUEST /fwd\r\n"+
"history: FORWARD /path1\r\n"+
"history: initial\r\n"+
"history: suspend\r\n"+
"history: resume\r\n"+
"history: ASYNC /path2\r\n"+
"history: !initial\r\n"+
"history: onComplete\r\n",response);
assertContains("DISPATCHED",response);
}
@Test
public void testFwdWrapStartDispatch() throws Exception
{
String response=process("fwd","wrap=true&suspend=200&resume=20",null);
assertEquals("HTTP/1.1 200 OK",response.substring(0,15));
assertContains(
"history: FWD REQUEST /fwd\r\n"+
"history: FORWARD /path1\r\n"+
"history: initial\r\n"+
"history: suspend\r\n"+
"history: resume\r\n"+
"history: ASYNC /path1\r\n"+
"history: wrapped REQ RSP\r\n"+
"history: !initial\r\n"+
"history: onComplete\r\n",response);
assertContains("DISPATCHED",response);
}
@Test
public void testFwdWrapStartDispatchPath() throws Exception
{
String response=process("fwd","wrap=true&suspend=200&resume=20&path=/path2",null);
assertEquals("HTTP/1.1 200 OK",response.substring(0,15));
assertContains(
"history: FWD REQUEST /fwd\r\n"+
"history: FORWARD /path1\r\n"+
"history: initial\r\n"+
"history: suspend\r\n"+
"history: resume\r\n"+
"history: ASYNC /path2\r\n"+
"history: wrapped REQ RSP\r\n"+
"history: !initial\r\n"+
"history: onComplete\r\n",response);
assertContains("DISPATCHED",response);
}
@Test
public void testAsyncRead() throws Exception
{
@ -389,12 +485,12 @@ public class AsyncServletTest
String response = IO.toString(socket.getInputStream());
assertEquals("HTTP/1.1 200 OK",response.substring(0,15));
assertContains(
"history: REQUEST\r\n"+
"history: REQUEST /path\r\n"+
"history: initial\r\n"+
"history: suspend\r\n"+
"history: async-read=10\r\n"+
"history: resume\r\n"+
"history: ASYNC\r\n"+
"history: ASYNC /path\r\n"+
"history: !initial\r\n"+
"history: onComplete\r\n",response);
}
@ -402,7 +498,12 @@ public class AsyncServletTest
public synchronized String process(String query,String content) throws Exception
{
String request = "GET /ctx/path/info";
return process("path",query,content);
}
public synchronized String process(String path,String query,String content) throws Exception
{
String request = "GET /ctx/"+path+"/info";
if (query!=null)
request+="?"+query;
@ -442,6 +543,18 @@ public class AsyncServletTest
Assert.assertThat(response,Matchers.not(Matchers.containsString(content)));
}
private static class FwdServlet extends HttpServlet
{
@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException
{
response.addHeader("history","FWD "+request.getDispatcherType()+" "+request.getServletPath());
if (request instanceof ServletRequestWrapper || response instanceof ServletResponseWrapper)
response.addHeader("history","wrapped"+((request instanceof ServletRequestWrapper)?" REQ":"")+((response instanceof ServletResponseWrapper)?" RSP":""));
request.getServletContext().getRequestDispatcher("/path1").forward(request,response);
}
}
private static class AsyncServlet extends HttpServlet
{
private static final long serialVersionUID = -8161977157098646562L;
@ -451,8 +564,11 @@ public class AsyncServletTest
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException
{
// System.err.println(request.getDispatcherType()+" "+request.getRequestURI());
response.addHeader("history",request.getDispatcherType().toString());
response.addHeader("history",request.getDispatcherType()+" "+request.getServletPath());
if (request instanceof ServletRequestWrapper || response instanceof ServletResponseWrapper)
response.addHeader("history","wrapped"+((request instanceof ServletRequestWrapper)?" REQ":"")+((response instanceof ServletResponseWrapper)?" RSP":""));
boolean wrap="true".equals(request.getParameter("wrap"));
int read_before=0;
long sleep_for=-1;
long suspend_for=-1;
@ -462,6 +578,7 @@ public class AsyncServletTest
long complete_after=-1;
long complete2_after=-1;
if (request.getParameter("read")!=null)
read_before=Integer.parseInt(request.getParameter("read"));
if (request.getParameter("sleep")!=null)
@ -472,6 +589,7 @@ public class AsyncServletTest
suspend2_for=Integer.parseInt(request.getParameter("suspend2"));
if (request.getParameter("resume")!=null)
resume_after=Integer.parseInt(request.getParameter("resume"));
final String path=request.getParameter("path");
if (request.getParameter("resume2")!=null)
resume2_after=Integer.parseInt(request.getParameter("resume2"));
if (request.getParameter("complete")!=null)
@ -479,8 +597,9 @@ public class AsyncServletTest
if (request.getParameter("complete2")!=null)
complete2_after=Integer.parseInt(request.getParameter("complete2"));
if (request.getDispatcherType()==DispatcherType.REQUEST)
if (request.getAttribute("State")==null)
{
request.setAttribute("State",new Integer(1));
response.addHeader("history","initial");
if (read_before>0)
{
@ -521,7 +640,7 @@ public class AsyncServletTest
if (suspend_for>=0)
{
final AsyncContext async=request.startAsync();
final AsyncContext async=wrap?request.startAsync(new HttpServletRequestWrapper(request),new HttpServletResponseWrapper(response)):request.startAsync();
if (suspend_for>0)
async.setTimeout(suspend_for);
async.addListener(__listener);
@ -567,7 +686,10 @@ public class AsyncServletTest
public void run()
{
((HttpServletResponse)async.getResponse()).addHeader("history","resume");
async.dispatch();
if (path!=null)
async.dispatch(path);
else
async.dispatch();
}
};
synchronized (_timer)
@ -578,7 +700,10 @@ public class AsyncServletTest
else if (resume_after==0)
{
((HttpServletResponse)async.getResponse()).addHeader("history","resume");
async.dispatch();
if (path!=null)
async.dispatch(path);
else
async.dispatch();
}
}
@ -607,7 +732,7 @@ public class AsyncServletTest
if (suspend2_for>=0 && request.getAttribute("2nd")==null)
{
final AsyncContext async=request.startAsync();
final AsyncContext async=wrap?request.startAsync(new HttpServletRequestWrapper(request),new HttpServletResponseWrapper(response)):request.startAsync();
async.addListener(__listener);
request.setAttribute("2nd","cycle");

View File

@ -24,35 +24,18 @@ import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.thread.NonBlockingThread;
/* ------------------------------------------------------------ */
/**
* A Callback for simple reusable conversion of an
* asynchronous API to blocking.
* <p>
* To avoid late redundant calls to {@link #succeeded()} or {@link #failed(Throwable)} from
* interfering with later reuses of this class, the callback context is used to hold pass a phase indicated
* and only a single callback per phase is allowed.
* <p>
* A typical usage pattern is:
* <pre>
* public class MyClass
* {
* BlockingCallback cb = new BlockingCallback();
*
* public void blockingMethod(Object args) throws Exception
* {
* asyncMethod(args,cb);
* cb.block();
* }
*
* public <C>void asyncMethod(Object args, Callback callback)
* {
* ...
* }
* }
* An implementation of Callback that blocks until success or failure.
*/
public class BlockingCallback implements Callback
{
private static final Logger LOG = Log.getLogger(BlockingCallback.class);
private static Throwable SUCCEEDED=new Throwable()
{
@Override
@ -87,6 +70,9 @@ public class BlockingCallback implements Callback
*/
public void block() throws IOException
{
if (NonBlockingThread.isNonBlockingThread())
LOG.warn("Blocking a NonBlockingThread: ",new Throwable());
try
{
_latch.await();

View File

@ -33,7 +33,6 @@ import java.nio.charset.Charset;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
/* ======================================================================== */
/** IO Utilities.

View File

@ -20,6 +20,7 @@ package org.eclipse.jetty.util;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

View File

@ -18,174 +18,232 @@
package org.eclipse.jetty.util;
import java.io.Closeable;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.util.thread.NonBlockingThread;
/* ------------------------------------------------------------ */
/**
* A Callback for simple reusable conversion of an
* asynchronous API to blocking.
* <p>
* To avoid late redundant calls to {@link #succeeded()} or {@link #failed(Throwable)} from
* interfering with later reuses of this class, the callback context is used to hold pass a phase indicated
* and only a single callback per phase is allowed.
* <p>
/** Provides a reusable BlockingCallback.
* A typical usage pattern is:
* <pre>
* public class MyClass
* void someBlockingCall(Object... args) throws IOException
* {
* BlockingCallback cb = new BlockingCallback();
*
* public void blockingMethod(Object args) throws Exception
* {
* asyncMethod(args,cb);
* cb.block();
* }
*
* public <C>void asyncMethod(Object args, Callback callback)
* {
* ...
* }
* }
* try(Blocker blocker=sharedBlockingCallback.acquire())
* {
* someAsyncCall(args,blocker);
* blocker.block();
* }
* }
* </pre>
*/
public class SharedBlockingCallback extends BlockingCallback
public class SharedBlockingCallback
{
private static Throwable IDLE=new Throwable()
{
@Override
public String toString() { return "IDLE"; }
};
private static Throwable SUCCEEDED=new Throwable()
{
@Override
public String toString() { return "SUCCEEDED"; }
};
private static final Logger LOG = Log.getLogger(SharedBlockingCallback.class);
final ReentrantLock _lock = new ReentrantLock();
Condition _idle = _lock.newCondition();
Condition _complete = _lock.newCondition();
Throwable _state = IDLE;
private static Throwable IDLE = new Throwable()
{
@Override
public String toString()
{
return "IDLE";
}
};
private static Throwable SUCCEEDED = new Throwable()
{
@Override
public String toString()
{
return "SUCCEEDED";
}
};
final Blocker _blocker;
public SharedBlockingCallback()
{}
public void acquire() throws IOException
{
_lock.lock();
this(new Blocker());
}
protected SharedBlockingCallback(Blocker blocker)
{
_blocker=blocker;
}
public Blocker acquire() throws IOException
{
_blocker._lock.lock();
try
{
while (_state!=IDLE)
_idle.await();
_state=null;
while (_blocker._state != IDLE)
_blocker._idle.await();
_blocker._state = null;
}
catch (final InterruptedException e)
{
throw new InterruptedIOException(){{initCause(e);}};
throw new InterruptedIOException()
{
{
initCause(e);
}
};
}
finally
{
_lock.unlock();
_blocker._lock.unlock();
}
return _blocker;
}
@Override
public void succeeded()
{
_lock.lock();
try
{
if (_state==null)
{
_state=SUCCEEDED;
_complete.signalAll();
}
else if (_state==IDLE)
throw new IllegalStateException("IDLE");
}
finally
{
_lock.unlock();
}
}
@Override
public void failed(Throwable cause)
{
_lock.lock();
try
{
if (_state==null)
{
_state=cause;
_complete.signalAll();
}
else if (_state==IDLE)
throw new IllegalStateException("IDLE");
}
finally
{
_lock.unlock();
}
}
/** Block until the Callback has succeeded or failed and
* after the return leave in the state to allow reuse.
* This is useful for code that wants to repeatable use a FutureCallback to convert
* an asynchronous API to a blocking API.
* @throws IOException if exception was caught during blocking, or callback was cancelled
/* ------------------------------------------------------------ */
/** A Closeable Callback.
* Uses the auto close mechanism to check block has been called OK.
*/
@Override
public void block() throws IOException
public static class Blocker implements Callback, Closeable
{
_lock.lock();
try
{
while (_state==null)
_complete.await();
if (_state==SUCCEEDED)
return;
if (_state==IDLE)
throw new IllegalStateException("IDLE");
if (_state instanceof IOException)
throw (IOException) _state;
if (_state instanceof CancellationException)
throw (CancellationException) _state;
throw new IOException(_state);
}
catch (final InterruptedException e)
{
throw new InterruptedIOException(){{initCause(e);}};
}
finally
{
_state=IDLE;
_idle.signalAll();
_lock.unlock();
}
}
@Override
public String toString()
{
_lock.lock();
try
{
return String.format("%s@%x{%s}",SharedBlockingCallback.class.getSimpleName(),hashCode(),_state);
}
finally
{
_lock.unlock();
}
}
final ReentrantLock _lock = new ReentrantLock();
final Condition _idle = _lock.newCondition();
final Condition _complete = _lock.newCondition();
Throwable _state = IDLE;
public Blocker()
{
}
@Override
public void succeeded()
{
_lock.lock();
try
{
if (_state == null)
{
_state = SUCCEEDED;
_complete.signalAll();
}
else if (_state == IDLE)
throw new IllegalStateException("IDLE");
}
finally
{
_lock.unlock();
}
}
@Override
public void failed(Throwable cause)
{
_lock.lock();
try
{
if (_state == null)
{
_state = cause;
_complete.signalAll();
}
else if (_state == IDLE)
throw new IllegalStateException("IDLE");
}
finally
{
_lock.unlock();
}
}
/**
* Block until the Callback has succeeded or failed and after the return leave in the state to allow reuse. This is useful for code that wants to
* repeatable use a FutureCallback to convert an asynchronous API to a blocking API.
*
* @throws IOException
* if exception was caught during blocking, or callback was cancelled
*/
public void block() throws IOException
{
if (NonBlockingThread.isNonBlockingThread())
LOG.warn("Blocking a NonBlockingThread: ",new Throwable());
_lock.lock();
try
{
while (_state == null)
_complete.await();
if (_state == SUCCEEDED)
return;
if (_state == IDLE)
throw new IllegalStateException("IDLE");
if (_state instanceof IOException)
throw (IOException)_state;
if (_state instanceof CancellationException)
throw (CancellationException)_state;
if (_state instanceof RuntimeException)
throw (RuntimeException)_state;
if (_state instanceof Error)
throw (Error)_state;
throw new IOException(_state);
}
catch (final InterruptedException e)
{
throw new InterruptedIOException()
{
{
initCause(e);
}
};
}
finally
{
_lock.unlock();
}
}
/**
* Check the Callback has succeeded or failed and after the return leave in the state to allow reuse.
*
* @throws IOException
* if exception was caught during blocking, or callback was cancelled
*/
@Override
public void close() throws IOException
{
_lock.lock();
try
{
if (_state == IDLE)
throw new IllegalStateException("IDLE");
if (_state == null)
LOG.warn(new Throwable());
}
finally
{
_state = IDLE;
_idle.signalAll();
_lock.unlock();
}
}
@Override
public String toString()
{
_lock.lock();
try
{
return String.format("%s@%x{%s}",SharedBlockingCallback.class.getSimpleName(),hashCode(),_state);
}
finally
{
_lock.unlock();
}
}
}
}

View File

@ -0,0 +1,59 @@
//
// ========================================================================
// Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.util.thread;
/**
* Marker that wraps a Runnable, indicating that it is running in a thread that must not be blocked.
* <p />
* Client code can use the thread-local {@link #isNonBlockingThread()} to detect whether they are
* in the context of a non-blocking thread, and perform different actions if that's the case.
*/
public class NonBlockingThread implements Runnable
{
private final static ThreadLocal<Boolean> __nonBlockingThread = new ThreadLocal<>();
/**
* @return whether the current thread is a thread that must not block.
*/
public static boolean isNonBlockingThread()
{
return Boolean.TRUE.equals(__nonBlockingThread.get());
}
private final Runnable delegate;
public NonBlockingThread(Runnable delegate)
{
this.delegate = delegate;
}
@Override
public void run()
{
try
{
__nonBlockingThread.set(Boolean.TRUE);
delegate.run();
}
finally
{
__nonBlockingThread.remove();
}
}
}

View File

@ -18,11 +18,9 @@
package org.eclipse.jetty.util;
import java.nio.charset.StandardCharsets;
import junit.framework.Assert;
import org.junit.Assert;
import org.junit.Test;
public class B64CodeTest

View File

@ -19,18 +19,12 @@
package org.eclipse.jetty.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
public class BlockingCallbackTest
{

View File

@ -19,22 +19,17 @@
package org.eclipse.jetty.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.util.SharedBlockingCallback.Blocker;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
public class SharedBlockingCallbackTest
{
final SharedBlockingCallback fcb= new SharedBlockingCallback();
final SharedBlockingCallback sbcb= new SharedBlockingCallback();
public SharedBlockingCallbackTest()
{
@ -43,34 +38,40 @@ public class SharedBlockingCallbackTest
@Test
public void testDone() throws Exception
{
fcb.acquire();
fcb.succeeded();
long start=System.currentTimeMillis();
fcb.block();
{
long start;
try (Blocker blocker=sbcb.acquire())
{
blocker.succeeded();
start=System.currentTimeMillis();
blocker.block();
}
Assert.assertThat(System.currentTimeMillis()-start,Matchers.lessThan(500L));
}
@Test
public void testGetDone() throws Exception
{
fcb.acquire();
final CountDownLatch latch = new CountDownLatch(1);
new Thread(new Runnable()
long start;
try (final Blocker blocker=sbcb.acquire())
{
@Override
public void run()
final CountDownLatch latch = new CountDownLatch(1);
new Thread(new Runnable()
{
latch.countDown();
try{TimeUnit.MILLISECONDS.sleep(100);}catch(Exception e){e.printStackTrace();}
fcb.succeeded();
}
}).start();
latch.await();
long start=System.currentTimeMillis();
fcb.block();
@Override
public void run()
{
latch.countDown();
try{TimeUnit.MILLISECONDS.sleep(100);}catch(Exception e){e.printStackTrace();}
blocker.succeeded();
}
}).start();
latch.await();
start=System.currentTimeMillis();
blocker.block();
}
Assert.assertThat(System.currentTimeMillis()-start,Matchers.greaterThan(10L));
Assert.assertThat(System.currentTimeMillis()-start,Matchers.lessThan(1000L));
}
@ -78,18 +79,20 @@ public class SharedBlockingCallbackTest
@Test
public void testFailed() throws Exception
{
fcb.acquire();
Exception ex=new Exception("FAILED");
fcb.failed(ex);
long start=System.currentTimeMillis();
final Exception ex = new Exception("FAILED");
long start=Long.MIN_VALUE;
try
{
fcb.block();
try (final Blocker blocker=sbcb.acquire())
{
blocker.failed(ex);
blocker.block();
}
Assert.fail();
}
catch(IOException ee)
{
start=System.currentTimeMillis();
Assert.assertEquals(ex,ee.getCause());
}
Assert.assertThat(System.currentTimeMillis()-start,Matchers.lessThan(100L));
@ -98,26 +101,30 @@ public class SharedBlockingCallbackTest
@Test
public void testGetFailed() throws Exception
{
fcb.acquire();
final Exception ex=new Exception("FAILED");
final Exception ex = new Exception("FAILED");
long start=Long.MIN_VALUE;
final CountDownLatch latch = new CountDownLatch(1);
new Thread(new Runnable()
{
@Override
public void run()
{
latch.countDown();
try{TimeUnit.MILLISECONDS.sleep(100);}catch(Exception e){e.printStackTrace();}
fcb.failed(ex);
}
}).start();
latch.await();
long start=System.currentTimeMillis();
try
{
fcb.block();
try (final Blocker blocker=sbcb.acquire())
{
new Thread(new Runnable()
{
@Override
public void run()
{
latch.countDown();
try{TimeUnit.MILLISECONDS.sleep(100);}catch(Exception e){e.printStackTrace();}
blocker.failed(ex);
}
}).start();
latch.await();
start=System.currentTimeMillis();
blocker.block();
}
Assert.fail();
}
catch(IOException ee)
@ -141,11 +148,13 @@ public class SharedBlockingCallbackTest
{
try
{
fcb.acquire();
latch.countDown();
TimeUnit.MILLISECONDS.sleep(100);
fcb.succeeded();
fcb.block();
try (Blocker blocker=sbcb.acquire())
{
latch.countDown();
TimeUnit.MILLISECONDS.sleep(100);
blocker.succeeded();
blocker.block();
}
}
catch(Exception e)
{
@ -157,12 +166,14 @@ public class SharedBlockingCallbackTest
latch.await();
long start=System.currentTimeMillis();
fcb.acquire();
Assert.assertThat(System.currentTimeMillis()-start,Matchers.greaterThan(10L));
Assert.assertThat(System.currentTimeMillis()-start,Matchers.lessThan(500L));
try (Blocker blocker=sbcb.acquire())
{
Assert.assertThat(System.currentTimeMillis()-start,Matchers.greaterThan(10L));
Assert.assertThat(System.currentTimeMillis()-start,Matchers.lessThan(500L));
fcb.succeeded();
fcb.block();
blocker.succeeded();
blocker.block();
};
Assert.assertThat(System.currentTimeMillis()-start,Matchers.lessThan(600L));
}
}

View File

@ -18,20 +18,12 @@
package org.eclipse.jetty.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.Set;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
*
*
*/
public class StringMapTest
{
StringMap<String> m0;
@ -46,18 +38,18 @@ public class StringMapTest
@Before
public void setUp() throws Exception
{
m0=new StringMap<String>();
m1=new StringMap<String>(false);
m0=new StringMap<>();
m1=new StringMap<>(false);
m1.put("abc", "0");
m5=new StringMap<String>(false);
m5=new StringMap<>(false);
m5.put("a", "0");
m5.put("ab", "1");
m5.put("abc", "2");
m5.put("abb", "3");
m5.put("bbb", "4");
m5i=new StringMap<String>(true);
m5i=new StringMap<>(true);
m5i.put("ab", "1");
m5i.put("abc", "2");
m5i.put("abb", "3");
@ -66,28 +58,28 @@ public class StringMapTest
@Test
public void testSize()
{
assertEquals(0, m0.size());
assertEquals(1, m1.size());
assertEquals(5, m5.size());
assertEquals(3, m5i.size());
Assert.assertEquals(0, m0.size());
Assert.assertEquals(1, m1.size());
Assert.assertEquals(5, m5.size());
Assert.assertEquals(3, m5i.size());
m1.remove("abc");
m5.remove("abc");
m5.put("bbb","x");
m5i.put("ABC", "x");
assertEquals(0, m0.size());
assertEquals(0, m1.size());
assertEquals(4, m5.size());
assertEquals(3, m5i.size());
Assert.assertEquals(0, m0.size());
Assert.assertEquals(0, m1.size());
Assert.assertEquals(4, m5.size());
Assert.assertEquals(3, m5i.size());
}
@Test
public void testIsEmpty()
{
assertTrue(m0.isEmpty());
assertFalse(m1.isEmpty());
assertFalse(m5.isEmpty());
assertFalse(m5i.isEmpty());
Assert.assertTrue(m0.isEmpty());
Assert.assertFalse(m1.isEmpty());
Assert.assertFalse(m5.isEmpty());
Assert.assertFalse(m5i.isEmpty());
}
@Test
@ -97,13 +89,13 @@ public class StringMapTest
m1.clear();
m5.clear();
m5i.clear();
assertTrue(m0.isEmpty());
assertTrue(m1.isEmpty());
assertTrue(m5.isEmpty());
assertTrue(m5i.isEmpty());
assertEquals(null,m1.get("abc"));
assertEquals(null,m5.get("abc"));
assertEquals(null,m5i.get("abc"));
Assert.assertTrue(m0.isEmpty());
Assert.assertTrue(m1.isEmpty());
Assert.assertTrue(m5.isEmpty());
Assert.assertTrue(m5i.isEmpty());
Assert.assertEquals(null, m1.get("abc"));
Assert.assertEquals(null, m5.get("abc"));
Assert.assertEquals(null, m5i.get("abc"));
}
@ -113,20 +105,20 @@ public class StringMapTest
@Test
public void testPutGet()
{
assertEquals("2",m5.get("abc"));
assertEquals(null,m5.get("aBc"));
assertEquals("2",m5i.get("abc"));
assertEquals("2",m5i.get("aBc"));
Assert.assertEquals("2", m5.get("abc"));
Assert.assertEquals(null, m5.get("aBc"));
Assert.assertEquals("2", m5i.get("abc"));
Assert.assertEquals("2", m5i.get("aBc"));
m5.put("aBc", "x");
m5i.put("AbC", "x");
StringBuilder buffer=new StringBuilder();
buffer.append("aBc");
assertEquals("2",m5.get("abc"));
assertEquals("x",m5.get(buffer));
assertEquals("x",m5i.get((Object)"abc"));
assertEquals("x",m5i.get("aBc"));
Assert.assertEquals("2", m5.get("abc"));
Assert.assertEquals("x", m5.get(buffer));
Assert.assertEquals("x", m5i.get((Object)"abc"));
Assert.assertEquals("x", m5i.get("aBc"));
}
@ -143,14 +135,14 @@ public class StringMapTest
m5.remove("bbb");
m5i.remove("aBc");
assertEquals(0, m0.size());
assertEquals(0, m1.size());
assertEquals(4, m5.size());
assertEquals(2, m5i.size());
Assert.assertEquals(0, m0.size());
Assert.assertEquals(0, m1.size());
Assert.assertEquals(4, m5.size());
Assert.assertEquals(2, m5i.size());
assertEquals("2",m5.get("abc"));
assertEquals(null,m5.get("bbb"));
assertEquals(null,m5i.get("AbC"));
Assert.assertEquals("2", m5.get("abc"));
Assert.assertEquals(null, m5.get("bbb"));
Assert.assertEquals(null, m5i.get("AbC"));
}
/*
@ -162,9 +154,9 @@ public class StringMapTest
Set es0=m0.entrySet();
Set es1=m1.entrySet();
Set es5=m5.entrySet();
assertEquals(0, es0.size());
assertEquals(1, es1.size());
assertEquals(5, es5.size());
Assert.assertEquals(0, es0.size());
Assert.assertEquals(1, es1.size());
Assert.assertEquals(5, es5.size());
}
/*
@ -173,28 +165,28 @@ public class StringMapTest
@Test
public void testContainsKey()
{
assertTrue(m5.containsKey("abc"));
assertTrue(!m5.containsKey("aBc"));
assertTrue(m5.containsKey("bbb"));
assertTrue(!m5.containsKey("xyz"));
Assert.assertTrue(m5.containsKey("abc"));
Assert.assertTrue(!m5.containsKey("aBc"));
Assert.assertTrue(m5.containsKey("bbb"));
Assert.assertTrue(!m5.containsKey("xyz"));
assertTrue(m5i.containsKey("abc"));
assertTrue(m5i.containsKey("aBc"));
assertTrue(m5i.containsKey("ABC"));
Assert.assertTrue(m5i.containsKey("abc"));
Assert.assertTrue(m5i.containsKey("aBc"));
Assert.assertTrue(m5i.containsKey("ABC"));
}
@Test
public void testToString()
{
assertEquals("{}",m0.toString());
assertEquals("{abc=0}",m1.toString());
assertTrue(m5.toString().indexOf("abc=2")>0);
Assert.assertEquals("{}", m0.toString());
Assert.assertEquals("{abc=0}", m1.toString());
Assert.assertTrue(m5.toString().indexOf("abc=2") > 0);
}
@Test
public void testIgnoreCase()
{
StringMap<String> map = new StringMap<String>(true);
StringMap<String> map = new StringMap<>(true);
map.put("POST","1");
map.put("HEAD","2");
map.put("PUT","3");
@ -204,13 +196,13 @@ public class StringMapTest
map.put("CONNECT","7");
map.put("Upgrade","8");
assertEquals("1",map.get("POST"));
assertEquals("1",map.get("pOST"));
assertEquals("1",map.get("Post"));
Assert.assertEquals("1", map.get("POST"));
Assert.assertEquals("1", map.get("pOST"));
Assert.assertEquals("1", map.get("Post"));
assertEquals("8",map.get("UPGRADE"));
assertEquals("8",map.get("Upgrade"));
assertEquals("8",map.get("upgrade"));
Assert.assertEquals("8", map.get("UPGRADE"));
Assert.assertEquals("8", map.get("Upgrade"));
Assert.assertEquals("8", map.get("upgrade"));
}

View File

@ -18,21 +18,16 @@
package org.eclipse.jetty.util.resource;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import java.io.File;
import java.net.MalformedURLException;
import org.eclipse.jetty.toolchain.test.FS;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class ResourceAliasTest
{
static File __dir;
@ -56,59 +51,59 @@ public class ResourceAliasTest
public void testNullCharEndingFilename() throws Exception
{
File file=new File(__dir,"test.txt");
assertFalse(file.exists());
file.createNewFile();
assertTrue(file.exists());
Assert.assertFalse(file.exists());
Assert.assertTrue(file.createNewFile());
Assert.assertTrue(file.exists());
File file0=new File(__dir,"test.txt\0");
if (!file0.exists())
return; // this file system does not suffer this problem
assertTrue(file0.exists()); // This is an alias!
Assert.assertTrue(file0.exists()); // This is an alias!
Resource dir = Resource.newResource(__dir);
// Test not alias paths
Resource resource = Resource.newResource(file);
assertTrue(resource.exists());
assertNull(resource.getAlias());
Assert.assertTrue(resource.exists());
Assert.assertNull(resource.getAlias());
resource = Resource.newResource(file.getAbsoluteFile());
assertTrue(resource.exists());
assertNull(resource.getAlias());
Assert.assertTrue(resource.exists());
Assert.assertNull(resource.getAlias());
resource = Resource.newResource(file.toURI());
assertTrue(resource.exists());
assertNull(resource.getAlias());
Assert.assertTrue(resource.exists());
Assert.assertNull(resource.getAlias());
resource = Resource.newResource(file.toURI().toString());
assertTrue(resource.exists());
assertNull(resource.getAlias());
Assert.assertTrue(resource.exists());
Assert.assertNull(resource.getAlias());
resource = dir.addPath("test.txt");
assertTrue(resource.exists());
assertNull(resource.getAlias());
Assert.assertTrue(resource.exists());
Assert.assertNull(resource.getAlias());
// Test alias paths
resource = Resource.newResource(file0);
assertTrue(resource.exists());
assertNotNull(resource.getAlias());
Assert.assertTrue(resource.exists());
Assert.assertNotNull(resource.getAlias());
resource = Resource.newResource(file0.getAbsoluteFile());
assertTrue(resource.exists());
assertNotNull(resource.getAlias());
Assert.assertTrue(resource.exists());
Assert.assertNotNull(resource.getAlias());
resource = Resource.newResource(file0.toURI());
assertTrue(resource.exists());
assertNotNull(resource.getAlias());
Assert.assertTrue(resource.exists());
Assert.assertNotNull(resource.getAlias());
resource = Resource.newResource(file0.toURI().toString());
assertTrue(resource.exists());
assertNotNull(resource.getAlias());
Assert.assertTrue(resource.exists());
Assert.assertNotNull(resource.getAlias());
try
{
resource = dir.addPath("test.txt\0");
assertTrue(resource.exists());
assertNotNull(resource.getAlias());
Assert.assertTrue(resource.exists());
Assert.assertNotNull(resource.getAlias());
}
catch(MalformedURLException e)
{
assertTrue(true);
Assert.assertTrue(true);
}
}
}

View File

@ -136,6 +136,7 @@ public class WebAppContext extends ServletContextHandler implements WebAppClassL
"-org.eclipse.jetty.apache.", // don't hide jetty apache impls
"-org.eclipse.jetty.util.log.", // don't hide server log
"org.objectweb.asm.", // hide asm used by jetty
"org.eclipse.jdt.", // hide jdt used by jetty
"org.eclipse.jetty." // hide other jetty classes
} ;

View File

@ -18,23 +18,39 @@
package org.eclipse.jetty.websocket.common;
import java.io.IOException;
import org.eclipse.jetty.util.SharedBlockingCallback;
import org.eclipse.jetty.websocket.api.WriteCallback;
public class BlockingWriteCallback extends SharedBlockingCallback implements WriteCallback
/* ------------------------------------------------------------ */
/** extend a SharedlBlockingCallback to an websocket WriteCallback
*/
public class BlockingWriteCallback extends SharedBlockingCallback
{
public BlockingWriteCallback()
{}
@Override
public void writeFailed(Throwable x)
{
failed(x);
super(new WriteBlocker());
}
@Override
public void writeSuccess()
public WriteBlocker acquireWriteBlocker() throws IOException
{
succeeded();
return (WriteBlocker)acquire();
}
public static class WriteBlocker extends Blocker implements WriteCallback
{
@Override
public void writeFailed(Throwable x)
{
failed(x);
}
@Override
public void writeSuccess()
{
succeeded();
}
}
}

View File

@ -32,6 +32,7 @@ import org.eclipse.jetty.websocket.api.BatchMode;
import org.eclipse.jetty.websocket.api.RemoteEndpoint;
import org.eclipse.jetty.websocket.api.WriteCallback;
import org.eclipse.jetty.websocket.api.extensions.OutgoingFrames;
import org.eclipse.jetty.websocket.common.BlockingWriteCallback.WriteBlocker;
import org.eclipse.jetty.websocket.common.frames.BinaryFrame;
import org.eclipse.jetty.websocket.common.frames.ContinuationFrame;
import org.eclipse.jetty.websocket.common.frames.DataFrame;
@ -100,9 +101,11 @@ public class WebSocketRemoteEndpoint implements RemoteEndpoint
private void blockingWrite(WebSocketFrame frame) throws IOException
{
blocker.acquire();
uncheckedSendFrame(frame, blocker);
blocker.block();
try(WriteBlocker b=blocker.acquireWriteBlocker())
{
uncheckedSendFrame(frame, b);
b.block();
}
}
private boolean lockMsg(MsgType type)
@ -441,14 +444,14 @@ public class WebSocketRemoteEndpoint implements RemoteEndpoint
this.batchMode = batchMode;
}
@Override
public void flush() throws IOException
{
lockMsg(MsgType.ASYNC);
try
try (WriteBlocker b = blocker.acquireWriteBlocker())
{
blocker.acquire();
uncheckedSendFrame(FrameFlusher.FLUSH_FRAME, blocker);
blocker.block();
uncheckedSendFrame(FrameFlusher.FLUSH_FRAME, b);
b.block();
}
finally
{

View File

@ -31,6 +31,7 @@ import org.eclipse.jetty.websocket.api.WriteCallback;
import org.eclipse.jetty.websocket.api.extensions.OutgoingFrames;
import org.eclipse.jetty.websocket.common.BlockingWriteCallback;
import org.eclipse.jetty.websocket.common.WebSocketSession;
import org.eclipse.jetty.websocket.common.BlockingWriteCallback.WriteBlocker;
import org.eclipse.jetty.websocket.common.frames.BinaryFrame;
/**
@ -142,9 +143,11 @@ public class MessageOutputStream extends OutputStream
frame.setPayload(buffer);
frame.setFin(fin);
blocker.acquire();
outgoing.outgoingFrame(frame, blocker, BatchMode.OFF);
blocker.block();
try(WriteBlocker b=blocker.acquireWriteBlocker())
{
outgoing.outgoingFrame(frame, b, BatchMode.OFF);
b.block();
}
++frameCount;
// Any flush after the first will be a CONTINUATION frame.

View File

@ -31,6 +31,7 @@ import org.eclipse.jetty.websocket.api.WriteCallback;
import org.eclipse.jetty.websocket.api.extensions.OutgoingFrames;
import org.eclipse.jetty.websocket.common.BlockingWriteCallback;
import org.eclipse.jetty.websocket.common.WebSocketSession;
import org.eclipse.jetty.websocket.common.BlockingWriteCallback.WriteBlocker;
import org.eclipse.jetty.websocket.common.frames.TextFrame;
/**
@ -146,9 +147,11 @@ public class MessageWriter extends Writer
frame.setPayload(data);
frame.setFin(fin);
blocker.acquire();
outgoing.outgoingFrame(frame, blocker, BatchMode.OFF);
blocker.block();
try (WriteBlocker b = blocker.acquireWriteBlocker())
{
outgoing.outgoingFrame(frame, b, BatchMode.OFF);
b.block();
}
++frameCount;
// Any flush after the first will be a CONTINUATION frame.