org.apache.mina.core.write.WriteRequest Java Examples

The following examples show how to use org.apache.mina.core.write.WriteRequest. 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: 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 #2
Source File: DefaultIoEventSizeEstimator.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Estimate the size of an Objecr in number of bytes
 * @param message The object to estimate
 * @return The estimated size of the object
 */
public int estimateSize(Object message) {
    if (message == null) {
        return 8;
    }

    int answer = 8 + estimateSize(message.getClass(), null);

    if (message instanceof IoBuffer) {
        answer += ((IoBuffer) message).remaining();
    } else if (message instanceof WriteRequest) {
        answer += estimateSize(((WriteRequest) message).getMessage());
    } else if (message instanceof CharSequence) {
        answer += ((CharSequence) message).length() << 1;
    } else if (message instanceof Iterable) {
        for (Object m : (Iterable<?>) message) {
            answer += estimateSize(m);
        }
    }

    return align(answer);
}
 
Example #3
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 #4
Source File: SslHandler.java    From jane with GNU Lesser General Public License v3.0 6 votes vote down vote up
void flushScheduledEvents() throws Exception {
	scheduledEvents.getAndIncrement();

	// Fire events only when the lock is available for this handler.
	if (sslLock.tryLock()) {
		try {
			do {
				Entry<NextFilter, WriteRequest> eventW;
				// We need synchronization here inevitably because filterWrite can be
				// called simultaneously and cause 'bad record MAC' integrity error.
				while ((eventW = filterWriteEventQueue.poll()) != null)
					eventW.getKey().filterWrite(eventW.getValue());

				Entry<NextFilter, Object> eventR;
				while ((eventR = messageReceivedEventQueue.poll()) != null)
					eventR.getKey().messageReceived(eventR.getValue());
			} while (scheduledEvents.decrementAndGet() > 0);
		} finally {
			sslLock.unlock();
		}
	}
}
 
Example #5
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 #6
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 #7
Source File: AbstractProxyLogicHandler.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Send any write requests which were queued whilst waiting for handshaking to complete.
 */
protected synchronized void flushPendingWriteRequests() throws Exception {
    LOGGER.debug(" flushPendingWriteRequests()");

    if (writeRequestQueue == null) {
        return;
    }

    Event scheduledWrite;
    while ((scheduledWrite = writeRequestQueue.poll()) != null) {
        LOGGER.debug(" Flushing buffered write request: {}", scheduledWrite.data);

        getProxyFilter().filterWrite(scheduledWrite.nextFilter, getSession(), (WriteRequest) scheduledWrite.data);
    }

    // Free queue
    writeRequestQueue = null;
}
 
Example #8
Source File: AbstractIoSession.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
private static void notifyWriteTimeout(IoSession session, long currentTime) {

        long writeTimeout = session.getConfig().getWriteTimeoutInMillis();
        if ((writeTimeout > 0) && (currentTime - session.getLastWriteTime() >= writeTimeout)
                && !session.getWriteRequestQueue().isEmpty(session)) {
            WriteRequest request = session.getCurrentWriteRequest();
            if (request != null) {
                session.setCurrentWriteRequest(null);
                WriteTimeoutException cause = new WriteTimeoutException(request);
                request.getFuture().setException(cause);
                session.getFilterChain().fireExceptionCaught(cause);
                // WriteException is an IOException, so we close the session.
                session.close(true);
            }
        }
    }
 
Example #9
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 #10
Source File: SslFilter.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception {
	SslHandler sslHandler = getSslSessionHandler(session);

	try {
		boolean needsFlush = true;
		synchronized (sslHandler) {
			if (!isSslStarted(session))
				sslHandler.scheduleFilterWrite(nextFilter, writeRequest);
			else if (session.containsAttribute(DISABLE_ENCRYPTION_ONCE)) { // don't encrypt the data if encryption is disabled
				session.removeAttribute(DISABLE_ENCRYPTION_ONCE); // remove the marker attribute because it is temporary
				sslHandler.scheduleFilterWrite(nextFilter, writeRequest);
			} else { // otherwise, encrypt the buffer
				if (sslHandler.isWritingEncryptedData())
					sslHandler.scheduleFilterWrite(nextFilter, writeRequest); // data already encrypted; simply return buffer
				else if (sslHandler.isHandshakeComplete()) { // SSL encrypt
					sslHandler.encrypt(((IoBuffer)writeRequest.writeRequestMessage()).buf());
					IoBuffer encryptedBuffer = sslHandler.fetchOutNetBuffer();
					sslHandler.scheduleFilterWrite(nextFilter, new EncryptedWriteRequest(writeRequest, encryptedBuffer));
				} else {
					if (session.isConnected())
						sslHandler.schedulePreHandshakeWriteRequest(nextFilter, writeRequest); // handshake not complete yet
					needsFlush = false;
				}
			}
		}

		if (needsFlush)
			sslHandler.flushScheduledEvents();
	} catch (SSLException se) {
		sslHandler.release();
		throw se;
	}
}
 
Example #11
Source File: BlacklistFilter.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 {
    if (!isBlocked(session)) {
        // forward if not blocked
        nextFilter.messageSent(session, writeRequest);
    } else {
        blockSession(session);
    }
}
 
Example #12
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 #13
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 #14
Source File: StatisticsFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void messageSent ( final NextFilter nextFilter, final IoSession session, final WriteRequest writeRequest ) throws Exception
{
    updateStats ( session );

    super.messageSent ( nextFilter, session, writeRequest );
}
 
Example #15
Source File: NetManager.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static boolean write(IoSession session, Object obj)
{
	if (session.isClosing() || obj == null)
		return false;
	IoFilterChain ifc = session.getFilterChain();
	WriteRequest wr = (obj instanceof WriteRequest ? (WriteRequest)obj : new SimpleWriteRequest(obj));
	synchronized (session)
	{
		ifc.fireFilterWrite(wr);
	}
	return true;
}
 
Example #16
Source File: TestRc4Filter.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception
{
	Object message = writeRequest.writeRequestMessage();
	if (message instanceof IoBuffer)
	{
		IoBuffer ioBuf = (IoBuffer)message;
		if (ioBuf.hasArray())
			updateOutput(ioBuf.array(), ioBuf.position(), ioBuf.remaining());
		else
			updateOutput(ioBuf.buf(), ioBuf.position(), ioBuf.remaining());
	}
	nextFilter.filterWrite(writeRequest);
}
 
Example #17
Source File: StatisticsFilter.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
{
    updateStats ( session );

    super.filterWrite ( nextFilter, session, writeRequest );
}
 
Example #18
Source File: ProxyFilter.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Actually write data. Queues the data up unless it relates to the handshake or the 
 * handshake is done.
 * 
 * @param nextFilter the next filter in filter chain
 * @param session the session object
 * @param writeRequest the data to write
 * @param isHandshakeData true if writeRequest is written by the proxy classes.
 */
public void writeData(final NextFilter nextFilter, final IoSession session, final WriteRequest writeRequest,
        final boolean isHandshakeData) {
    ProxyLogicHandler handler = getProxyHandler(session);

    synchronized (handler) {
        if (handler.isHandshakeComplete()) {
            // Handshake is done - write data as normal
            nextFilter.filterWrite(session, writeRequest);
        } else if (isHandshakeData) {
            LOGGER.debug("   handshake data: {}", writeRequest.getMessage());

            // Writing handshake data
            nextFilter.filterWrite(session, writeRequest);
        } else {
            // Writing non-handshake data before the handshake finished
            if (!session.isConnected()) {
                // Not even connected - ignore
                LOGGER.debug(" Write request on closed session. Request ignored.");
            } else {
                // Queue the data to be sent as soon as the handshake completes
                LOGGER.debug(" Handshaking is not complete yet. Buffering write request.");
                handler.enqueueWriteRequest(nextFilter, writeRequest);
            }
        }
    }
}
 
Example #19
Source File: AbstractStreamWriteFilter.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 {
    // If we're already processing a stream we need to queue the WriteRequest.
    if (session.getAttribute(CURRENT_STREAM) != null) {
        Queue<WriteRequest> queue = getWriteRequestQueue(session);
        if (queue == null) {
            queue = new ConcurrentLinkedQueue<WriteRequest>();
            session.setAttribute(WRITE_REQUEST_QUEUE, queue);
        }
        queue.add(writeRequest);
        return;
    }

    Object message = writeRequest.getMessage();

    if (getMessageClass().isInstance(message)) {

        T stream = getMessageClass().cast(message);

        IoBuffer buffer = getNextBuffer(stream);
        if (buffer == null) {
            // End of stream reached.
            writeRequest.getFuture().setWritten();
            nextFilter.messageSent(session, writeRequest);
        } else {
            session.setAttribute(CURRENT_STREAM, message);
            session.setAttribute(CURRENT_WRITE_REQUEST, writeRequest);

            nextFilter.filterWrite(session, new DefaultWriteRequest(buffer));
        }

    } else {
        nextFilter.filterWrite(session, writeRequest);
    }
}
 
Example #20
Source File: AbstractStreamWriteFilter.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 {
    T stream = getMessageClass().cast(session.getAttribute(CURRENT_STREAM));

    if (stream == null) {
        nextFilter.messageSent(session, writeRequest);
    } else {
        IoBuffer buffer = getNextBuffer(stream);

        if (buffer == null) {
            // End of stream reached.
            session.removeAttribute(CURRENT_STREAM);
            WriteRequest currentWriteRequest = (WriteRequest) session.removeAttribute(CURRENT_WRITE_REQUEST);

            // Write queued WriteRequests.
            Queue<WriteRequest> queue = removeWriteRequestQueue(session);
            if (queue != null) {
                WriteRequest wr = queue.poll();
                while (wr != null) {
                    filterWrite(nextFilter, session, wr);
                    wr = queue.poll();
                }
            }

            currentWriteRequest.getFuture().setWritten();
            nextFilter.messageSent(session, currentWriteRequest);
        } else {
            nextFilter.filterWrite(session, new DefaultWriteRequest(buffer));
        }
    }
}
 
Example #21
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 #22
Source File: TestEcho.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public WriteRequestQueue getWriteRequestQueue(IoSession session)
{
	_wrqCount.getAndIncrement();
	return new WriteRequestQueue()
	{
		private final ArrayDeque<WriteRequest> _wrq = new ArrayDeque<>();

		@Override
		public synchronized boolean offer(WriteRequest writeRequest) // message must be IoBuffer or FileRegion
		{
			_wrq.addLast(writeRequest);
			return true;
		}

		@Override
		public synchronized WriteRequest peek()
		{
			return _wrq.peekFirst();
		}

		@Override
		public synchronized WriteRequest poll()
		{
			return _wrq.pollFirst();
		}

		@Override
		public synchronized String toString()
		{
			return _wrq.toString();
		}
	};
}
 
Example #23
Source File: SslHandler.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
void flushPreHandshakeEvents() throws SSLException {
    IoFilterEvent scheduledWrite;

    while ((scheduledWrite = preHandshakeEventQueue.poll()) != null) {
        sslFilter
                .filterWrite(scheduledWrite.getNextFilter(), session, (WriteRequest) scheduledWrite.getParameter());
    }
}
 
Example #24
Source File: SslFilter.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) {
    if (writeRequest instanceof EncryptedWriteRequest) {
        EncryptedWriteRequest wrappedRequest = (EncryptedWriteRequest) writeRequest;
        nextFilter.messageSent(session, wrappedRequest.getParentRequest());
    } else {
        // ignore extra buffers used for handshaking
    }
}
 
Example #25
Source File: WriteRequestFilter.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 {
    if (writeRequest instanceof FilteredWriteRequest) {
        FilteredWriteRequest req = (FilteredWriteRequest) writeRequest;
        if (req.getParent() == this) {
            nextFilter.messageSent(session, req.getParentRequest());
            return;
        }
    }

    nextFilter.messageSent(session, writeRequest);
}
 
Example #26
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 #27
Source File: ProtocolCodecFilter.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 {
    if (writeRequest instanceof EncodedWriteRequest) {
        return;
    }

    if (writeRequest instanceof MessageWriteRequest) {
        MessageWriteRequest wrappedRequest = (MessageWriteRequest) writeRequest;
        nextFilter.messageSent(session, wrappedRequest.getParentRequest());
    } else {
        nextFilter.messageSent(session, writeRequest);
    }
}
 
Example #28
Source File: NioSession.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public WriteFuture write(Object message) {
	if (message == null)
		throw new IllegalArgumentException("trying to write a null message: not allowed");

	// If the session has been closed or is closing, we can't either send a message to the remote side.
	// We generate a future containing an exception.
	if (isClosing() || !isConnected())
		return DefaultWriteFuture.newNotWrittenFuture(this, new WriteToClosedSessionException(null));

	try {
		if ((message instanceof IoBuffer) && !((IoBuffer)message).hasRemaining()) {
			// Nothing to write: probably an error in the user code
			throw new IllegalArgumentException("message is empty, forgot to call flip()?");
		} else if (message instanceof FileChannel) {
			FileChannel fileChannel = (FileChannel)message;
			message = new DefaultFileRegion(fileChannel, 0, fileChannel.size());
		}
	} catch (IOException e) {
		ExceptionMonitor.getInstance().exceptionCaught(e);
		return DefaultWriteFuture.newNotWrittenFuture(this, e);
	}

	// Now, we can write the message.
	WriteFuture writeFuture = new DefaultWriteFuture(this);
	WriteRequest writeRequest = new DefaultWriteRequest(message, writeFuture);
	filterChain.fireFilterWrite(writeRequest);
	return writeFuture;
}
 
Example #29
Source File: HttpCodec.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void filterWrite(NextFilter next, IoSession session, WriteRequest writeRequest) throws Exception
{
	Object message = writeRequest.writeRequestMessage();
	if (message instanceof Octets) // for raw data
	{
		Octets oct = (Octets)message;
		int n = oct.remain();
		if (n > 0)
			write(next, writeRequest, IoBuffer.wrap(oct.array(), oct.position(), n));
	}
	else if (message instanceof byte[]) // for raw data
	{
		byte[] bytes = (byte[])message;
		if (bytes.length > 0)
			write(next, writeRequest, IoBuffer.wrap(bytes));
	}
	else if (message instanceof ByteBuffer) // for chunked data
	{
		ByteBuffer bb = (ByteBuffer)message;
		write(next, createHexLine((bb).remaining()));
		write(next, IoBuffer.wrap(bb));
		write(next, writeRequest, IoBuffer.wrap(RES_HEAD_END, 0, 2));
	}
	else
		next.filterWrite(writeRequest);
}
 
Example #30
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;
}