Top Description Inners Fields Constructors Methods
org.glassfish.grizzly.http.io

public Class OutputBuffer

extends Object
Class Inheritance
Imports
java.io.EOFException, .File, .IOException, java.nio.ByteBuffer, .CharBuffer, java.nio.charset.Charset, .CharsetEncoder, .CoderResult, .CodingErrorAction, java.util.ArrayList, .HashMap, .List, .Map, java.util.concurrent.CancellationException, .ExecutionException, .Executor, .ExecutorService, .TimeUnit, .TimeoutException, java.util.function.Supplier, java.util.logging.Level, .Logger, org.glassfish.grizzly.Buffer, .CloseReason, .CompletionHandler, .Connection, .FileTransfer, .Grizzly, .IOEvent, .WriteHandler, .WriteResult, .Writer.Reentrant, org.glassfish.grizzly.asyncqueue.AsyncQueueWriter, .MessageCloner, org.glassfish.grizzly.filterchain.FilterChainContext, org.glassfish.grizzly.http.HttpContent, .HttpContent.Builder, .HttpContext, .HttpHeader, .HttpServerFilter, .HttpTrailer, .Protocol, org.glassfish.grizzly.http.util.Header, .HeaderValue, .MimeType, org.glassfish.grizzly.impl.FutureImpl, org.glassfish.grizzly.memory.Buffers, .CompositeBuffer, .MemoryManager, org.glassfish.grizzly.threadpool.Threads, org.glassfish.grizzly.utils.Charsets, .Exceptions, .Futures

Abstraction exposing both byte and character methods to write content to the HTTP messaging system in Grizzly.

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv static class
OutputBuffer.ByteArrayCloner

The MessageCloner, responsible for cloning Buffer content, if it wasn't possible to write it in the current Thread (it was added to async write queue).

private static class
public static interface

Field Summary

Modifier and TypeField and Description
private OutputBuffer.InternalWriteHandler
private int
private HttpContent.Builder<T extends HttpContent.Builder>
private char[]
private int
private CharBuffer
private final OutputBuffer.ByteArrayCloner
private boolean
private boolean
private CompositeBuffer
private Connection<L>
private FilterChainContext
private Buffer
private static final int
private CharsetEncoder
private final Map<String, CharsetEncoder>
private boolean
private boolean
private volatile WriteHandler
private boolean
private HttpContext
private static final boolean
IS_BLOCKING

Flag indicating whether or not async operations are being used on the input streams.

private boolean
private boolean
private final List<OutputBuffer.LifeCycleListener>
protected static final Logger
private static final int
private MemoryManager<E extends Buffer>
private static final int
private HttpHeader
protected boolean
private final TemporaryHeapBuffer
private Supplier<Map<String, String>>
private Runnable

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
protected void
public boolean
canWrite(final int length)
Deprecated the length parameter will be ignored. Please use canWrite().

public boolean
public boolean
canWriteChar(final int length)
Deprecated

private boolean
private void
private void
private void
public void
private boolean
public void
private void
public void
flush()

Flush the response.

private boolean
flushAllBuffers(final boolean isLast)

private boolean
flushBinaryBuffers(final boolean isLast)

private void
private void
flushBuffer(final Buffer bufferToFlush, final boolean isLast, final MessageCloner<Buffer> messageCloner)

private void
flushCharsToBuf(final boolean canFlushToNet)

private void
flushCharsToBuf(final CharBuffer charBuf, final boolean canFlushToNet)

private void
forceCommitHeaders(final boolean isLast)

public int

Returns:

the number of bytes buffered on OutputBuffer and ready to be sent.
getBufferedDataSize
()

Get the number of bytes buffered on OutputBuffer and ready to be sent.

public int
private CharsetEncoder
protected Executor
getThreadPool()

Returns: Executor, which will be used for notifying user registered WriteHandler.

public Supplier<Map<String, String>>
public void
initialize(final HttpHeader outputHeader, final boolean sendfileEnabled, final FilterChainContext ctx)

public boolean

Returns:

true if content will be written in a non-blocking fashion, otherwise returns false.
isAsyncEnabled
()
Deprecated will always return true

Returns true if content will be written in a non-blocking fashion, otherwise returns false.

public boolean
isClosed()

Returns: true if this OutputBuffer is closed, otherwise returns false.

public void
notifyCanWrite(final WriteHandler handler, final int length)
Deprecated the length parameter will be ignored.

public void
private void
private void
notifyWritePossible()

Notify WriteHandler

private void
notifyWritePossibleAsync()

Notify WriteHandler asynchronously

public void
public void
recycle()

Recycle the output buffer.

public void
public boolean
public void
reset()

Reset current response.

public void
sendfile(final File
the File to transfer.
file
,
final CompletionHandler<WriteResult<K, L>>
CompletionHandler that will be notified of the transfer progress/completion or failure.
handler
)

Calls write(file, 0, file.length()).

public void
sendfile(final File
the File to transfer.
file
,
final long
the starting offset within the File
offset
,
final long
the total number of bytes to transfer
length
,
final CompletionHandler<WriteResult<K, L>>
CompletionHandler that will be notified of the transfer progress/completion or failure.
handler
)

Will use java.nio.channels.FileChannel#transferTo(long, long, java.nio.channels.WritableByteChannel) to send file to the remote endpoint.

public void
setAsyncEnabled(boolean
true if this OutputBuffer will write content without blocking. @since 2.1.2 @deprecated OutputBuffer always supports async mode
asyncEnabled
)
Deprecated

Sets the asynchronous processing state of this OutputBuffer.

public void
setBufferSize(final int bufferSize)

public void
setTrailers(Supplier<Map<String, String>> trailersSupplier)

private void
public void
write(char[] cbuf, int off, int len)

public void
write(final char[] cbuf)

public void
write(final String str)

public void
write(final String str, final int off, final int len)

public void
write(final byte[] b)

public void
write(final byte[] b, final int off, final int len)

public void
writeBuffer(final Buffer
the Buffer to write
buffer
)

Writes the contents of the specified Buffer to the client.

public void
writeByte(final int b)

public void
writeByteBuffer(final ByteBuffer
the ByteBuffer to write
byteBuffer
)

Writes the contents of the specified ByteBuffer to the client.

public void
writeChar(int c)

public void
writeInterimResponse()

Flush a pending informational (1xx) interim response — either a 100-Continue acknowledgement of an Expect header, or any other interim status such as 103 Early Hints — without committing the response.

private boolean
private boolean
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

asyncWriteHandlerback to summary
private OutputBuffer.InternalWriteHandler asyncWriteHandler
bufferSizeback to summary
private int bufferSize
builderback to summary
private HttpContent.Builder<T extends HttpContent.Builder> builder
charsArrayback to summary
private char[] charsArray
charsArrayLengthback to summary
private int charsArrayLength
charsBufferback to summary
private CharBuffer charsBuffer
clonerback to summary
private final OutputBuffer.ByteArrayCloner cloner
closedback to summary
private boolean closed
committedback to summary
private boolean committed
compositeBufferback to summary
private CompositeBuffer compositeBuffer
connectionback to summary
private Connection<L> connection
ctxback to summary
private FilterChainContext ctx
currentBufferback to summary
private Buffer currentBuffer
DEFAULT_BUFFER_SIZEback to summary
private static final int DEFAULT_BUFFER_SIZE
encoderback to summary
private CharsetEncoder encoder
encodersback to summary
private final Map<String, CharsetEncoder> encoders
fileTransferRequestedback to summary
private boolean fileTransferRequested
finishedback to summary
private boolean finished
handlerback to summary
private volatile WriteHandler handler
headersWrittenback to summary
private boolean headersWritten
httpContextback to summary
private HttpContext httpContext
IS_BLOCKINGback to summary
private static final boolean IS_BLOCKING

Flag indicating whether or not async operations are being used on the input streams.

isLastWriteNonBlockingback to summary
private boolean isLastWriteNonBlocking
isNonBlockingWriteGuaranteedback to summary
private boolean isNonBlockingWriteGuaranteed
lifeCycleListenersback to summary
private final List<OutputBuffer.LifeCycleListener> lifeCycleListeners
LOGGERback to summary
protected static final Logger LOGGER
MAX_CHAR_BUFFER_SIZEback to summary
private static final int MAX_CHAR_BUFFER_SIZE
memoryManagerback to summary
private MemoryManager<E extends Buffer> memoryManager
MIN_BUFFER_SIZEback to summary
private static final int MIN_BUFFER_SIZE
outputHeaderback to summary
private HttpHeader outputHeader
sendfileEnabledback to summary
protected boolean sendfileEnabled
temporaryWriteBufferback to summary
private final TemporaryHeapBuffer temporaryWriteBuffer
trailersSupplierback to summary
private Supplier<Map<String, String>> trailersSupplier
writePossibleRunnableback to summary
private Runnable writePossibleRunnable

Constructor Detail

OutputBufferback to summary
public OutputBuffer()

Method Detail

blockAfterWriteIfNeededback to summary
protected void blockAfterWriteIfNeeded() throws IOException
canWriteback to summary
public boolean canWrite(final int length)

Deprecated

the length parameter will be ignored. Please use canWrite().

Annotations
@Deprecated
@SuppressWarnings:UnusedParameters
See Also
AsyncQueueWriter#canWrite(org.glassfish.grizzly.Connection, int)
canWriteback to summary
public boolean canWrite()
See Also
AsyncQueueWriter#canWrite(org.glassfish.grizzly.Connection)
canWriteCharback to summary
public boolean canWriteChar(final int length)

Deprecated

Annotations
@SuppressWarnings:UnusedDeclaration
@Deprecated
canWritePayloadChunkback to summary
private boolean canWritePayloadChunk()
checkCharBufferback to summary
private void checkCharBuffer()
checkCompositeBufferback to summary
private void checkCompositeBuffer()
checkCurrentBufferback to summary
private void checkCurrentBuffer()
closeback to summary
public void close() throws IOException
doCommitback to summary
private boolean doCommit() throws IOException
endRequestback to summary
public void endRequest() throws IOException
finishCurrentBufferback to summary
private void finishCurrentBuffer()
flushback to summary
public void flush() throws IOException

Flush the response.

Exceptions
IOException:
an underlying I/O error occurred
flushAllBuffersback to summary
private boolean flushAllBuffers(final boolean isLast) throws IOException
flushBinaryBuffersback to summary
private boolean flushBinaryBuffers(final boolean isLast) throws IOException
flushBinaryBuffersIfNeededback to summary
private void flushBinaryBuffersIfNeeded() throws IOException
flushBufferback to summary
private void flushBuffer(final Buffer bufferToFlush, final boolean isLast, final MessageCloner<Buffer> messageCloner) throws IOException
flushCharsToBufback to summary
private void flushCharsToBuf(final boolean canFlushToNet) throws IOException
flushCharsToBufback to summary
private void flushCharsToBuf(final CharBuffer charBuf, final boolean canFlushToNet) throws IOException
forceCommitHeadersback to summary
private void forceCommitHeaders(final boolean isLast) throws IOException
getBufferedDataSizeback to summary
public int getBufferedDataSize()

Get the number of bytes buffered on OutputBuffer and ready to be sent.

Returns:int

the number of bytes buffered on OutputBuffer and ready to be sent.

Annotations
@SuppressWarnings:UnusedDeclaration
getBufferSizeback to summary
public int getBufferSize()
getEncoderback to summary
private CharsetEncoder getEncoder()
getThreadPoolback to summary
protected Executor getThreadPool()
Returns:Executor

Executor, which will be used for notifying user registered WriteHandler.

getTrailersback to summary
public Supplier<Map<String, String>> getTrailers()
initializeback to summary
public void initialize(final HttpHeader outputHeader, final boolean sendfileEnabled, final FilterChainContext ctx)
isAsyncEnabledback to summary
public boolean isAsyncEnabled()

Deprecated

will always return true

Returns true if content will be written in a non-blocking fashion, otherwise returns false.

Returns:boolean

true if content will be written in a non-blocking fashion, otherwise returns false.

Annotations
@Deprecated
@SuppressWarnings:UnusedDeclaration
Since
2.1.2
isClosedback to summary
public boolean isClosed()
Returns:boolean

true if this OutputBuffer is closed, otherwise returns false.

Annotations
@SuppressWarnings:UnusedDeclaration
notifyCanWriteback to summary
public void notifyCanWrite(final WriteHandler handler, final int length)

Deprecated

the length parameter will be ignored. Please use notifyCanWrite(org.glassfish.grizzly.WriteHandler).

Annotations
@Deprecated
@SuppressWarnings:UnusedParameters
See Also
AsyncQueueWriter#notifyWritePossible(org.glassfish.grizzly.Connection, org.glassfish.grizzly.WriteHandler, int)
notifyCanWriteback to summary
public void notifyCanWrite(final WriteHandler handler)
notifyCommitback to summary
private void notifyCommit() throws IOException
notifyWritePossibleback to summary
private void notifyWritePossible()

Notify WriteHandler

notifyWritePossibleAsyncback to summary
private void notifyWritePossibleAsync()

Notify WriteHandler asynchronously

prepareCharacterEncoderback to summary
public void prepareCharacterEncoder()
recycleback to summary
public void recycle()

Recycle the output buffer. This should be called when closing the connection.

registerLifeCycleListenerback to summary
public void registerLifeCycleListener(final OutputBuffer.LifeCycleListener listener)
Annotations
@SuppressWarnings:UnusedDeclaration
removeLifeCycleListenerback to summary
public boolean removeLifeCycleListener(final OutputBuffer.LifeCycleListener listener)
Annotations
@SuppressWarnings:UnusedDeclaration
resetback to summary
public void reset()

Reset current response.

Exceptions
IllegalStateException:
if the response has already been committed
sendfileback to summary
public void sendfile(final File file, final CompletionHandler<WriteResult<K, L>> handler)

Calls write(file, 0, file.length()).

Parameters
file:File

the File to transfer.

handler:CompletionHandler<WriteResult<K, L>>

CompletionHandler that will be notified of the transfer progress/completion or failure.

Exceptions
IllegalArgumentException:
if file is null
Since
2.2
See Also
sendfile(java.io.File, long, long, org.glassfish.grizzly.CompletionHandler)
sendfileback to summary
public void sendfile(final File file, final long offset, final long length, final CompletionHandler<WriteResult<K, L>> handler)

Will use java.nio.channels.FileChannel#transferTo(long, long, java.nio.channels.WritableByteChannel) to send file to the remote endpoint. Note that all headers necessary for the file transfer must be set prior to invoking this method as this will case the HTTP header to be flushed to the client prior to sending the file content. This should also be the last call to write any content to the remote endpoint.

It's required that the response be suspended when using this functionality. It will be assumed that if the response wasn't suspended when this method is called, that it's desired that this method manages the suspend/resume cycle.

Parameters
file:File

the File to transfer.

offset:long

the starting offset within the File

length:long

the total number of bytes to transfer

handler:CompletionHandler<WriteResult<K, L>>

CompletionHandler that will be notified of the transfer progress/completion or failure.

Exceptions
IllegalArgumentException:
if the response has already been committed at the time this method was invoked.
IllegalStateException:
  • if a file transfer request has already been made or if send file support isn't available.
  • if the response was in a suspended state when this method was invoked, but no CompletionHandler was provided.
Since
2.2
setAsyncEnabledback to summary
public void setAsyncEnabled(boolean asyncEnabled)

Deprecated

Sets the asynchronous processing state of this OutputBuffer.

Parameters
asyncEnabled:boolean

true if this OutputBuffer will write content without blocking. @since 2.1.2 @deprecated OutputBuffer always supports async mode

Annotations
@Deprecated
@SuppressWarnings:UnusedDeclaration
setBufferSizeback to summary
public void setBufferSize(final int bufferSize)
setTrailersback to summary
public void setTrailers(Supplier<Map<String, String>> trailersSupplier)
updateNonBlockingStatusback to summary
private void updateNonBlockingStatus()
writeback to summary
public void write(char[] cbuf, int off, int len) throws IOException
writeback to summary
public void write(final char[] cbuf) throws IOException
writeback to summary
public void write(final String str) throws IOException
writeback to summary
public void write(final String str, final int off, final int len) throws IOException
writeback to summary
public void write(final byte[] b) throws IOException
writeback to summary
public void write(final byte[] b, final int off, final int len) throws IOException
writeBufferback to summary
public void writeBuffer(final Buffer buffer) throws IOException

Writes the contents of the specified Buffer to the client.

Note, that passed Buffer will be directly used by underlying connection, so it could be reused only if it has been flushed.
Parameters
buffer:Buffer

the Buffer to write

Exceptions
IOException:
if an error occurs during the write
writeByteback to summary
public void writeByte(final int b) throws IOException
writeByteBufferback to summary
public void writeByteBuffer(final ByteBuffer byteBuffer) throws IOException

Writes the contents of the specified ByteBuffer to the client.

Note, that passed ByteBuffer will be directly used by underlying connection, so it could be reused only if it has been flushed.
Parameters
byteBuffer:ByteBuffer

the ByteBuffer to write

Annotations
@SuppressWarnings:unchecked, UnusedDeclaration
Exceptions
IOException:
if an error occurs during the write
writeCharback to summary
public void writeChar(int c) throws IOException
writeInterimResponseback to summary
public void writeInterimResponse() throws IOException

Flush a pending informational (1xx) interim response — either a 100-Continue acknowledgement of an Expect header, or any other interim status such as 103 Early Hints — without committing the response. The interim status must have been set on the response packet via org.glassfish.grizzly.http.HttpResponsePacket#setInterimStatus before invoking this method.

Exceptions
IOException:
if an error occurs writing the interim response.
writingBytesback to summary
private boolean writingBytes()
writingCharsback to summary
private boolean writingChars()
org.glassfish.grizzly.http.io back to summary

pack-priv final Class OutputBuffer.ByteArrayCloner

extends Object
implements MessageCloner<Buffer>
Class Inheritance
All Implemented Interfaces
org.glassfish.grizzly.asyncqueue.MessageCloner

The MessageCloner, responsible for cloning Buffer content, if it wasn't possible to write it in the current Thread (it was added to async write queue). We do this, because write(byte[], int, int) method is not aware of async write queues, and content of the passed byte[] might be changed by user application once in gets control back.

Field Summary

Modifier and TypeField and Description
private final TemporaryHeapBuffer

Constructor Summary

AccessConstructor and Description
public
ByteArrayCloner(final TemporaryHeapBuffer temporaryWriteBuffer)

Method Summary

Modifier and TypeMethod and Description
public Buffer
clone(final Connection<L> connection, final Buffer originalMessage)

Implements org.glassfish.grizzly.asyncqueue.MessageCloner.clone.

Method will be called by AsyncQueueWriter, when message could not be written directly, and will be added to the queue.

pack-priv Buffer
clone0(final MemoryManager<E extends Buffer> memoryManager, final Buffer originalMessage)

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

temporaryWriteBufferback to summary
private final TemporaryHeapBuffer temporaryWriteBuffer

Constructor Detail

ByteArrayClonerback to summary
public ByteArrayCloner(final TemporaryHeapBuffer temporaryWriteBuffer)

Method Detail

cloneback to summary
public Buffer clone(final Connection<L> connection, final Buffer originalMessage)

Implements org.glassfish.grizzly.asyncqueue.MessageCloner.clone.

Doc from org.glassfish.grizzly.asyncqueue.MessageCloner.clone.

Method will be called by AsyncQueueWriter, when message could not be written directly, and will be added to the queue. Cloner may create a clone of original message and return it to the AsyncQueueWriter instead of original one. Using MessageCloner, developer has a chance to clone a message only in case, when it is really required.

Annotations
@Override
clone0back to summary
pack-priv Buffer clone0(final MemoryManager<E extends Buffer> memoryManager, final Buffer originalMessage)
org.glassfish.grizzly.http.io back to summary

private Class OutputBuffer.InternalWriteHandler

extends Object
implements WriteHandler
Class Inheritance
  • java.lang.Object
  • org.glassfish.grizzly.http.io.OutputBuffer.InternalWriteHandler
All Implemented Interfaces
org.glassfish.grizzly.WriteHandler

Field Summary

Modifier and TypeField and Description
private volatile OutputBuffer

Constructor Summary

AccessConstructor and Description
public
InternalWriteHandler(final OutputBuffer outputBuffer)

Method Summary

Modifier and TypeMethod and Description
public void
public void
onError(final Throwable t)

Implements org.glassfish.grizzly.WriteHandler.onError.

Invoked when an error occurs processing the request asynchronously.

private static void
onError0(final OutputBuffer ob, final Throwable t)

public void
onWritePossible()

Implements org.glassfish.grizzly.WriteHandler.onWritePossible.

This callback will be invoked when the requirements as dictated by writer are met.

private static void
Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

outputBufferback to summary
private volatile OutputBuffer outputBuffer

Constructor Detail

InternalWriteHandlerback to summary
public InternalWriteHandler(final OutputBuffer outputBuffer)

Method Detail

detachback to summary
public void detach()
onErrorback to summary
public void onError(final Throwable t)

Implements org.glassfish.grizzly.WriteHandler.onError.

Doc from org.glassfish.grizzly.WriteHandler.onError.

Invoked when an error occurs processing the request asynchronously.

Annotations
@Override
onError0back to summary
private static void onError0(final OutputBuffer ob, final Throwable t)
onWritePossibleback to summary
public void onWritePossible() throws Exception

Implements org.glassfish.grizzly.WriteHandler.onWritePossible.

Doc from org.glassfish.grizzly.WriteHandler.onWritePossible.

This callback will be invoked when the requirements as dictated by writer are met.

Annotations
@Override
Exceptions
Exception:
Exception might be thrown by the custom handler code. This exception will be delegated for processing to onError(java.lang.Throwable).
onWritePossible0back to summary
private static void onWritePossible0(final OutputBuffer ob) throws Exception
org.glassfish.grizzly.http.io back to summary

public Interface OutputBuffer.LifeCycleListener


Method Summary

Modifier and TypeMethod and Description
public void

Method Detail

onCommitback to summary
public void onCommit() throws IOException