Package org.apache.mina.common

Examples of org.apache.mina.common.ByteBuffer


        int matchCount = ctx.getMatchCount();
       
        // Convert delimiter to ByteBuffer if not done yet.
        if (delimBuf == null) {
            ByteBuffer tmp = ByteBuffer.allocate(2).setAutoExpand(true);
            tmp.putString(delimiter.getValue(), charset.newEncoder());
            tmp.flip();
            delimBuf = tmp;
        }

        // Try to find a match
        int oldPos = in.position();
        int oldLimit = in.limit();
        while (in.hasRemaining()) {
            byte b = in.get();
            if (delimBuf.get(matchCount) == b) {
                matchCount++;
                if (matchCount == delimBuf.limit()) {
                    // Found a match.
                    int pos = in.position();
                    in.limit(pos);
                    in.position(oldPos);

                    ctx.append(in);
                   
                    in.limit(oldLimit);
                    in.position(pos);

                    if (ctx.getOverflowPosition() == 0) {
                        ByteBuffer buf = ctx.getBuffer();
                        buf.flip();
                        buf.limit(buf.limit() - matchCount);
                        try {
                            out.write(buf.getString(ctx.getDecoder()));
                        } finally {
                            buf.clear();
                        }
                    } else {
                        int overflowPosition = ctx.getOverflowPosition();
                        ctx.reset();
                        throw new BufferDataException(
View Full Code Here


            encoder = charset.newEncoder();
            session.setAttribute(ENCODER, encoder);
        }

        String value = message.toString();
        ByteBuffer buf = ByteBuffer.allocate(value.length())
                .setAutoExpand(true);
        buf.putString(value, encoder);
        if (buf.position() > maxLineLength) {
            throw new IllegalArgumentException("Line length: " + buf.position());
        }
        buf.putString(delimiter.getValue(), encoder);
        buf.flip();
        out.write(buf);
    }
View Full Code Here

                throws Exception {
            if (!(message instanceof ByteBuffer)) {
                return;
            }

            ByteBuffer rb = (ByteBuffer) message;
            // Write the received data back to remote peer
            ByteBuffer wb = ByteBuffer.allocate(rb.remaining());
            wb.put(rb);
            wb.flip();
            session.write(wb);
        }
View Full Code Here

    }

    public void encode(IoSession session, Object message,
            ProtocolEncoderOutput out) throws Exception {
        HttpResponseMessage msg = (HttpResponseMessage) message;
        ByteBuffer buf = ByteBuffer.allocate(256);
        // Enable auto-expand for easier encoding
        buf.setAutoExpand(true);

        try {
            // output all headers except the content length
            CharsetEncoder encoder = Charset.defaultCharset().newEncoder();
            buf.putString("HTTP/1.1 ", encoder);
            buf.putString(String.valueOf(msg.getResponseCode()), encoder);
            switch (msg.getResponseCode()) {
            case HttpResponseMessage.HTTP_STATUS_SUCCESS:
                buf.putString(" OK", encoder);
                break;
            case HttpResponseMessage.HTTP_STATUS_NOT_FOUND:
                buf.putString(" Not Found", encoder);
                break;
            }
            buf.put(CRLF);
            for (Iterator it = msg.getHeaders().entrySet().iterator(); it
                    .hasNext();) {
                Entry entry = (Entry) it.next();
                buf.putString((String) entry.getKey(), encoder);
                buf.putString(": ", encoder);
                buf.putString((String) entry.getValue(), encoder);
                buf.put(CRLF);
            }
            // now the content length is the body length
            buf.putString("Content-Length: ", encoder);
            buf.putString(String.valueOf(msg.getBodyLength()), encoder);
            buf.put(CRLF);
            buf.put(CRLF);
            // add body
            buf.put(msg.getBody());
            //System.out.println("\n+++++++");
            //for (int i=0; i<buf.position();i++)System.out.print(new String(new byte[]{buf.get(i)}));
            //System.out.println("\n+++++++");
        } catch (CharacterCodingException ex) {
            ex.printStackTrace();
        }

        buf.flip();
        out.write(buf);
    }
View Full Code Here

        }
    }

    private void readSession(DatagramChannel channel, RegistrationRequest req)
            throws Exception {
        ByteBuffer readBuf = ByteBuffer
                .allocate(((DatagramSessionConfig) req.config
                        .getSessionConfig()).getReceiveBufferSize());
        try {
            SocketAddress remoteAddress = channel.receive(readBuf.buf());
            if (remoteAddress != null) {
                DatagramSessionImpl session = (DatagramSessionImpl) newSession(
                        remoteAddress, req.address);

                readBuf.flip();

                ByteBuffer newBuf = ByteBuffer.allocate(readBuf.limit());
                newBuf.put(readBuf);
                newBuf.flip();

                session.increaseReadBytes(newBuf.remaining());
                session.getFilterChain().fireMessageReceived(session, newBuf);
            }
        } finally {
            readBuf.release();
        }
View Full Code Here

                WriteRequest req = writeRequestQueue.peek();
   
                if (req == null)
                    break;
   
                ByteBuffer buf = (ByteBuffer) req.getMessage();
                if (buf.remaining() == 0) {
                    // pop and fire event
                    writeRequestQueue.poll();
   
                    buf.reset();
                   
                    if (!buf.hasRemaining()) {
                        session.increaseWrittenMessages();
                    }
                    session.getFilterChain().fireMessageSent(session, req);
                    continue;
                }
   
                SocketAddress destination = req.getDestination();
                if (destination == null) {
                    destination = session.getRemoteAddress();
                }
   
                int localWrittenBytes = ch.send(buf.buf(), destination);
                writtenBytes += localWrittenBytes;
   
                if (localWrittenBytes == 0 || writtenBytes >= maxWrittenBytes) {
                    // Kernel buffer is full or wrote too much
                    key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
                    return false;
                } else {
                    // pop and fire event
                    writeRequestQueue.poll();
   
                    buf.reset();
                   
                    if (!buf.hasRemaining()) {
                        session.increaseWrittenMessages();
                    }

                    session.getFilterChain().fireMessageSent(session, req);
                }
View Full Code Here

                    Object message = writeRequest.getMessage();

                    int byteCount = 1;
                    Object messageCopy = message;
                    if (message instanceof ByteBuffer) {
                        ByteBuffer rb = (ByteBuffer) message;
                        rb.mark();
                        byteCount = rb.remaining();
                        ByteBuffer wb = ByteBuffer.allocate(rb.remaining());
                        wb.put(rb);
                        wb.flip();
                        rb.reset();
                        messageCopy = wb;
                    }

                    // Avoid unwanted side effect that scheduledWrite* becomes negative
View Full Code Here

        selectedKeys.clear();
    }

    private void read(SocketSessionImpl session) {
        ByteBuffer buf = ByteBuffer.allocate(session.getReadBufferSize());
        SocketChannel ch = session.getChannel();

        try {
            int readBytes = 0;
            int ret;

            try {
                while ((ret = ch.read(buf.buf())) > 0) {
                    readBytes += ret;
                }
            } finally {
                buf.flip();
            }

            session.increaseReadBytes(readBytes);

            if (readBytes > 0) {
                session.getFilterChain().fireMessageReceived(session, buf);
                buf = null;

                if (readBytes * 2 < session.getReadBufferSize()) {
                    session.decreaseReadBufferSize();
                } else if (readBytes == session.getReadBufferSize()) {
                    session.increaseReadBufferSize();
                }
            }
            if (ret < 0) {
                scheduleRemove(session);
            }
        } catch (Throwable e) {
            if (e instanceof IOException)
                scheduleRemove(session);
            session.getFilterChain().fireExceptionCaught(session, e);
        } finally {
            if (buf != null)
                buf.release();
        }
    }
View Full Code Here

    private void releaseWriteBuffers(SocketSessionImpl session) {
        Queue<WriteRequest> writeRequestQueue = session.getWriteRequestQueue();
        WriteRequest req;

        if ((req = writeRequestQueue.poll()) != null) {
            ByteBuffer buf = (ByteBuffer) req.getMessage();
            try {
                buf.release();
            } catch (IllegalStateException e) {
                session.getFilterChain().fireExceptionCaught(session, e);
            } finally {
                // The first unwritten empty buffer must be
                // forwarded to the filter chain.
                if (buf.hasRemaining()) {
                    req.getFuture().setWritten(false);
                } else {
                    session.getFilterChain().fireMessageSent(session, req);
                }
            }
View Full Code Here

                WriteRequest req = writeRequestQueue.peek();

                if (req == null)
                    break;

                ByteBuffer buf = (ByteBuffer) req.getMessage();
                if (buf.remaining() == 0) {
                    writeRequestQueue.poll();

                    buf.reset();
                   
                    if (!buf.hasRemaining()) {
                        session.increaseWrittenMessages();
                    }
                   
                    session.getFilterChain().fireMessageSent(session, req);
                    continue;
                }

                int localWrittenBytes = 0;
                for (int i = WRITE_SPIN_COUNT; i > 0; i --) {
                    localWrittenBytes = ch.write(buf.buf());
                    if (localWrittenBytes != 0 || !buf.hasRemaining()) {
                        break;
                    }
                }

                writtenBytes += localWrittenBytes;
View Full Code Here

TOP

Related Classes of org.apache.mina.common.ByteBuffer

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.