Element Summary

ElementDescriptionClass
blacklistFilterA {@link IoFilter} which blocks connections from blacklisted remote address.org.apache.mina.filter.firewall.BlacklistFilter
bufferedWriteFilterAn {@link IoFilter} implementation used to buffer outgoing {@link WriteRequest} almost like what {@link BufferedOutputStream} does. Using this filter allows to be less dependent from network latency. It is also useful when a session is generating very small messages too frequently and consequently generating unnecessary traffic overhead. Please note that it should always be placed before the {@link ProtocolCodecFilter} as it only handles {@link WriteRequest}'s carrying {@link IoBuffer} objects.org.apache.mina.filter.buffer.BufferedWriteFilter
defaultIoFilterChainBuilderThe default implementation of {@link IoFilterChainBuilder} which is useful in most cases. {@link DefaultIoFilterChainBuilder} has an identical interface with {@link IoFilter}; it contains a list of {@link IoFilter}s that you can modify. The {@link IoFilter}s which are added to this builder will be appended to the {@link IoFilterChain} when {@link #buildFilterChain(IoFilterChain)} is invoked.

However, the identical interface doesn't mean that it behaves in an exactly same way with {@link IoFilterChain}. {@link DefaultIoFilterChainBuilder} doesn't manage the life cycle of the {@link IoFilter}s at all, and the existing {@link IoSession}s won't get affected by the changes in this builder. {@link IoFilterChainBuilder}s affect only newly created {@link IoSession}s.

IoAcceptor acceptor = ...;
DefaultIoFilterChainBuilder builder = acceptor.getFilterChain();
builder.addLast( "myFilter", new MyFilter() );
...
org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder
errorGeneratingFilterAn {@link IoFilter} implementation generating random bytes and PDU modification in your communication streams. It's quite simple to use : ErrorGeneratingFilter egf = new ErrorGeneratingFilter(); For activate the change of some bytes in your {@link IoBuffer}, for a probability of 200 out of 1000 {@link IoBuffer} processed : egf.setChangeByteProbability(200); For activate the insertion of some bytes in your {@link IoBuffer}, for a probability of 200 out of 1000 : egf.setInsertByteProbability(200); And for the removing of some bytes : egf.setRemoveByteProbability(200); You can activate the error generation for write or read with the following methods : egf.setManipulateReads(true); egf.setManipulateWrites(true); org.apache.mina.filter.errorgenerating.ErrorGeneratingFilter
executorFilterA filter that forwards I/O events to {@link Executor} to enforce a certain thread model while allowing the events per session to be processed simultaneously. You can apply various thread model by inserting this filter to a {@link IoFilterChain}.

Life Cycle Management

Please note that this filter doesn't manage the life cycle of the {@link Executor}. If you created this filter using {@link #ExecutorFilter(Executor)} or similar constructor that accepts an {@link Executor} that you've instantiated, you have full control and responsibility of managing its life cycle (e.g. calling {@link ExecutorService#shutdown()}.

If you created this filter using convenience constructors like {@link #ExecutorFilter(int)}, then you can shut down the executor by calling {@link #destroy()} explicitly.

Event Ordering

All convenience constructors of this filter creates a new {@link OrderedThreadPoolExecutor} instance. Therefore, the order of event is maintained like the following:
  • All event handler methods are called exclusively. (e.g. messageReceived and messageSent can't be invoked at the same time.)
  • The event order is never mixed up. (e.g. messageReceived is always invoked before sessionClosed or messageSent.)
However, if you specified other {@link Executor} instance in the constructor, the order of events are not maintained at all. This means more than one event handler methods can be invoked at the same time with mixed order. For example, let's assume that messageReceived, messageSent, and sessionClosed events are fired.
  • All event handler methods can be called simultaneously. (e.g. messageReceived and messageSent can be invoked at the same time.)
  • The event order can be mixed up. (e.g. sessionClosed or messageSent can be invoked before messageReceived is invoked.)
If you need to maintain the order of events per session, please specify an {@link OrderedThreadPoolExecutor} instance or use the convenience constructors.

Selective Filtering

By default, all event types but sessionCreated, filterWrite, filterClose and filterSetTrafficMask are submitted to the underlying executor, which is most common setting.

If you want to submit only a certain set of event types, you can specify them in the constructor. For example, you could configure a thread pool for write operation for the maximum performance:


IoService service = ...;
DefaultIoFilterChainBuilder chain = service.getFilterChain();

chain.addLast("codec", new ProtocolCodecFilter(...));
// Use one thread pool for most events.
chain.addLast("executor1", new ExecutorFilter());
// and another dedicated thread pool for 'filterWrite' events.
chain.addLast("executor2", new ExecutorFilter(IoEventType.WRITE));

Preventing {@link OutOfMemoryError}

Please refer to {@link IoEventQueueThrottle}, which is specified as a parameter of the convenience constructors.
org.apache.mina.filter.executor.ExecutorFilter
expiringSessionRecyclerAn {@link IoSessionRecycler} with sessions that time out on inactivity.org.apache.mina.core.session.ExpiringSessionRecycler
fileRegionWriteFilterFilter implementation that converts a {@link FileRegion} to {@link IoBuffer} objects and writes those buffers to the next filter. When end of the {@code FileRegion} has been reached this filter will call {@link org.apache.mina.core.filterchain.IoFilter.NextFilter#messageSent(org.apache.mina.core.session.IoSession, org.apache.mina.core.write.WriteRequest)} using the original {@link FileRegion} written to the session and notifies {@link org.apache.mina.core.future.WriteFuture} on the original {@link org.apache.mina.core.write.WriteRequest}.

Normall {@code FileRegion} objects should be handled by the {@link org.apache.mina.core.service.IoProcessor} but this is not always possible if a filter is being used that needs to modify the contents of the file before sending over the network (i.e. the {@link org.apache.mina.filter.ssl.SslFilter} or a data compression filter.)

This filter will ignore written messages which aren't {@link FileRegion} instances. Such messages will be passed to the next filter directly.

NOTE: this filter does not close the file channel in {@link FileRegion#getFileChannel()} after the data from the file has been written. The {@code FileChannel} should be closed in either {@link org.apache.mina.core.service.IoHandler#messageSent(IoSession,Object)} or in an {@link org.apache.mina.core.future.IoFutureListener} associated with the {@code WriteFuture}.

org.apache.mina.filter.stream.FileRegionWriteFilter
keepAliveFilterAn {@link IoFilter} that sends a keep-alive request on {@link IoEventType#SESSION_IDLE} and sends back the response for the sent keep-alive request.

Interference with {@link IoSessionConfig#setIdleTime(IdleStatus, int)}

This filter adjusts idleTime of the {@link IdleStatus}s that this filter is interested in automatically (e.g. {@link IdleStatus#READER_IDLE} and {@link IdleStatus#WRITER_IDLE}.) Changing the idleTime of the {@link IdleStatus}s can lead this filter to a unexpected behavior. Please also note that any {@link IoFilter} and {@link IoHandler} behind {@link KeepAliveFilter} will not get any {@link IoEventType#SESSION_IDLE} event. To receive the internal {@link IoEventType#SESSION_IDLE} event, you can call {@link #setForwardEvent(boolean)} with true.

Implementing {@link KeepAliveMessageFactory}

To use this filter, you have to provide an implementation of {@link KeepAliveMessageFactory}, which determines a received or sent message is a keep-alive message or not and creates a new keep-alive message:
NameDescriptionImplementation
Active You want a keep-alive request is sent when the reader is idle. Once the request is sent, the response for the request should be received within keepAliveRequestTimeout seconds. Otherwise, the specified {@link KeepAliveRequestTimeoutHandler} will be invoked. If a keep-alive request is received, its response also should be sent back. Both {@link KeepAliveMessageFactory#getRequest(IoSession)} and {@link KeepAliveMessageFactory#getResponse(IoSession, Object)} must return a non-null.
Semi-active You want a keep-alive request to be sent when the reader is idle. However, you don't really care if the response is received or not. If a keep-alive request is received, its response should also be sent back. Both {@link KeepAliveMessageFactory#getRequest(IoSession)} and {@link KeepAliveMessageFactory#getResponse(IoSession, Object)} must return a non-null, and the timeoutHandler property should be set to {@link KeepAliveRequestTimeoutHandler#NOOP}, {@link KeepAliveRequestTimeoutHandler#LOG} or the custom {@link KeepAliveRequestTimeoutHandler} implementation that doesn't affect the session state nor throw an exception.
Passive You don't want to send a keep-alive request by yourself, but the response should be sent back if a keep-alive request is received. {@link KeepAliveMessageFactory#getRequest(IoSession)} must return null and {@link KeepAliveMessageFactory#getResponse(IoSession, Object)} must return a non-null.
Deaf Speaker You want a keep-alive request to be sent when the reader is idle, but you don't want to send any response back. {@link KeepAliveMessageFactory#getRequest(IoSession)} must return a non-null, {@link KeepAliveMessageFactory#getResponse(IoSession, Object)} must return null and the timeoutHandler must be set to {@link KeepAliveRequestTimeoutHandler#DEAF_SPEAKER}.
Silent Listener You don't want to send a keep-alive request by yourself nor send any response back. Both {@link KeepAliveMessageFactory#getRequest(IoSession)} and {@link KeepAliveMessageFactory#getResponse(IoSession, Object)} must return null.
Please note that you must implement {@link KeepAliveMessageFactory#isRequest(IoSession, Object)} and {@link KeepAliveMessageFactory#isResponse(IoSession, Object)} properly whatever case you chose.

Handling timeout

{@link KeepAliveFilter} will notify its {@link KeepAliveRequestTimeoutHandler} when {@link KeepAliveFilter} didn't receive the response message for a sent keep-alive message. The default handler is {@link KeepAliveRequestTimeoutHandler#CLOSE}, but you can use other presets such as {@link KeepAliveRequestTimeoutHandler#NOOP}, {@link KeepAliveRequestTimeoutHandler#LOG} or {@link KeepAliveRequestTimeoutHandler#EXCEPTION}. You can even implement your own handler.

Special handler: {@link KeepAliveRequestTimeoutHandler#DEAF_SPEAKER}

{@link KeepAliveRequestTimeoutHandler#DEAF_SPEAKER} is a special handler which is dedicated for the 'deaf speaker' mode mentioned above. Setting the timeoutHandler property to {@link KeepAliveRequestTimeoutHandler#DEAF_SPEAKER} stops this filter from waiting for response messages and therefore disables response timeout detection.
org.apache.mina.filter.keepalive.KeepAliveFilter
loggingFilterLogs all MINA protocol events. Each event can be tuned to use a different level based on the user's specific requirements. Methods are in place that allow the user to use either the get or set method for each event and pass in the {@link IoEventType} and the {@link LogLevel}. By default, all events are logged to the {@link LogLevel#INFO} level except {@link IoFilterAdapter#exceptionCaught(IoFilter.NextFilter, IoSession, Throwable)}, which is logged to {@link LogLevel#WARN}.org.apache.mina.filter.logging.LoggingFilter
nioDatagramAcceptor{@link IoAcceptor} for datagram transport (UDP/IP).org.apache.mina.transport.socket.nio.NioDatagramAcceptor
orderedThreadPoolExecutorA {@link ThreadPoolExecutor} that maintains the order of {@link IoEvent}s.

If you don't need to maintain the order of events per session, please use {@link UnorderedThreadPoolExecutor}.

org.apache.mina.filter.executor.OrderedThreadPoolExecutor
profilerTimerFilterThis class will measure the time it takes for a method in the {@link IoFilterAdapter} class to execute. The basic premise of the logic in this class is to get the current time at the beginning of the method, call method on nextFilter, and then get the current time again. An example of how to use the filter is:
ProfilerTimerFilter profiler = new ProfilerTimerFilter(
TimeUnit.MILLISECOND, IoEventType.MESSAGE_RECEIVED);
chain.addFirst("Profiler", profiler);
The profiled {@link IoEventType} are :
  • IoEventType.MESSAGE_RECEIVED
  • IoEventType.MESSAGE_SENT
  • IoEventType.SESSION_CREATED
  • IoEventType.SESSION_OPENED
  • IoEventType.SESSION_IDLE
  • IoEventType.SESSION_CLOSED
org.apache.mina.filter.statistic.ProfilerTimerFilter
protocolCodecFilterAn {@link IoFilter} which translates binary or protocol specific data into message objects and vice versa using {@link ProtocolCodecFactory}, {@link ProtocolEncoder}, or {@link ProtocolDecoder}.org.apache.mina.filter.codec.ProtocolCodecFilter
referenceCountingFilterAn {@link IoFilter}s wrapper that keeps track of the number of usages of this filter and will call init/destroy when the filter is not in use.org.apache.mina.filter.util.ReferenceCountingFilter
sessionAttributeInitializingFilterAn {@link IoFilter} that sets initial attributes when a new {@link IoSession} is created. By default, the attribute map is empty when an {@link IoSession} is newly created. Inserting this filter will make the pre-configured attributes available after this filter executes the sessionCreated event.org.apache.mina.filter.util.SessionAttributeInitializingFilter
socketAddressWorkaround for dealing with inability to annotate java docs of JDK socket address classes.org.apache.mina.integration.xbean.SocketAddressFactory
sslFilterAn SSL filter that encrypts and decrypts the data exchanged in the session. Adding this filter triggers SSL handshake procedure immediately by sending a SSL 'hello' message, so you don't need to call {@link #startSsl(IoSession)} manually unless you are implementing StartTLS (see below). If you don't want the handshake procedure to start immediately, please specify {@code false} as {@code autoStart} parameter in the constructor.

This filter uses an {@link SSLEngine} which was introduced in Java 5, so Java version 5 or above is mandatory to use this filter. And please note that this filter only works for TCP/IP connections.

Implementing StartTLS

You can use {@link #DISABLE_ENCRYPTION_ONCE} attribute to implement StartTLS:

public void messageReceived(IoSession session, Object message) {
if (message instanceof MyStartTLSRequest) {
// Insert SSLFilter to get ready for handshaking
session.getFilterChain().addFirst(sslFilter);

// Disable encryption temporarilly.
// This attribute will be removed by SSLFilter
// inside the Session.write() call below.
session.setAttribute(SSLFilter.DISABLE_ENCRYPTION_ONCE, Boolean.TRUE);

// Write StartTLSResponse which won't be encrypted.
session.write(new MyStartTLSResponse(OK));

// Now DISABLE_ENCRYPTION_ONCE attribute is cleared.
assert session.getAttribute(SSLFilter.DISABLE_ENCRYPTION_ONCE) == null;
}
}
org.apache.mina.filter.ssl.SslFilter
standardThreadPoolorg.apache.mina.integration.xbean.StandardThreadPool
streamWriteFilterFilter implementation which makes it possible to write {@link InputStream} objects directly using {@link IoSession#write(Object)}. When an {@link InputStream} is written to a session this filter will read the bytes from the stream into {@link IoBuffer} objects and write those buffers to the next filter. When end of stream has been reached this filter will call {@link org.apache.mina.core.filterchain.IoFilter.NextFilter#messageSent(org.apache.mina.core.session.IoSession, org.apache.mina.core.write.WriteRequest)} using the original {@link InputStream} written to the session and notifies {@link org.apache.mina.core.future.WriteFuture} on the original {@link org.apache.mina.core.write.WriteRequest}.

This filter will ignore written messages which aren't {@link InputStream} instances. Such messages will be passed to the next filter directly.

NOTE: this filter does not close the stream after all data from stream has been written. The {@link org.apache.mina.core.service.IoHandler} should take care of that in its {@link org.apache.mina.core.service.IoHandler#messageSent(IoSession,Object)} callback.

org.apache.mina.filter.stream.StreamWriteFilter
unorderedThreadPoolExecutorA {@link ThreadPoolExecutor} that does not maintain the order of {@link IoEvent}s. This means more than one event handler methods can be invoked at the same time with mixed order. For example, let's assume that messageReceived, messageSent, and sessionClosed events are fired.
  • All event handler methods can be called simultaneously. (e.g. messageReceived and messageSent can be invoked at the same time.)
  • The event order can be mixed up. (e.g. sessionClosed or messageSent can be invoked before messageReceived is invoked.)
If you need to maintain the order of events per session, please use {@link OrderedThreadPoolExecutor}.
org.apache.mina.filter.executor.UnorderedThreadPoolExecutor

Element Detail

Element: blacklistFilter

ElementTypeDescription
blacklist<spring:bean/>Sets the addresses to be blacklisted. NOTE: this call will remove any previously blacklisted addresses.
subnetBlacklist<spring:bean/>Sets the subnets to be blacklisted. NOTE: this call will remove any previously blacklisted subnets.

Element: bufferedWriteFilter

AttributeTypeDescription
bufferSizexs:integerSets the buffer size but only for the newly created buffers.
ElementTypeDescription
buffersMap<spring:bean/>the map to use for storing each session buffer

Element: defaultIoFilterChainBuilder

ElementTypeDescription
filterChaindefaultIoFilterChainBuilderThe FilterChain we will copy
filters<spring:bean/>Clears the current list of filters and adds the specified filter mapping to this builder. Please note that you must specify a {@link Map} implementation that iterates the filter mapping in the order of insertion such as {@link LinkedHashMap}. Otherwise, it will throw an {@link IllegalArgumentException}.

Element: errorGeneratingFilter

AttributeTypeDescription
changeByteProbabilityxs:integerSet the probability for the change byte error. If this probability is > 0 the filter will modify a random number of byte of the processed {@link IoBuffer}.
duplicatePduProbabilityxs:integernot functional ATM
insertByteProbabilityxs:integerSet the probability for the insert byte error. If this probability is > 0 the filter will insert a random number of byte in the processed {@link IoBuffer}.
manipulateReadsxs:booleanSet to true if you want to apply error to the read {@link IoBuffer}
manipulateWritesxs:booleanSet to true if you want to apply error to the written {@link IoBuffer}
maxInsertBytexs:integerSet the maximum number of byte the filter can insert in a {@link IoBuffer}. The default value is 10.
removeByteProbabilityxs:integerSet the probability for the remove byte error. If this probability is > 0 the filter will remove a random number of byte in the processed {@link IoBuffer}.
removePduProbabilityxs:integernot functional ATM
resendPduLasterProbabilityxs:integernot functional ATM

Element: executorFilter

AttributeTypeDescription
corePoolSizexs:integerThe initial pool size
eventTypesxs:stringThe event for which the executor will be used
keepAliveTimexs:longDefault duration for a thread
maximumPoolSizexs:integerThe maximum pool size
unitxs:stringTime unit used for the keepAlive value
ElementTypeDescription
executorstandardThreadPoolthe user's managed Executor to use in this filter
queueHandler<spring:bean/>The queue used to store events
threadFactory<spring:bean/>The factory used to create threads

Element: expiringSessionRecycler

AttributeTypeDescription
expirationIntervalxs:integer
timeToLivexs:integer

Element: fileRegionWriteFilter

AttributeTypeDescription
writeBufferSizexs:integerSets the size of the write buffer in bytes. Data will be read from the stream in chunks of this size and then written to the next filter.

Element: keepAliveFilter

AttributeTypeDescription
forwardEventxs:booleanSets if this filter needs to forward a {@link IoEventType#SESSION_IDLE} event to the next filter. By default, the value of this property is false.
keepAliveRequestIntervalxs:integerthe interval to use
keepAliveRequestTimeoutxs:integerThe timeout to use
requestIntervalxs:integerSets the interval for keepAlive messages
requestTimeoutxs:integerSets the timeout
ElementTypeDescription
interestedIdleStatus<spring:bean/>The IdleStatus the filter is interested in
messageFactory<spring:bean/>The message factory to use
policy<spring:bean/>The TimeOut handler policy
requestTimeoutHandler<spring:bean/>Set the timeout handler

Element: loggingFilter

AttributeTypeDescription
clazzxs:stringthe cass which name will be used to create the logger
exceptionCaughtLogLevelxs:stringGet the LogLevel for the ExceptionCaught event.
messageReceivedLogLevelxs:stringGet the LogLevel for the MessageReceived event.
messageSentLogLevelxs:stringGet the LogLevel for the MessageSent event.
namexs:stringthe name used to create the logger. If null, will default to "NoopFilter"
sessionClosedLogLevelxs:stringGet the LogLevel for the SessionClosed event.
sessionCreatedLogLevelxs:stringGet the LogLevel for the SessionCreated event.
sessionIdleLogLevelxs:stringGet the LogLevel for the SessionIdle event.
sessionOpenedLogLevelxs:stringGet the LogLevel for the SessionOpened event.

Element: nioDatagramAcceptor

AttributeTypeDescription
closeOnDeactivationxs:boolean{@inheritDoc}
ElementTypeDescription
defaultLocalAddress<spring:bean/>
defaultLocalAddresses<spring:bean/>{@inheritDoc}
executorstandardThreadPoolThe executor to use
filterChainBuilderdefaultIoFilterChainBuilder{@inheritDoc}
handler<spring:bean/>{@inheritDoc}
sessionDataStructureFactory<spring:bean/>{@inheritDoc}
sessionRecyclerexpiringSessionRecycler

Element: orderedThreadPoolExecutor

AttributeTypeDescription
corePoolSizexs:integer{@inheritDoc}
keepAliveTimexs:longDefault duration for a thread
maximumPoolSizexs:integer{@inheritDoc}
unitxs:stringTime unit used for the keepAlive value
ElementTypeDescription
eventQueueHandler<spring:bean/>The queue used to store events
rejectedExecutionHandler<spring:bean/>{@inheritDoc}
threadFactory<spring:bean/>

Element: profilerTimerFilter

AttributeTypeDescription
eventTypesxs:stringA list of {@link IoEventType} representation of the methods to profile
eventsToProfilexs:stringReturn the set of {@link IoEventType} which are profiled.
profilersxs:stringCreate the profilers for a list of {@link IoEventType}.
timeUnitxs:stringSets the {@link TimeUnit} being used.

Element: protocolCodecFilter

AttributeTypeDescription
decoderClassxs:stringThe class responsible for decoding the message
encoderClassxs:stringThe class responsible for encoding the message
ElementTypeDescription
decoder<spring:bean/>The class responsible for decoding the message
encoder<spring:bean/>The class responsible for encoding the message
factory<spring:bean/>The associated factory

Element: referenceCountingFilter

ElementTypeDescription
filterblacklistFilter | bufferedWriteFilter | errorGeneratingFilter | executorFilter | fileRegionWriteFilter | keepAliveFilter | loggingFilter | profilerTimerFilter | protocolCodecFilter | referenceCountingFilter | sessionAttributeInitializingFilter | sslFilter | streamWriteFilter

Element: sessionAttributeInitializingFilter

AttributeTypeDescription
attributexs:stringSets a user defined attribute without a value. This is useful when you just want to put a 'mark' attribute. Its value is set to {@link Boolean#TRUE}.
ElementTypeDescription
attributes<spring:bean/>Sets the attribute map. The specified attributes are copied into the underlying map, so modifying the specified attributes parameter after the call won't change the internal state.

Element: socketAddress

AttributeTypeDescription
valuexs:stringThe socket address as a String

Element: sslFilter

AttributeTypeDescription
autoStartxs:booleanThe flag used to tell the filter to start the handshake immediately
needClientAuthxs:booleanConfigures the engine to require client authentication. This option is only useful for engines in the server mode.
useClientModexs:booleanConfigures the engine to use client (or server) mode when handshaking.
wantClientAuthxs:booleanConfigures the engine to request client authentication. This option is only useful for engines in the server mode.
ElementTypeDescription
enabledCipherSuites(<spring:bean/>)*Sets the list of cipher suites to be enabled when {@link SSLEngine} is initialized.
enabledProtocols(<spring:bean/>)*Sets the list of protocols to be enabled when {@link SSLEngine} is initialized.
sslContext<spring:bean/>The SSLContext to use

Element: standardThreadPool

AttributeTypeDescription
maxThreadsxs:integer

Element: streamWriteFilter

AttributeTypeDescription
writeBufferSizexs:integerSets the size of the write buffer in bytes. Data will be read from the stream in chunks of this size and then written to the next filter.

Element: unorderedThreadPoolExecutor

AttributeTypeDescription
corePoolSizexs:integer
keepAliveTimexs:long
maximumPoolSizexs:integer
unitxs:string
ElementTypeDescription
queueHandler<spring:bean/>
rejectedExecutionHandler<spring:bean/>
threadFactory<spring:bean/>