当前位置: 首页>>代码示例>>Java>>正文


Java IoBuffer.position方法代码示例

本文整理汇总了Java中org.apache.mina.core.buffer.IoBuffer.position方法的典型用法代码示例。如果您正苦于以下问题:Java IoBuffer.position方法的具体用法?Java IoBuffer.position怎么用?Java IoBuffer.position使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.apache.mina.core.buffer.IoBuffer的用法示例。


在下文中一共展示了IoBuffer.position方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: handleResponse

import org.apache.mina.core.buffer.IoBuffer; //导入方法依赖的package包/类
/**
 * Handle a SOCKS4/SOCKS4a response from the proxy server. Test
 * the response buffer reply code and call {@link #setHandshakeComplete()}
 * if access is granted.
 * 
 * @param buf the buffer holding the server response data.
 * @throws exception if server response is malformed or if request is rejected
 * by the proxy server.
 */
protected void handleResponse(final IoBuffer buf) throws Exception {
    byte first = buf.get(0);

    if (first != 0) {
        throw new Exception("Socks response seems to be malformed");
    }

    byte status = buf.get(1);

    // Consumes all the response data from the buffer
    buf.position(buf.position() + SocksProxyConstants.SOCKS_4_RESPONSE_SIZE);

    if (status == SocksProxyConstants.V4_REPLY_REQUEST_GRANTED) {
        setHandshakeComplete();
    } else {
        throw new Exception("Proxy handshake failed - Code: 0x" + ByteUtilities.asHex(new byte[] { status }) + " ("
                + SocksProxyConstants.getReplyCodeAsString(status) + ")");
    }
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:29,代码来源:Socks4LogicHandler.java

示例2: encode

import org.apache.mina.core.buffer.IoBuffer; //导入方法依赖的package包/类
public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
    if (!(message instanceof Serializable)) {
        throw new NotSerializableException();
    }

    IoBuffer buf = IoBuffer.allocate(64);
    buf.setAutoExpand(true);
    buf.putObject(message);

    int objectSize = buf.position() - 4;
    if (objectSize > maxObjectSize) {
        throw new IllegalArgumentException("The encoded object is too big: " + objectSize + " (> " + maxObjectSize
                + ')');
    }

    buf.flip();
    out.write(buf);
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:19,代码来源:ObjectSerializationEncoder.java

示例3: readObject

import org.apache.mina.core.buffer.IoBuffer; //导入方法依赖的package包/类
public Object readObject() throws ClassNotFoundException, IOException {
    int objectSize = in.readInt();
    if (objectSize <= 0) {
        throw new StreamCorruptedException("Invalid objectSize: " + objectSize);
    }
    if (objectSize > maxObjectSize) {
        throw new StreamCorruptedException("ObjectSize too big: " + objectSize + " (expected: <= " + maxObjectSize
                + ')');
    }

    IoBuffer buf = IoBuffer.allocate(objectSize + 4, false);
    buf.putInt(objectSize);
    in.readFully(buf.array(), 4, objectSize);
    buf.position(0);
    buf.limit(objectSize + 4);

    return buf.getObject(classLoader);
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:19,代码来源:ObjectSerializationInputStream.java

示例4: decode

import org.apache.mina.core.buffer.IoBuffer; //导入方法依赖的package包/类
/**
 * {@inheritDoc}
 */
public DecodingState decode(IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    int beginPos = in.position();
    int limit = in.limit();
    for (int i = beginPos; i < limit; i++) {
        byte b = in.get(i);
        if (!canSkip(b)) {
            in.position(i);
            int answer = this.skippedBytes;
            this.skippedBytes = 0;
            return finishDecode(answer);
        }

        skippedBytes++;
    }

    in.position(limit);
    return this;
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:22,代码来源:SkippingState.java

示例5: decodeTimeoutFrame

import org.apache.mina.core.buffer.IoBuffer; //导入方法依赖的package包/类
private void decodeTimeoutFrame ( final IoSession session, final IoBuffer currentFrame, final ProtocolDecoderOutput out )
{
    logger.trace ( "timeout () frame = {}", currentFrame.getHexDump () );

    if ( currentFrame.limit () <= Constants.RTU_HEADER_SIZE )
    {
        throw new ModbusProtocolError ( "frame must be at least 4 bytes long (address + data[] + crc low + crc high" );
    }

    currentFrame.order ( ByteOrder.LITTLE_ENDIAN );
    final int receivedCrc = currentFrame.getUnsignedShort ( currentFrame.limit () - 2 );
    currentFrame.order ( ByteOrder.BIG_ENDIAN );

    final int actualCrc = Checksum.crc16 ( currentFrame.array (), 0, currentFrame.limit () - 2 );
    if ( receivedCrc != actualCrc )
    {
        final String hd = currentFrame.getHexDump ();
        logger.info ( "CRC error - received: {}, calculated: {} - data: {}", receivedCrc, actualCrc, hd );
        throw new ChecksumProtocolException ( String.format ( "CRC error. received: %04x, but actually was: %04x - Data: %s", receivedCrc, actualCrc, hd ) );
    }

    currentFrame.position ( 0 );

    // get unit id
    final byte unitIdentifier = currentFrame.get ();

    final int len = currentFrame.limit () - ( 2 /*crc*/+ 1/*unit id*/);

    final IoBuffer pdu = IoBuffer.allocate ( len );
    for ( int i = 0; i < len; i++ )
    {
        pdu.put ( currentFrame.get () );
    }
    pdu.flip ();

    // decode and send
    logger.trace ( "Decoded PDU - data: {}", pdu.getHexDump () );
    out.write ( new Pdu ( 0, unitIdentifier, pdu ) );
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:40,代码来源:ModbusRtuDecoder.java

示例6: writeBuffer

import org.apache.mina.core.buffer.IoBuffer; //导入方法依赖的package包/类
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;
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:40,代码来源:AbstractPollingIoProcessor.java

示例7: messageReceived

import org.apache.mina.core.buffer.IoBuffer; //导入方法依赖的package包/类
/**
 * Receives data from the remote host, passes to the handler if a handshake is in progress, 
 * otherwise passes on transparently.
 * 
 * @param nextFilter the next filter in filter chain
 * @param session the session object
 * @param message the object holding the received data
 */
@Override
public void messageReceived(final NextFilter nextFilter, final IoSession session, final Object message)
        throws ProxyAuthException {
    ProxyLogicHandler handler = getProxyHandler(session);

    synchronized (handler) {
        IoBuffer buf = (IoBuffer) message;

        if (handler.isHandshakeComplete()) {
            // Handshake done - pass data on as-is
            nextFilter.messageReceived(session, buf);

        } else {
            LOGGER.debug(" Data Read: {} ({})", handler, buf);

            // Keep sending handshake data to the handler until we run out
            // of data or the handshake is finished
            while (buf.hasRemaining() && !handler.isHandshakeComplete()) {
                LOGGER.debug(" Pre-handshake - passing to handler");

                int pos = buf.position();
                handler.messageReceived(nextFilter, buf);

                // Data not consumed or session closing
                if (buf.position() == pos || session.isClosing()) {
                    return;
                }
            }

            // Pass on any remaining data to the next filter
            if (buf.hasRemaining()) {
                LOGGER.debug(" Passing remaining data to next filter");

                nextFilter.messageReceived(session, buf);
            }
        }
    }
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:47,代码来源:ProxyFilter.java

示例8: isCloseNotify

import org.apache.mina.core.buffer.IoBuffer; //导入方法依赖的package包/类
private boolean isCloseNotify(Object message) {
    if (!(message instanceof IoBuffer)) {
        return false;
    }

    IoBuffer buf = (IoBuffer) message;
    int offset = buf.position();
    return (buf.get(offset + 0) == 0x15) /* Alert */
            && (buf.get(offset + 1) == 0x03) /* TLS/SSL */
            && ((buf.get(offset + 2) == 0x00) /* SSL 3.0 */
                    || (buf.get(offset + 2) == 0x01) /* TLS 1.0 */
                    || (buf.get(offset + 2) == 0x02) /* TLS 1.1 */
            || (buf.get(offset + 2) == 0x03)) /* TLS 1.2 */
            && (buf.get(offset + 3) == 0x00); /* close_notify */
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:16,代码来源:SslFilter.java

示例9: decode

import org.apache.mina.core.buffer.IoBuffer; //导入方法依赖的package包/类
/**
 * {@inheritDoc}
 */
public DecodingState decode(IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    boolean found = false;
    boolean finished = false;
    while (in.hasRemaining()) {
        byte b = in.get();
        if (!hasCR) {
            if (b == CR) {
                hasCR = true;
            } else {
                if (b == LF) {
                    found = true;
                } else {
                    in.position(in.position() - 1);
                    found = false;
                }
                finished = true;
                break;
            }
        } else {
            if (b == LF) {
                found = true;
                finished = true;
                break;
            }

            throw new ProtocolDecoderException("Expected LF after CR but was: " + (b & 0xff));
        }
    }

    if (finished) {
        hasCR = false;
        return finishDecode(found, out);
    }

    return this;
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:40,代码来源:CrLfDecodingState.java

示例10: messageReceived

import org.apache.mina.core.buffer.IoBuffer; //导入方法依赖的package包/类
@Override
public void messageReceived ( final NextFilter nextFilter, final IoSession session, final Object message ) throws Exception
{
    if ( ! ( message instanceof IoBuffer ) )
    {
        nextFilter.messageReceived ( session, message );
        return;
    }

    final IoBuffer in = (IoBuffer)message;
    final IoBuffer sessionBuffer = getSessionBuffer ( session );

    // first add to the session buffer (may be optimized later)
    sessionBuffer.position ( sessionBuffer.limit () );
    sessionBuffer.put ( in );
    sessionBuffer.flip ();

    while ( sessionBuffer.remaining () >= 4 )
    {
        final int len = sessionBuffer.getUnsignedShort ( 2 );
        if ( sessionBuffer.remaining () < len )
        {
            logger.debug ( "Next packet requires {} bytes", new Object[] { len } );
            // not enough data for body
            return;
        }

        // convert
        final IoBuffer data = IoBuffer.allocate ( len - 4 );
        sessionBuffer.get (); // version
        sessionBuffer.get (); // reserved
        sessionBuffer.getUnsignedShort (); // length

        sessionBuffer.get ( data.array () );

        nextFilter.messageReceived ( session, data );

        logger.debug ( "{} bytes left in session buffer", sessionBuffer.remaining () );
    }

    if ( sessionBuffer.hasRemaining () )
    {
        sessionBuffer.compact ();
    }
    else
    {
        sessionBuffer.clear ().flip ();
    }
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:50,代码来源:TPKTFilter.java

示例11: doDecode

import org.apache.mina.core.buffer.IoBuffer; //导入方法依赖的package包/类
@Override
protected boolean doDecode ( final IoSession session, final IoBuffer data, final ProtocolDecoderOutput output ) throws Exception
{
    logger.trace ( "decode data - session: {}, data: {}", session, data );

    if ( data.remaining () < HEADER_SIZE )
    {
        return false;
    }

    final int position = data.position ();

    final byte version = data.get ( position ); // peek at version
    if ( version != 0x01 )
    {
        throw new IllegalStateException ( String.format ( "Version 0x%02x is not supported.", version ) );
    }

    final int frameTypeOrdinal = data.get ( position + 1 ); // peek at frame type
    final FrameType frameType = FrameType.values ()[frameTypeOrdinal]; // may case an exception, that is ok then

    final int dataLength = data.getInt ( position + 2 ); // we need to look at "here" + 2

    logger.trace ( "Data length: {}, remainingData: {}", dataLength, data.remaining () - 6 );

    if ( data.remaining () < HEADER_SIZE + dataLength )
    {
        return false;
    }

    // consume fields
    data.get (); // version - #0
    data.get (); // frame type - #1
    data.getInt (); // dataLength - #2

    // data - #6
    final IoBuffer frameData = data.getSlice ( dataLength ); // this also consumes the buffer 'data'

    final Frame frame = new Frame ( frameType, frameData );

    logger.trace ( "Decoded frame: {} ... {} bytes remaining", frame, data.remaining () );
    output.write ( frame );

    return true;
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:46,代码来源:FrameDecoder.java

示例12: removeTo

import org.apache.mina.core.buffer.IoBuffer; //导入方法依赖的package包/类
/**
 * Remove component <code>ByteArray</code>s to the given index (splitting
 * them if necessary) and returning them in a single <code>ByteArray</code>.
 * The caller is responsible for freeing the returned object.
 *
 * TODO: Document free behaviour more thoroughly.
 */
public ByteArray removeTo(int index) {
    if (index < first() || index > last()) {
        throw new IndexOutOfBoundsException();
    }
    // Optimisation when removing exactly one component.
    //        if (index == start() + getFirst().length()) {
    //            ByteArray component = getFirst();
    //            removeFirst();
    //            return component;
    //        }
    // Removing
    CompositeByteArray prefix = new CompositeByteArray(byteArrayFactory);
    int remaining = index - first();

    while (remaining > 0) {
        ByteArray component = removeFirst();

        if (component.last() <= remaining) {
            // Remove entire component.
            prefix.addLast(component);
            remaining -= component.last();
        } else {
            // Remove part of component. Do this by removing entire
            // component then readding remaining bytes.
            // TODO: Consider using getIoBuffers(), as would avoid
            // performance problems for nested ComponentByteArrays.
            IoBuffer bb = component.getSingleIoBuffer();
            // get the limit of the buffer
            int originalLimit = bb.limit();
            // set the position to the beginning of the buffer
            bb.position(0);
            // set the limit of the buffer to what is remaining
            bb.limit(remaining);
            // create a new IoBuffer, sharing the data with 'bb'
            IoBuffer bb1 = bb.slice();
            // set the position at the end of the buffer
            bb.position(remaining);
            // gets the limit of the buffer
            bb.limit(originalLimit);
            // create a new IoBuffer, sharing teh data with 'bb'
            IoBuffer bb2 = bb.slice();
            // create a new ByteArray with 'bb1'
            ByteArray ba1 = new BufferByteArray(bb1) {
                @Override
                public void free() {
                    // Do not free.  This will get freed 
                }
            };

            // add the new ByteArray to the CompositeByteArray
            prefix.addLast(ba1);
            remaining -= ba1.last();

            // final for anonymous inner class
            final ByteArray componentFinal = component;
            ByteArray ba2 = new BufferByteArray(bb2) {
                @Override
                public void free() {
                    componentFinal.free();
                }
            };
            // add the new ByteArray to the CompositeByteArray
            addFirst(ba2);
        }
    }

    // return the CompositeByteArray
    return prefix;
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:77,代码来源:CompositeByteArray.java

示例13: filterWrite

import org.apache.mina.core.buffer.IoBuffer; //导入方法依赖的package包/类
@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();
    }
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:46,代码来源:SslFilter.java

示例14: decode

import org.apache.mina.core.buffer.IoBuffer; //导入方法依赖的package包/类
/**
 * {@inheritDoc}
 */
public DecodingState decode(IoBuffer in, ProtocolDecoderOutput out) throws Exception {
    int terminatorPos = in.indexOf(terminator);

    if (terminatorPos >= 0) {
        int limit = in.limit();
        IoBuffer product;

        if (in.position() < terminatorPos) {
            in.limit(terminatorPos);

            if (buffer == null) {
                product = in.slice();
            } else {
                buffer.put(in);
                product = buffer.flip();
                buffer = null;
            }

            in.limit(limit);
        } else {
            // When input contained only terminator rather than actual data...
            if (buffer == null) {
                product = IoBuffer.allocate(0);
            } else {
                product = buffer.flip();
                buffer = null;
            }
        }
        in.position(terminatorPos + 1);
        return finishDecode(product, out);
    }

    if (buffer == null) {
        buffer = IoBuffer.allocate(in.remaining());
        buffer.setAutoExpand(true);
    }

    buffer.put(in);
    return this;
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:44,代码来源:ConsumeToTerminatorDecodingState.java

示例15: messageReceived

import org.apache.mina.core.buffer.IoBuffer; //导入方法依赖的package包/类
/**
 * Process the incoming message, calling the session decoder. As the incoming
 * buffer might contains more than one messages, we have to loop until the decoder
 * throws an exception.
 * 
 *  while ( buffer not empty )
 *    try
 *      decode ( buffer )
 *    catch
 *      break;
 * 
 */
@Override
public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception {
    LOGGER.debug("Processing a MESSAGE_RECEIVED for session {}", session.getId());

    if (!(message instanceof IoBuffer)) {
        nextFilter.messageReceived(session, message);
        return;
    }

    IoBuffer in = (IoBuffer) message;
    ProtocolDecoder decoder = factory.getDecoder(session);
    ProtocolDecoderOutput decoderOut = getDecoderOut(session, nextFilter);

    // Loop until we don't have anymore byte in the buffer,
    // or until the decoder throws an unrecoverable exception or
    // can't decoder a message, because there are not enough
    // data in the buffer
    while (in.hasRemaining()) {
        int oldPos = in.position();

        try {
            synchronized (decoderOut) {
                // Call the decoder with the read bytes
                decoder.decode(session, in, decoderOut);
            }

            // Finish decoding if no exception was thrown.
            decoderOut.flush(nextFilter, session);
        } catch (Throwable t) {
            ProtocolDecoderException pde;
            if (t instanceof ProtocolDecoderException) {
                pde = (ProtocolDecoderException) t;
            } else {
                pde = new ProtocolDecoderException(t);
            }

            if (pde.getHexdump() == null) {
                // Generate a message hex dump
                int curPos = in.position();
                in.position(oldPos);
                pde.setHexdump(in.getHexDump());
                in.position(curPos);
            }

            // Fire the exceptionCaught event.
            decoderOut.flush(nextFilter, session);
            nextFilter.exceptionCaught(session, pde);

            // Retry only if the type of the caught exception is
            // recoverable and the buffer position has changed.
            // We check buffer position additionally to prevent an
            // infinite loop.
            if (!(t instanceof RecoverableProtocolDecoderException) || (in.position() == oldPos)) {
                break;
            }
        }
    }
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:71,代码来源:ProtocolCodecFilter.java


注:本文中的org.apache.mina.core.buffer.IoBuffer.position方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。