FileDocCategorySizeDatePackage
CometWriter.javaAPI DocGlassfish v2 API4961Tue Jul 10 13:20:24 BST 2007com.sun.enterprise.web.connector.grizzly.comet

CometWriter

public class CometWriter extends Object
Non blocking Writer. This class can be used from a CometHandler to execute non blocking write. If the write was incomplete, the CometHandler must register itself using CometContext.registerAsyncWrite()
author
Jeanfrancois Arcand

Fields Summary
private boolean
isComplete
private SocketChannel
socketChannel
protected byte[]
chunkLength
Buffer used for chunk length conversion.
private static final ByteBuffer
end
private boolean
ready
Is this CometWriter ready
Constructors Summary
public CometWriter()

  
    
    
      
        chunkLength = new byte[10];
        chunkLength[8] = (byte) '\r";
        chunkLength[9] = (byte) '\n";
    
Methods Summary
public booleanisComplete()

        return isComplete;
    
public booleanisReady()
Return true if this instance is ready to read.

        return ready;
    
public voidrecycle()

        isComplete = true;
        socketChannel = null;
    
protected voidsetChannel(java.nio.channels.SocketChannel socketChannel)

      
        this.socketChannel = socketChannel;
    
public voidsetReady(boolean ready)
false if this instance is no longer ready to read.

        this.ready = ready;
    
public intwrite(byte[] buf)

        return write(buf,0,buf.length);
    
public intwrite(byte[] buf, int off, int len)

        if (!ready){
            throw new IllegalStateException("This CometWriter is no longer usable.");
        }
        int pos = 7;
        int current = len;
                
        // Force a blocking read.
        if (isComplete) {
            while (current > 0) {
                int digit = current % 16;
                current = current / 16;
                chunkLength[pos--] = HexUtils.HEX[digit];
            }     

            OutputWriter.flushChannel(socketChannel, 
                    ByteBuffer.wrap(chunkLength, pos + 1, 9 - pos));
        }
        
        int nWrite = socketChannel.write(ByteBuffer.wrap(buf,off,len));    
        if (nWrite == len) {
            isComplete = true;
            OutputWriter.flushChannel(socketChannel,
                    ByteBuffer.wrap(chunkLength, 8, 2));
            OutputWriter.flushChannel(socketChannel,end.slice());
        } else {
            isComplete = false;
        }
        return nWrite;