Java Code Examples for org.apache.mina.core.write.WriteRequest#getMessage()

The following examples show how to use org.apache.mina.core.write.WriteRequest#getMessage() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ModbusMasterProtocolFilter.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void filterWrite ( final NextFilter nextFilter, final IoSession session, final WriteRequest writeRequest ) throws Exception
{
    if ( writeRequest.getMessage () instanceof BaseMessage )
    {
        final Pdu pdu = ModbusProtocol.encodeAsMaster ( (BaseMessage)writeRequest.getMessage () );
        nextFilter.filterWrite ( session, new WriteRequestWrapper ( writeRequest ) {
            @Override
            public Object getMessage ()
            {
                return pdu;
            };
        } );
    }
    else
    {
        nextFilter.filterWrite ( session, writeRequest );
    }
}
 
Example 2
Source File: ModbusSlaveProtocolFilter.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void filterWrite ( final NextFilter nextFilter, final IoSession session, final WriteRequest writeRequest ) throws Exception
{
    if ( writeRequest.getMessage () instanceof BaseMessage )
    {
        final Pdu pdu = ModbusProtocol.encodeAsSlave ( (BaseMessage)writeRequest.getMessage () );
        nextFilter.filterWrite ( session, new WriteRequestWrapper ( writeRequest ) {
            @Override
            public Object getMessage ()
            {
                return pdu;
            };
        } );
    }
    else
    {
        nextFilter.filterWrite ( session, writeRequest );
    }
}
 
Example 3
Source File: AbstractIoSession.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * TODO Add method documentation
 */
public final void increaseWrittenMessages(WriteRequest request, long currentTime) {
    Object message = request.getMessage();
    if (message instanceof IoBuffer) {
        IoBuffer b = (IoBuffer) message;
        if (b.hasRemaining()) {
            return;
        }
    }

    writtenMessages++;
    lastWriteTime = currentTime;
    if (getService() instanceof AbstractIoService) {
        ((AbstractIoService) getService()).getStatistics().increaseWrittenMessages(currentTime);
    }

    decreaseScheduledWriteMessages();
}
 
Example 4
Source File: COTPFilter.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Handle data transmission
 * 
 * @param nextFilter
 * @param session
 * @param writeRequest
 */
private void handleDT ( final NextFilter nextFilter, final IoSession session, final WriteRequest writeRequest )
{
    final DataTPDU userData = (DataTPDU)writeRequest.getMessage ();
    final IoBuffer data = IoBuffer.allocate ( userData.getData ().remaining () + 3 );

    data.put ( (byte)0x02 ); // header length
    data.put ( (byte) ( COMMAND_DATA << 4 ) );

    final byte seq = (byte)0x80; // bit 8 to 1 (last packet)... bit 7..1 to zero (packet #0)

    data.put ( seq );

    data.put ( userData.getData () );

    data.flip ();

    nextFilter.filterWrite ( session, new WriteRequestWrapper ( writeRequest ) {
        @Override
        public Object getMessage ()
        {
            return data;
        }
    } );
}
 
Example 5
Source File: CompressionFilter.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected Object doFilterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest)
        throws IOException {
    if (!compressOutbound) {
        return null;
    }

    if (session.containsAttribute(DISABLE_COMPRESSION_ONCE)) {
        // Remove the marker attribute because it is temporary.
        session.removeAttribute(DISABLE_COMPRESSION_ONCE);
        return null;
    }

    Zlib deflater = (Zlib) session.getAttribute(DEFLATER);
    if (deflater == null) {
        throw new IllegalStateException();
    }

    IoBuffer inBuffer = (IoBuffer) writeRequest.getMessage();
    if (!inBuffer.hasRemaining()) {
        // Ignore empty buffers
        return null;
    } else {
        return deflater.deflate(inBuffer);
    }
}
 
Example 6
Source File: AbstractIoSession.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public final Object getCurrentWriteMessage() {
    WriteRequest req = getCurrentWriteRequest();
    if (req == null) {
        return null;
    }
    return req.getMessage();
}
 
Example 7
Source File: AbstractPollingIoProcessor.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private int writeBuffer(S session, WriteRequest req, boolean hasFragmentation, int maxLength, long currentTime)
        throws Exception {
    IoBuffer buf = (IoBuffer) req.getMessage();
    int localWrittenBytes = 0;

    if (buf.hasRemaining()) {
        int length;

        if (hasFragmentation) {
            length = Math.min(buf.remaining(), maxLength);
        } else {
            length = buf.remaining();
        }

        try {
            localWrittenBytes = write(session, buf, length);
        } catch (IOException ioe) {
            // We have had an issue while trying to send data to the 
            // peer : let's close the session.
            session.close(true);
        }

    }

    session.increaseWrittenBytes(localWrittenBytes, currentTime);

    if (!buf.hasRemaining() || (!hasFragmentation && (localWrittenBytes != 0))) {
        // Buffer has been sent, clear the current request.
        int pos = buf.position();
        buf.reset();

        fireMessageSent(session, req);

        // And set it back to its position
        buf.position(pos);
    }

    return localWrittenBytes;
}
 
Example 8
Source File: AbstractIoSession.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * TODO Add method documentation
 */
public final void decreaseScheduledBytesAndMessages(WriteRequest request) {
    Object message = request.getMessage();
    if (message instanceof IoBuffer) {
        IoBuffer b = (IoBuffer) message;
        if (b.hasRemaining()) {
            increaseScheduledWriteBytes(-((IoBuffer) message).remaining());
        } else {
            decreaseScheduledWriteMessages();
        }
    } else {
        decreaseScheduledWriteMessages();
    }
}
 
Example 9
Source File: WriteRequestFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception {
    Object filteredMessage = doFilterWrite(nextFilter, session, writeRequest);
    if (filteredMessage != null && filteredMessage != writeRequest.getMessage()) {
        nextFilter.filterWrite(session, new FilteredWriteRequest(filteredMessage, writeRequest));
    } else {
        nextFilter.filterWrite(session, writeRequest);
    }
}
 
Example 10
Source File: BufferedWriteFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * 
 * @throws Exception if <code>writeRequest.message</code> isn't an
 *                   {@link IoBuffer} instance.
 */
@Override
public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception {

    Object data = writeRequest.getMessage();

    if (data instanceof IoBuffer) {
        write(session, (IoBuffer) data);
    } else {
        throw new IllegalArgumentException("This filter should only buffer IoBuffer objects");
    }
}
 
Example 11
Source File: RTMPEIoFilter.java    From red5-client with Apache License 2.0 5 votes vote down vote up
@Override
public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest request) throws Exception {
    RTMPMinaConnection conn = (RTMPMinaConnection) RTMPConnManager.getInstance().getConnectionBySessionId((String) session.getAttribute(RTMPConnection.RTMP_SESSION_ID));
    // filter based on current connection state
    if (conn.getState().getState() == RTMP.STATE_CONNECTED && session.containsAttribute(RTMPConnection.RTMPE_CIPHER_OUT)) {
        Cipher cipher = (Cipher) session.getAttribute(RTMPConnection.RTMPE_CIPHER_OUT);
        IoBuffer message = (IoBuffer) request.getMessage();
        if (!message.hasRemaining()) {
            if (log.isTraceEnabled()) {
                log.trace("Ignoring empty message");
            }
            nextFilter.filterWrite(session, request);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Encrypting message: {}", message);
            }
            byte[] plain = new byte[message.remaining()];
            message.get(plain);
            message.clear();
            message.free();
            // encrypt and write
            byte[] encrypted = cipher.update(plain);
            IoBuffer messageEncrypted = IoBuffer.wrap(encrypted);
            if (log.isDebugEnabled()) {
                log.debug("Encrypted message: {}", messageEncrypted);
            }
            nextFilter.filterWrite(session, new EncryptedWriteRequest(request, messageEncrypted));
        }
    } else {
        log.trace("Non-encrypted message");
        nextFilter.filterWrite(session, request);
    }
}
 
Example 12
Source File: KeepAliveFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void messageSent(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception {
    Object message = writeRequest.getMessage();
    if (!isKeepAliveMessage(session, message)) {
        nextFilter.messageSent(session, writeRequest);
    }
}
 
Example 13
Source File: AbstractPollingIoProcessor.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private int writeFile(S session, WriteRequest req, boolean hasFragmentation, int maxLength, long currentTime)
        throws Exception {
    int localWrittenBytes;
    FileRegion region = (FileRegion) req.getMessage();

    if (region.getRemainingBytes() > 0) {
        int length;

        if (hasFragmentation) {
            length = (int) Math.min(region.getRemainingBytes(), maxLength);
        } else {
            length = (int) Math.min(Integer.MAX_VALUE, region.getRemainingBytes());
        }

        localWrittenBytes = transferFile(session, region, length);
        region.update(localWrittenBytes);
    } else {
        localWrittenBytes = 0;
    }

    session.increaseWrittenBytes(localWrittenBytes, currentTime);

    if ((region.getRemainingBytes() <= 0) || (!hasFragmentation && (localWrittenBytes != 0))) {
        fireMessageSent(session, req);
    }

    return localWrittenBytes;
}
 
Example 14
Source File: ProxyFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Filter handshake related messages from reaching the messageSent callbacks of 
 * downstream filters.
 * 
 * @param nextFilter the next filter in filter chain
 * @param session the session object
 * @param writeRequest the data written
 */
@Override
public void messageSent(final NextFilter nextFilter, final IoSession session, final WriteRequest writeRequest)
        throws Exception {
    if (writeRequest.getMessage() != null && writeRequest.getMessage() instanceof ProxyHandshakeIoBuffer) {
        // Ignore buffers used in handshaking
        return;
    }

    nextFilter.messageSent(session, writeRequest);
}
 
Example 15
Source File: COTPFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void filterWrite ( final NextFilter nextFilter, final IoSession session, final WriteRequest writeRequest ) throws Exception
{
    if ( writeRequest.getMessage () instanceof DataTPDU )
    {
        logger.debug ( "Filter as DT: {}", writeRequest );
        handleDT ( nextFilter, session, writeRequest );
    }
    else
    {
        nextFilter.filterWrite ( session, writeRequest );
    }
}
 
Example 16
Source File: MessageChannelCodecFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void filterWrite ( final NextFilter nextFilter, final IoSession session, final WriteRequest writeRequest ) throws Exception
{
    if ( writeRequest.getMessage () instanceof CloseMessage )
    {
        nextFilter.filterWrite ( session, new WriteRequestWrapperExtension ( writeRequest, encodeCloseMessage ( session, (CloseMessage)writeRequest.getMessage () ) ) );
    }
    else if ( writeRequest.getMessage () instanceof HelloMessage )
    {
        nextFilter.filterWrite ( session, new WriteRequestWrapperExtension ( writeRequest, encodeHelloMessage ( session, (HelloMessage)writeRequest.getMessage () ) ) );
    }
    else if ( writeRequest.getMessage () instanceof AcceptMessage )
    {
        nextFilter.filterWrite ( session, new WriteRequestWrapperExtension ( writeRequest, encodeAcceptMessage ( session, (AcceptMessage)writeRequest.getMessage () ) ) );
    }
    else if ( writeRequest.getMessage () instanceof StartMessage )
    {
        nextFilter.filterWrite ( session, new WriteRequestWrapperExtension ( writeRequest, encodeStartMessage ( session ) ) );
    }
    else if ( writeRequest.getMessage () instanceof DataMessage )
    {
        nextFilter.filterWrite ( session, new WriteRequestWrapperExtension ( writeRequest, makeMessageFrame ( (DataMessage)writeRequest.getMessage () ) ) );
    }
    else
    {
        throw new IllegalStateException ( String.format ( "Unable to process message of type: %s", writeRequest.getMessage ().getClass () ) );
    }
}
 
Example 17
Source File: MessageChannelFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void filterWrite ( final NextFilter nextFilter, final IoSession session, final WriteRequest writeRequest ) throws Exception
{
    if ( ! ( writeRequest.getMessage () instanceof DataMessage ) )
    {
        throw new IllegalStateException ( String.format ( "Can only handle messages of type %s (this is: %s)", DataMessage.class, writeRequest.getMessage () ) ); //$NON-NLS-1$
    }

    super.filterWrite ( nextFilter, session, writeRequest );
}
 
Example 18
Source File: TPKTFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void filterWrite ( final NextFilter nextFilter, final IoSession session, final WriteRequest writeRequest ) throws Exception
{
    // we only handle IoBuffers
    if ( writeRequest.getMessage () instanceof IoBuffer )
    {
        final IoBuffer inData = (IoBuffer)writeRequest.getMessage ();
        final IoBuffer outData = IoBuffer.allocate ( inData.remaining () + 4 );

        // put the version, the reserved
        outData.put ( (byte)this.version );
        outData.put ( (byte)0 );

        // and the data length
        outData.putShort ( (short) ( inData.remaining () + 4 ) );

        // append the data itself
        outData.put ( inData );

        outData.flip ();

        logger.debug ( "TPKT out: {}", outData );

        // pass on data buffer
        nextFilter.filterWrite ( session, new WriteRequestWrapper ( writeRequest ) {
            @Override
            public Object getMessage ()
            {
                return outData;
            }
        } );
    }
    else
    {
        nextFilter.filterWrite ( session, writeRequest );
    }
}
 
Example 19
Source File: SslFilter.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws SSLException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("{}: Writing Message : {}", getSessionInfo(session), writeRequest);
    }

    boolean needsFlush = true;
    SslHandler handler = getSslSessionHandler(session);
    synchronized (handler) {
        if (!isSslStarted(session)) {
            handler.scheduleFilterWrite(nextFilter, writeRequest);
        }
        // Don't encrypt the data if encryption is disabled.
        else if (session.containsAttribute(DISABLE_ENCRYPTION_ONCE)) {
            // Remove the marker attribute because it is temporary.
            session.removeAttribute(DISABLE_ENCRYPTION_ONCE);
            handler.scheduleFilterWrite(nextFilter, writeRequest);
        } else {
            // Otherwise, encrypt the buffer.
            IoBuffer buf = (IoBuffer) writeRequest.getMessage();

            if (handler.isWritingEncryptedData()) {
                // data already encrypted; simply return buffer
                handler.scheduleFilterWrite(nextFilter, writeRequest);
            } else if (handler.isHandshakeComplete()) {
                // SSL encrypt
                int pos = buf.position();
                handler.encrypt(buf.buf());
                buf.position(pos);
                IoBuffer encryptedBuffer = handler.fetchOutNetBuffer();
                handler.scheduleFilterWrite(nextFilter, new EncryptedWriteRequest(writeRequest, encryptedBuffer));
            } else {
                if (session.isConnected()) {
                    // Handshake not complete yet.
                    handler.schedulePreHandshakeWriteRequest(nextFilter, writeRequest);
                }
                needsFlush = false;
            }
        }
    }

    if (needsFlush) {
        handler.flushScheduledEvents();
    }
}
 
Example 20
Source File: ProtocolCodecFilter.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception {
    Object message = writeRequest.getMessage();

    // Bypass the encoding if the message is contained in a IoBuffer,
    // as it has already been encoded before
    if ((message instanceof IoBuffer) || (message instanceof FileRegion)) {
        nextFilter.filterWrite(session, writeRequest);
        return;
    }

    // Get the encoder in the session
    ProtocolEncoder encoder = factory.getEncoder(session);

    ProtocolEncoderOutput encoderOut = getEncoderOut(session, nextFilter, writeRequest);

    if (encoder == null) {
        throw new ProtocolEncoderException("The encoder is null for the session " + session);
    }

    if (encoderOut == null) {
        throw new ProtocolEncoderException("The encoderOut is null for the session " + session);
    }

    try {
        // Now we can try to encode the response
        encoder.encode(session, message, encoderOut);

        // Send it directly
        Queue<Object> bufferQueue = ((AbstractProtocolEncoderOutput) encoderOut).getMessageQueue();

        // Write all the encoded messages now
        while (!bufferQueue.isEmpty()) {
            Object encodedMessage = bufferQueue.poll();

            if (encodedMessage == null) {
                break;
            }

            // Flush only when the buffer has remaining.
            if (!(encodedMessage instanceof IoBuffer) || ((IoBuffer) encodedMessage).hasRemaining()) {
                SocketAddress destination = writeRequest.getDestination();
                WriteRequest encodedWriteRequest = new EncodedWriteRequest(encodedMessage, null, destination);

                nextFilter.filterWrite(session, encodedWriteRequest);
            }
        }

        // Call the next filter
        nextFilter.filterWrite(session, new MessageWriteRequest(writeRequest));
    } catch (Throwable t) {
        ProtocolEncoderException pee;

        // Generate the correct exception
        if (t instanceof ProtocolEncoderException) {
            pee = (ProtocolEncoderException) t;
        } else {
            pee = new ProtocolEncoderException(t);
        }

        throw pee;
    }
}