Merge branch 'jetty-9' of ssh://git.eclipse.org/gitroot/jetty/org.eclipse.jetty.project into jetty-9

This commit is contained in:
Jesse McConnell 2012-07-18 14:01:42 -05:00
commit 960491cc64
26 changed files with 627 additions and 443 deletions

View File

@ -7,7 +7,7 @@ public abstract class AbstractEndPoint implements EndPoint
private final long _created=System.currentTimeMillis();
private final InetSocketAddress _local;
private final InetSocketAddress _remote;
private volatile int _maxIdleTime;
private volatile long _maxIdleTime;
private volatile long _idleTimestamp=System.currentTimeMillis();
@ -25,13 +25,13 @@ public abstract class AbstractEndPoint implements EndPoint
@Override
public int getMaxIdleTime()
public long getMaxIdleTime()
{
return _maxIdleTime;
}
@Override
public void setMaxIdleTime(int timeMs)
public void setMaxIdleTime(long timeMs)
{
_maxIdleTime=timeMs;
}
@ -62,11 +62,6 @@ public abstract class AbstractEndPoint implements EndPoint
_idleTimestamp=System.currentTimeMillis();
}
/* ------------------------------------------------------------ */
public void onClose()
{
}
/* ------------------------------------------------------------ */
@Override
public String toString()

View File

@ -146,11 +146,15 @@ public class AsyncByteArrayEndPoint extends ByteArrayEndPoint implements AsyncEn
}
}
@Override
public void onOpen()
{
}
@Override
public void onClose()
{
_checkTimeout.cancel();
super.onClose();
}
private static class TimeoutTask extends TimerTask

View File

@ -103,6 +103,7 @@ public interface AsyncEndPoint extends EndPoint
void setAsyncConnection(AsyncConnection connection);
void onClose();
void onOpen();
void onClose();
}

View File

@ -116,13 +116,13 @@ public interface EndPoint
* extraordinary handling takes place.
* @return the max idle time in ms or if ms <= 0 implies an infinite timeout
*/
int getMaxIdleTime();
long getMaxIdleTime();
/* ------------------------------------------------------------ */
/** Set the max idle time.
* @param timeMs the max idle time in MS. Timeout <= 0 implies an infinite timeout
*/
void setMaxIdleTime(int timeMs);
void setMaxIdleTime(long timeMs);

View File

@ -73,7 +73,7 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable,
};
/* ------------------------------------------------------------ */
public SelectChannelEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey key, int maxIdleTime) throws IOException
public SelectChannelEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey key, long maxIdleTime) throws IOException
{
super(channel);
_manager = selectSet.getManager();
@ -327,6 +327,11 @@ public class SelectChannelEndPoint extends ChannelEndPoint implements Runnable,
updateKey();
}
@Override
public void onOpen()
{
}
/* ------------------------------------------------------------ */
@Override
public void onClose()

View File

@ -51,6 +51,7 @@ public abstract class SelectorManager extends AbstractLifeCycle implements Dumpa
private final ManagedSelector[] _selectSets;
private long _selectSetIndex;
private volatile long _maxIdleTime;
protected SelectorManager()
{
@ -62,11 +63,18 @@ public abstract class SelectorManager extends AbstractLifeCycle implements Dumpa
this._selectSets = new ManagedSelector[selectors];
}
/**
* @return the max idle time
*/
protected abstract int getMaxIdleTime();
protected long getMaxIdleTime()
{
return _maxIdleTime;
}
public void setMaxIdleTime(long maxIdleTime)
{
_maxIdleTime = maxIdleTime;
}
protected abstract void execute(Runnable task);
@ -139,18 +147,27 @@ public abstract class SelectorManager extends AbstractLifeCycle implements Dumpa
/**
* @param endpoint the endPoint being opened
*/
protected abstract void endPointOpened(AsyncEndPoint endpoint);
protected void endPointOpened(AsyncEndPoint endpoint)
{
endpoint.getAsyncConnection().onOpen();
}
/**
* @param endpoint the endPoint being closed
*/
protected abstract void endPointClosed(AsyncEndPoint endpoint);
protected void endPointClosed(AsyncEndPoint endpoint)
{
endpoint.getAsyncConnection().onClose();
endpoint.onClose();
}
/**
* @param endpoint the endPoint being upgraded
* @param oldConnection the previous connection
*/
protected abstract void endPointUpgraded(AsyncEndPoint endpoint,AsyncConnection oldConnection);
protected void endPointUpgraded(AsyncEndPoint endpoint, AsyncConnection oldConnection)
{
}
/**
* @param channel the socket channel

View File

@ -1,52 +0,0 @@
package org.eclipse.jetty.io;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.nio.ByteBuffer;
import org.eclipse.jetty.util.BufferUtil;
import org.junit.Test;
public class BufferUtilTest
{
@Test
public void testPut() throws Exception
{
ByteBuffer to = BufferUtil.allocate(10);
ByteBuffer from=BufferUtil.toBuffer("12345");
BufferUtil.clear(to);
assertEquals(5,BufferUtil.append(from,to));
assertTrue(BufferUtil.isEmpty(from));
assertEquals("12345",BufferUtil.toString(to));
from=BufferUtil.toBuffer("XX67890ZZ");
from.position(2);
assertEquals(5,BufferUtil.append(from,to));
assertEquals(2,from.remaining());
assertEquals("1234567890",BufferUtil.toString(to));
}
@Test
public void testPutDirect() throws Exception
{
ByteBuffer to = BufferUtil.allocateDirect(10);
ByteBuffer from=BufferUtil.toBuffer("12345");
BufferUtil.clear(to);
assertEquals(5,BufferUtil.append(from,to));
assertTrue(BufferUtil.isEmpty(from));
assertEquals("12345",BufferUtil.toString(to));
from=BufferUtil.toBuffer("XX67890ZZ");
from.position(2);
assertEquals(5,BufferUtil.append(from,to));
assertEquals(2,from.remaining());
assertEquals("1234567890",BufferUtil.toString(to));
}
}

View File

@ -1,11 +1,5 @@
package org.eclipse.jetty.io;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
@ -30,42 +24,25 @@ import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class SelectChannelEndPointTest
{
protected volatile AsyncEndPoint _lastEndp;
protected ServerSocketChannel _connector;
protected QueuedThreadPool _threadPool = new QueuedThreadPool();
private int maxIdleTimeout = 600000; // TODO: use smaller value
protected SelectorManager _manager = new SelectorManager()
{
@Override
protected int getMaxIdleTime()
{
return maxIdleTimeout;
}
@Override
protected void execute(Runnable task)
{
_threadPool.execute(task);
}
@Override
protected void endPointClosed(AsyncEndPoint endpoint)
{
}
@Override
protected void endPointOpened(AsyncEndPoint endpoint)
{
endpoint.getAsyncConnection().onOpen();
}
@Override
protected void endPointUpgraded(AsyncEndPoint endpoint, AsyncConnection oldConnection)
{
}
@Override
public AsyncConnection newConnection(SocketChannel channel, AsyncEndPoint endpoint, Object attachment)
{
@ -81,6 +58,9 @@ public class SelectChannelEndPointTest
return endp;
}
};
{
_manager.setMaxIdleTime(600000); // TODO: use smaller value
}
// Must be volatile or the test may fail spuriously
protected volatile int _blockAt=0;

View File

@ -7,7 +7,6 @@ import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSocket;
@ -32,38 +31,14 @@ public class SslConnectionTest
protected volatile AsyncEndPoint _lastEndp;
protected ServerSocketChannel _connector;
protected QueuedThreadPool _threadPool = new QueuedThreadPool();
private int maxIdleTimeout = 600000; // TODO: use smaller value
protected SelectorManager _manager = new SelectorManager()
{
@Override
protected int getMaxIdleTime()
{
return maxIdleTimeout;
}
@Override
protected void execute(Runnable task)
{
_threadPool.execute(task);
}
@Override
protected void endPointClosed(AsyncEndPoint endpoint)
{
}
@Override
protected void endPointOpened(AsyncEndPoint endpoint)
{
// System.err.println("endPointOpened");
endpoint.getAsyncConnection().onOpen();
}
@Override
protected void endPointUpgraded(AsyncEndPoint endpoint, AsyncConnection oldConnection)
{
}
@Override
public AsyncConnection newConnection(SocketChannel channel, AsyncEndPoint endpoint, Object attachment)
{
@ -89,6 +64,9 @@ public class SslConnectionTest
return endp;
}
};
{
_manager.setMaxIdleTime(600000); // TODO: use smaller value
}
// Must be volatile or the test may fail spuriously
protected volatile int _blockAt=0;

View File

@ -191,7 +191,7 @@ public abstract class AbstractConnector extends AggregateLifeCycle implements Co
* @return Returns the maxIdleTime.
*/
@Override
public int getMaxIdleTime()
public long getMaxIdleTime()
{
return _maxIdleTime;
}
@ -437,8 +437,6 @@ public abstract class AbstractConnector extends AggregateLifeCycle implements Co
/* ------------------------------------------------------------ */
protected void connectionOpened(AsyncConnection connection)
{
// TODO: should we dispatch the call to onOpen() to another thread ?
connection.onOpen();
_stats.connectionOpened();
}
@ -453,9 +451,6 @@ public abstract class AbstractConnector extends AggregateLifeCycle implements Co
/* ------------------------------------------------------------ */
protected void connectionClosed(AsyncConnection connection)
{
// TODO: should we dispatch the call to onClose() to another thread ?
connection.onClose();
long duration = System.currentTimeMillis() - connection.getEndPoint().getCreatedTimeStamp();
// TODO: remove casts to HttpConnection
int requests = (connection instanceof HttpConnection)?((HttpConnection)connection).getHttpChannel().getRequests():0;

View File

@ -54,7 +54,7 @@ public interface Connector extends LifeCycle
/**
* @return Max Idle time for connections in milliseconds
*/
int getMaxIdleTime();
long getMaxIdleTime();
/* ------------------------------------------------------------ */
/**

View File

@ -204,7 +204,6 @@ public class LocalHttpConnector extends HttpConnector
public void onClose()
{
super.onClose();
connectionClosed(getAsyncConnection());
_closed.countDown();
}

View File

@ -210,7 +210,6 @@ public class SelectChannelConnector extends HttpConnector implements NetConnecto
/* ------------------------------------------------------------------------------- */
protected void endPointClosed(AsyncEndPoint endpoint)
{
endpoint.onClose();
connectionClosed(endpoint.getAsyncConnection());
}
@ -238,7 +237,7 @@ public class SelectChannelConnector extends HttpConnector implements NetConnecto
}
@Override
protected int getMaxIdleTime()
protected long getMaxIdleTime()
{
return SelectChannelConnector.this.getMaxIdleTime();
}
@ -246,6 +245,7 @@ public class SelectChannelConnector extends HttpConnector implements NetConnecto
@Override
protected void endPointClosed(AsyncEndPoint endpoint)
{
super.endPointClosed(endpoint);
SelectChannelConnector.this.endPointClosed(endpoint);
}
@ -253,6 +253,7 @@ public class SelectChannelConnector extends HttpConnector implements NetConnecto
protected void endPointOpened(AsyncEndPoint endpoint)
{
// TODO handle max connections and low resources
super.endPointOpened(endpoint);
connectionOpened(endpoint.getAsyncConnection());
}

View File

@ -287,22 +287,6 @@ public class SPDYClient
return result;
}
@Override
protected void endPointOpened(AsyncEndPoint endpoint)
{
}
@Override
protected void endPointUpgraded(AsyncEndPoint endpoint, AsyncConnection oldConnection)
{
}
@Override
protected void endPointClosed(AsyncEndPoint endpoint)
{
endpoint.getAsyncConnection().onClose();
}
@Override
public AsyncConnection newConnection(final SocketChannel channel, AsyncEndPoint endPoint, Object attachment)
{

View File

@ -650,6 +650,34 @@ public class BufferUtil
return ByteBuffer.wrap(s.getBytes(charset));
}
/**
* Create a new ByteBuffer using provided byte array.
*
* @param array
* the byte array to back buffer with.
* @return ByteBuffer with provided byte array, in flush mode
*/
public static ByteBuffer toBuffer(byte array[])
{
return ByteBuffer.wrap(array);
}
/**
* Create a new ByteBuffer using the provided byte array.
*
* @param array
* the byte array to use.
* @param offset
* the offset within the byte array to use from
* @param length
* the length in bytes of the array to use
* @return ByteBuffer with provided byte array, in flush mode
*/
public static ByteBuffer toBuffer(byte array[], int offset, int length)
{
return ByteBuffer.wrap(array,offset,length);
}
public static ByteBuffer toBuffer(File file) throws IOException
{
RandomAccessFile raf = new RandomAccessFile(file,"r");

View File

@ -14,15 +14,14 @@
package org.eclipse.jetty.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.*;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.junit.Assert;
import org.junit.Test;
/**
*
*/
public class BufferUtilTest
{
@Test
@ -119,4 +118,81 @@ public class BufferUtilTest
assertEquals("t"+i,str[i],BufferUtil.toString(buffer));
}
}
@Test
public void testPut() throws Exception
{
ByteBuffer to = BufferUtil.allocate(10);
ByteBuffer from=BufferUtil.toBuffer("12345");
BufferUtil.clear(to);
assertEquals(5,BufferUtil.append(from,to));
assertTrue(BufferUtil.isEmpty(from));
assertEquals("12345",BufferUtil.toString(to));
from=BufferUtil.toBuffer("XX67890ZZ");
from.position(2);
assertEquals(5,BufferUtil.append(from,to));
assertEquals(2,from.remaining());
assertEquals("1234567890",BufferUtil.toString(to));
}
@Test
public void testPutDirect() throws Exception
{
ByteBuffer to = BufferUtil.allocateDirect(10);
ByteBuffer from=BufferUtil.toBuffer("12345");
BufferUtil.clear(to);
assertEquals(5,BufferUtil.append(from,to));
assertTrue(BufferUtil.isEmpty(from));
assertEquals("12345",BufferUtil.toString(to));
from=BufferUtil.toBuffer("XX67890ZZ");
from.position(2);
assertEquals(5,BufferUtil.append(from,to));
assertEquals(2,from.remaining());
assertEquals("1234567890",BufferUtil.toString(to));
}
@Test
public void testToBuffer_Array()
{
byte arr[] = new byte[128];
Arrays.fill(arr,(byte)0x44);
ByteBuffer buf = BufferUtil.toBuffer(arr);
int count = 0;
while (buf.remaining() > 0)
{
byte b = buf.get();
Assert.assertEquals(b,0x44);
count++;
}
Assert.assertEquals("Count of bytes",arr.length,count);
}
@Test
public void testToBuffer_ArrayOffsetLength()
{
byte arr[] = new byte[128];
Arrays.fill(arr,(byte)0xFF); // fill whole thing with FF
int offset = 10;
int length = 100;
Arrays.fill(arr,offset,offset + length,(byte)0x77); // fill partial with 0x77
ByteBuffer buf = BufferUtil.toBuffer(arr,offset,length);
int count = 0;
while (buf.remaining() > 0)
{
byte b = buf.get();
Assert.assertEquals(b,0x77);
count++;
}
Assert.assertEquals("Count of bytes",length,count);
}
}

View File

@ -21,7 +21,6 @@ import java.nio.channels.SocketChannel;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicReference;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
@ -51,36 +50,12 @@ public class WebSocketClientSelectorManager extends SelectorManager
this.executor = executor;
}
@Override
protected void endPointClosed(AsyncEndPoint endpoint)
{
endpoint.getAsyncConnection().onClose();
}
@Override
protected void endPointOpened(AsyncEndPoint endpoint)
{
}
@Override
protected void endPointUpgraded(AsyncEndPoint endpoint, AsyncConnection oldConnection)
{
// TODO Investigate role of this with websocket
}
@Override
protected void execute(Runnable task)
{
// TODO Auto-generated method stub
}
@Override
protected int getMaxIdleTime()
{
return 0;
}
public SslContextFactory getSslContextFactory()
{
return sslContextFactory;

View File

@ -19,10 +19,13 @@ import java.nio.ByteBuffer;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.websocket.protocol.WebSocketFrame;
public class DataFrameBytes<C> extends FrameBytes<C>
{
private static final Logger LOG = Log.getLogger(DataFrameBytes.class);
private int size;
private ByteBuffer buffer;
@ -34,6 +37,11 @@ public class DataFrameBytes<C> extends FrameBytes<C>
@Override
public void completed(C context)
{
if (LOG.isDebugEnabled())
{
LOG.debug("completed({}) - frame.remaining() = {}",context,frame.remaining());
}
connection.getBufferPool().release(buffer);
if (frame.remaining() > 0)

View File

@ -340,14 +340,17 @@ public class WebSocketAsyncConnection extends AbstractAsyncConnection implements
private <C> void write(ByteBuffer buffer, WebSocketAsyncConnection webSocketAsyncConnection, FrameBytes<C> frameBytes)
{
AsyncEndPoint endpoint = getEndPoint();
if (LOG.isDebugEnabled())
{
LOG.debug("Writing {} frame bytes of {}",buffer.remaining(),frameBytes);
LOG.debug("EndPoint: {}",getEndPoint());
LOG.debug("EndPoint: {}",endpoint);
}
try
{
getEndPoint().write(frameBytes.context,frameBytes,buffer);
endpoint.write(frameBytes.context,frameBytes,buffer);
// endpoint.flush();
}
catch (Throwable t)
{

View File

@ -166,10 +166,13 @@ public class Generator
*/
public ByteBuffer generate(int bufferSize, WebSocketFrame frame)
{
LOG.debug(String.format("Generate.Frame[opcode=%s,fin=%b,cont=%b,rsv1=%b,rsv2=%b,rsv3=%b,mask=%b,plength=%d]",frame.getOpCode().toString(),
frame.isFin(),frame.isContinuation(),frame.isRsv1(),frame.isRsv2(),frame.isRsv3(),frame.isMasked(),frame.getPayloadLength()));
assertFrameValid(frame);
if (LOG.isDebugEnabled())
{
LOG.debug(String.format(
"Generate.Frame[opcode=%s,fin=%b,cont=%b,rsv1=%b,rsv2=%b,rsv3=%b,mask=%b,plength=%d,payloadStart=%s,remaining=%d,position=%s]",frame
.getOpCode().toString(),frame.isFin(),frame.isContinuation(),frame.isRsv1(),frame.isRsv2(),frame.isRsv3(),frame.isMasked(),frame
.getPayloadLength(),frame.getPayloadStart(),frame.remaining(),frame.position()));
}
/*
* prepare the byte buffer to put frame into
@ -177,6 +180,11 @@ public class Generator
ByteBuffer buffer = bufferPool.acquire(bufferSize,true);
BufferUtil.clearToFill(buffer);
if (frame.remaining() == frame.getPayloadLength())
{
// we need a framing header
assertFrameValid(frame);
/*
* start the generation process
*/
@ -261,33 +269,49 @@ public class Generator
{
buffer.put(frame.getMask());
}
// remember the position
int positionPrePayload = buffer.position();
}
// copy payload
if (frame.hasPayload())
{
buffer.put(frame.getPayload());
}
// remember the position
int maskingStartPosition = buffer.position();
int positionPostPayload = buffer.position();
// remember the offset within the frame payload (for working with
// windowed frames that don't split on 4 byte barriers)
int payloadOffset = frame.getPayload().position();
int payloadStart = frame.getPayloadStart();
// put as much as possible into the buffer
BufferUtil.put(frame.getPayload(),buffer);
// mask it if needed
if (frame.isMasked())
{
// move back to remembered position.
int size = positionPostPayload - positionPrePayload;
int size = buffer.position() - maskingStartPosition;
byte[] mask = frame.getMask();
int pos;
byte b;
int posBuf;
int posFrame;
for (int i = 0; i < size; i++)
{
pos = positionPrePayload + i;
posBuf = i + maskingStartPosition;
posFrame = i + (payloadOffset - payloadStart);
// get raw byte from buffer.
b = buffer.get(posBuf);
// mask, using offset information from frame windowing.
b ^= mask[posFrame % 4];
// Mask each byte by its absolute position in the bytebuffer
buffer.put(pos,(byte)(buffer.get(pos) ^ mask[i % 4]));
buffer.put(posBuf,b);
}
}
}
BufferUtil.flipToFlush(buffer,0);
return buffer;
}

View File

@ -93,6 +93,10 @@ public class WebSocketFrame implements Frame
* It is assumed to always be in FLUSH mode (ready to read) in this object.
*/
private ByteBuffer data;
private int payloadLength = 0;
/** position of start of data within a fresh payload */
private int payloadStart = -1;
private boolean continuation = false;
private int continuationIndex = 0;
@ -207,12 +211,20 @@ public class WebSocketFrame implements Frame
return opcode;
}
/**
* Get the payload ByteBuffer. possible null.
* <p>
*
* @return A {@link ByteBuffer#slice()} of the payload buffer (to prevent modification of the buffer state). Possibly null if no payload present.
* <p>
* Note: this method is exposed via the immutable {@link Frame#getPayload()} method.
*/
@Override
public ByteBuffer getPayload()
{
if (data != null)
{
return data.slice();
return data;
}
else
{
@ -236,12 +248,21 @@ public class WebSocketFrame implements Frame
{
return 0;
}
return data.remaining();
return payloadLength;
}
public int getPayloadStart()
{
if (data == null)
{
return -1;
}
return payloadStart;
}
public boolean hasPayload()
{
return ((data != null) && (data.remaining() > 0));
return ((data != null) && (payloadLength > 0));
}
public boolean isContinuation()
@ -284,6 +305,29 @@ public class WebSocketFrame implements Frame
return rsv3;
}
/**
* Get the position currently within the payload data.
* <p>
* Used by flow control, generator and window sizing.
*
* @return the number of bytes remaining in the payload data that has not yet been written out to Network ByteBuffers.
*/
public int position()
{
if (data == null)
{
return -1;
}
return data.position();
}
/**
* Get the number of bytes remaining to write out to the Network ByteBuffer.
* <p>
* Used by flow control, generator and window sizing.
*
* @return the number of bytes remaining in the payload data that has not yet been written out to Network ByteBuffers.
*/
public int remaining()
{
if (data == null)
@ -302,6 +346,7 @@ public class WebSocketFrame implements Frame
opcode = null;
masked = false;
data = null;
payloadLength = 0;
mask = null;
continuationIndex = 0;
continuation = false;
@ -366,11 +411,9 @@ public class WebSocketFrame implements Frame
}
}
int len = buf.length;
data = ByteBuffer.allocate(len);
BufferUtil.clearToFill(data);
data.put(buf,0,len);
BufferUtil.flipToFlush(data,0);
data = BufferUtil.toBuffer(buf);
payloadStart = data.position();
payloadLength = data.limit();
return this;
}
@ -396,10 +439,9 @@ public class WebSocketFrame implements Frame
}
}
data = ByteBuffer.allocate(len);
BufferUtil.clearToFill(data);
data.put(buf,0,len);
BufferUtil.flipToFlush(data,0);
data = BufferUtil.toBuffer(buf,offset,len);
payloadStart = data.position();
payloadLength = data.limit();
return this;
}
@ -430,6 +472,8 @@ public class WebSocketFrame implements Frame
}
data = buf.slice();
payloadStart = data.position();
payloadLength = data.limit();
return this;
}
@ -470,7 +514,7 @@ public class WebSocketFrame implements Frame
b.append("NO-OP");
}
b.append('[');
b.append("len=").append(getPayloadLength());
b.append("len=").append(payloadLength);
b.append(",fin=").append(fin);
b.append(",masked=").append(masked);
b.append(",continuation=").append(continuation);

View File

@ -2,22 +2,13 @@ package org.eclipse.jetty.websocket;
import org.eclipse.jetty.websocket.driver.EventMethodsCacheTest;
import org.eclipse.jetty.websocket.driver.WebSocketEventDriverTest;
import org.eclipse.jetty.websocket.protocol.AcceptHashTest;
import org.eclipse.jetty.websocket.protocol.ClosePayloadParserTest;
import org.eclipse.jetty.websocket.protocol.ParserTest;
import org.eclipse.jetty.websocket.protocol.PingPayloadParserTest;
import org.eclipse.jetty.websocket.protocol.RFC6455ExamplesGeneratorTest;
import org.eclipse.jetty.websocket.protocol.RFC6455ExamplesParserTest;
import org.eclipse.jetty.websocket.protocol.TextPayloadParserTest;
import org.eclipse.jetty.websocket.protocol.WebSocketFrameTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses(
{ org.eclipse.jetty.websocket.ab.AllTests.class, EventMethodsCacheTest.class, WebSocketEventDriverTest.class, AcceptHashTest.class,
ClosePayloadParserTest.class, ParserTest.class, PingPayloadParserTest.class, RFC6455ExamplesGeneratorTest.class, RFC6455ExamplesParserTest.class,
TextPayloadParserTest.class, WebSocketFrameTest.class, GeneratorParserRoundtripTest.class })
{ org.eclipse.jetty.websocket.ab.AllTests.class, EventMethodsCacheTest.class, WebSocketEventDriverTest.class,
org.eclipse.jetty.websocket.protocol.AllTests.class, GeneratorParserRoundtripTest.class })
public class AllTests
{
/* nothing to do here */

View File

@ -0,0 +1,13 @@
package org.eclipse.jetty.websocket.protocol;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses(
{ AcceptHashTest.class, ClosePayloadParserTest.class, GeneratorTest.class, ParserTest.class, PingPayloadParserTest.class, RFC6455ExamplesGeneratorTest.class,
RFC6455ExamplesParserTest.class, TextPayloadParserTest.class, WebSocketFrameTest.class })
public class AllTests
{
/* allow junit annotations to do the heavy lifting */
}

View File

@ -0,0 +1,115 @@
package org.eclipse.jetty.websocket.protocol;
import static org.hamcrest.Matchers.*;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.websocket.api.WebSocketPolicy;
import org.junit.Assert;
import org.junit.Test;
public class GeneratorTest
{
@Test
public void testWindowedGenerate()
{
byte payload[] = new byte[10240];
Arrays.fill(payload,(byte)0x44);
WebSocketFrame frame = WebSocketFrame.binary(payload);
int totalParts = 0;
int totalBytes = 0;
int windowSize = 1024;
int expectedHeaderSize = 4;
int expectedParts = (int)Math.ceil((double)(payload.length + expectedHeaderSize) / windowSize);
Generator generator = new UnitGenerator();
boolean done = false;
while (!done)
{
Assert.assertThat("Too many parts",totalParts,lessThan(20));
ByteBuffer buf = generator.generate(windowSize,frame);
// System.out.printf("Generated buf.limit() = %,d%n",buf.limit());
totalBytes += buf.remaining();
totalParts++;
done = (frame.remaining() <= 0);
}
Assert.assertThat("Created Parts",totalParts,is(expectedParts));
Assert.assertThat("Created Bytes",totalBytes,is(payload.length + expectedHeaderSize));
}
@Test
public void testWindowedGenerateWithMasking()
{
byte payload[] = new byte[10240];
Arrays.fill(payload,(byte)0x55);
byte mask[] = new byte[]
{ 0x2A, (byte)0xF0, 0x0F, 0x00 };
WebSocketFrame frame = WebSocketFrame.binary(payload);
frame.setMask(mask);
int totalParts = 0;
int totalBytes = 0;
int windowSize = 2929; // important, use an odd # window size to test masking across window barriers
int expectedHeaderSize = 8;
int expectedParts = (int)Math.ceil((double)(payload.length + expectedHeaderSize) / windowSize);
// Buffer to capture generated bytes
ByteBuffer completeBuf = ByteBuffer.allocate(payload.length + expectedHeaderSize);
BufferUtil.clearToFill(completeBuf);
// Generate and capture generator output
Generator generator = new UnitGenerator();
boolean done = false;
while (!done)
{
Assert.assertThat("Too many parts",totalParts,lessThan(20));
ByteBuffer buf = generator.generate(windowSize,frame);
// System.out.printf("Generated buf.limit() = %,d%n",buf.limit());
totalBytes += buf.remaining();
totalParts++;
BufferUtil.put(buf,completeBuf);
done = (frame.remaining() <= 0);
}
Assert.assertThat("Created Parts",totalParts,is(expectedParts));
Assert.assertThat("Created Bytes",totalBytes,is(payload.length + expectedHeaderSize));
// Parse complete buffer.
WebSocketPolicy policy = WebSocketPolicy.newServerPolicy();
Parser parser = new Parser(policy);
FrameParseCapture capture = new FrameParseCapture();
parser.setIncomingFramesHandler(capture);
BufferUtil.flipToFlush(completeBuf,0);
parser.parse(completeBuf);
// Assert validity of frame
WebSocketFrame actual = capture.getFrames().get(0);
Assert.assertThat("Frame.opcode",actual.getOpCode(),is(OpCode.BINARY));
Assert.assertThat("Frame.payloadLength",actual.getPayloadLength(),is(payload.length));
// Validate payload content for proper masking
ByteBuffer actualData = actual.getPayload().slice();
Assert.assertThat("Frame.payload.remaining",actualData.remaining(),is(payload.length));
while (actualData.remaining() > 0)
{
Assert.assertThat("Actual.payload[" + actualData.position() + "]",actualData.get(),is((byte)0x55));
}
}
}

View File

@ -303,7 +303,7 @@ public class XmlConfiguration
public void init(URL url, XmlParser.Node config, Map<String, Object> idMap, Map<String, String> properties)
{
_url=url.toString();
_url=url==null?null:url.toString();
_config=config;
_idMap=idMap;
_propertyMap=properties;

View File

@ -13,15 +13,15 @@
package org.eclipse.jetty.xml;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class XmlConfigurationTest
{
protected String _configure="org/eclipse/jetty/xml/configure.xml";
@ -31,14 +31,14 @@ public class XmlConfigurationTest
{
URL url = XmlConfigurationTest.class.getClassLoader().getResource("org/eclipse/jetty/xml/mortbay.xml");
XmlConfiguration configuration = new XmlConfiguration(url);
Object o=configuration.configure();
configuration.configure();
}
@Test
public void testPassedObject() throws Exception
{
TestConfiguration.VALUE=77;
Map<String,String> properties = new HashMap<String,String>();
Map<String,String> properties = new HashMap<>();
properties.put("whatever", "xxx");
URL url = XmlConfigurationTest.class.getClassLoader().getResource(_configure);
@ -54,18 +54,18 @@ public class XmlConfigurationTest
assertEquals("Put","PutValue",tc.get("Test"));
assertEquals("Put dft","2",tc.get("TestDft"));
assertEquals("Put type",new Integer(2),tc.get("TestInt"));
assertEquals("Put type",2,tc.get("TestInt"));
assertEquals("Trim","PutValue",tc.get("Trim"));
assertEquals("Null",null,tc.get("Null"));
assertEquals("NullTrim",null,tc.get("NullTrim"));
assertEquals("ObjectTrim",new Double(1.2345),tc.get("ObjectTrim"));
assertEquals("ObjectTrim",1.2345,tc.get("ObjectTrim"));
assertEquals("Objects","-1String",tc.get("Objects"));
assertEquals( "ObjectsTrim", "-1String",tc.get("ObjectsTrim"));
assertEquals( "String", "\n PutValue\n ",tc.get("String"));
assertEquals( "NullString", "",tc.get("NullString"));
assertEquals( "WhateSpace", "\n ",tc.get("WhiteSpace"));
assertEquals( "WhiteSpace", "\n ",tc.get("WhiteSpace"));
assertEquals( "ObjectString", "\n 1.2345\n ",tc.get("ObjectString"));
assertEquals( "ObjectsString", "-1String",tc.get("ObjectsString"));
assertEquals( "ObjectsWhiteString", "-1\n String",tc.get("ObjectsWhiteString"));
@ -82,7 +82,7 @@ public class XmlConfigurationTest
assertEquals("oa[0]","Blah",tc.oa[0]);
assertEquals("oa[1]","1.2.3.4:5678",tc.oa[1]);
assertEquals("oa[2]",new Double(1.2345),tc.oa[2]);
assertEquals("oa[2]",1.2345,tc.oa[2]);
assertEquals("oa[3]",null,tc.oa[3]);
assertEquals("ia[0]",1,tc.ia[0]);
@ -92,10 +92,10 @@ public class XmlConfigurationTest
TestConfiguration tc2=tc.nested;
assertTrue(tc2!=null);
assertEquals( "Called(bool)", new Boolean(true),tc2.get("Arg"));
assertEquals( "Called(bool)",true,tc2.get("Arg"));
assertEquals("nested config",null,tc.get("Arg"));
assertEquals("nested config",new Boolean(true),tc2.get("Arg"));
assertEquals("nested config",true,tc2.get("Arg"));
assertEquals("nested config","Call1",tc2.testObject);
assertEquals("nested config",4,tc2.testInt);
@ -110,7 +110,7 @@ public class XmlConfigurationTest
public void testNewObject() throws Exception
{
TestConfiguration.VALUE=71;
Map<String,String> properties = new HashMap<String,String>();
Map<String,String> properties = new HashMap<>();
properties.put("whatever", "xxx");
URL url = XmlConfigurationTest.class.getClassLoader().getResource(_configure);
@ -125,18 +125,18 @@ public class XmlConfigurationTest
assertEquals("Put","PutValue",tc.get("Test"));
assertEquals("Put dft","2",tc.get("TestDft"));
assertEquals("Put type",new Integer(2),tc.get("TestInt"));
assertEquals("Put type",2,tc.get("TestInt"));
assertEquals("Trim","PutValue",tc.get("Trim"));
assertEquals("Null",null,tc.get("Null"));
assertEquals("NullTrim",null,tc.get("NullTrim"));
assertEquals("ObjectTrim",new Double(1.2345),tc.get("ObjectTrim"));
assertEquals("ObjectTrim",1.2345,tc.get("ObjectTrim"));
assertEquals("Objects","-1String",tc.get("Objects"));
assertEquals( "ObjectsTrim", "-1String",tc.get("ObjectsTrim"));
assertEquals( "String", "\n PutValue\n ",tc.get("String"));
assertEquals( "NullString", "",tc.get("NullString"));
assertEquals( "WhateSpace", "\n ",tc.get("WhiteSpace"));
assertEquals( "WhiteSpace", "\n ",tc.get("WhiteSpace"));
assertEquals( "ObjectString", "\n 1.2345\n ",tc.get("ObjectString"));
assertEquals( "ObjectsString", "-1String",tc.get("ObjectsString"));
assertEquals( "ObjectsWhiteString", "-1\n String",tc.get("ObjectsWhiteString"));
@ -151,7 +151,7 @@ public class XmlConfigurationTest
assertEquals("oa[0]","Blah",tc.oa[0]);
assertEquals("oa[1]","1.2.3.4:5678",tc.oa[1]);
assertEquals("oa[2]",new Double(1.2345),tc.oa[2]);
assertEquals("oa[2]",1.2345,tc.oa[2]);
assertEquals("oa[3]",null,tc.oa[3]);
assertEquals("ia[0]",1,tc.ia[0]);
@ -161,10 +161,10 @@ public class XmlConfigurationTest
TestConfiguration tc2=tc.nested;
assertTrue(tc2!=null);
assertEquals( "Called(bool)", new Boolean(true),tc2.get("Arg"));
assertEquals( "Called(bool)",true,tc2.get("Arg"));
assertEquals("nested config",null,tc.get("Arg"));
assertEquals("nested config",new Boolean(true),tc2.get("Arg"));
assertEquals("nested config",true,tc2.get("Arg"));
assertEquals("nested config","Call1",tc2.testObject);
assertEquals("nested config",4,tc2.testInt);