Example usage for java.nio ByteBuffer remaining

List of usage examples for java.nio ByteBuffer remaining

Introduction

In this page you can find the example usage for java.nio ByteBuffer remaining.

Prototype

public final int remaining() 

Source Link

Document

Returns the number of remaining elements in this buffer, that is limit - position .

Usage

From source file:org.apache.james.protocols.imap.core.IMAPCommandDispatcher.java

@Override
protected Request parseRequest(IMAPSession session, ByteBuffer buffer) throws Exception {
    IMAPRequest request = new IMAPRequest(buffer);
    Matcher matcher = LITERAL_PATTERN.matcher(request.getArgument());
    if (matcher.matches()) {
        final long bytesToRead = Long.parseLong(matcher.group(1));
        MultiLineHandler<IMAPSession> handler = new MultiLineHandler<IMAPSession>() {

            private static final String BYTES_READ = "BYTES_READ";

            @Override/*  w ww.  j a v  a 2s. co  m*/
            public void init(Configuration config) throws ConfigurationException {

            }

            @Override
            public void destroy() {

            }

            /*
             * (non-Javadoc)
             * @see org.apache.james.protocols.api.handler.MultiLineHandler#isReady(org.apache.james.protocols.api.ProtocolSession, java.nio.ByteBuffer)
             */
            protected boolean isReady(IMAPSession session, ByteBuffer line) {
                long bytesRead = (Long) session.setAttachment(BYTES_READ, null, State.Transaction);
                bytesRead += line.remaining();
                if (bytesRead >= bytesToRead) {
                    return true;
                } else {
                    session.setAttachment(BYTES_READ, bytesRead, State.Transaction);
                    return false;
                }
            }

            @Override
            protected Response onLines(IMAPSession session, Collection<ByteBuffer> lines) {
                session.popLineHandler();
                return dispatchCommandHandlers(session, new IMAPRequest(lines));
            }
        };
        buffer.rewind();

        // push the line to the handler
        handler.onLine(session, buffer);

        session.pushLineHandler(handler);
        return null;

    } else {
        return request;
    }
}

From source file:gridool.communication.transport.nio.GridNioServer.java

private static void handleRead(final SocketChannel channel, final SelectionKey key,
        final ByteBuffer sharedReadBuf, final GridTransportListener notifier, final ExecutorService exec) {
    sharedReadBuf.clear();//from  ww  w  . j a  v  a 2s  .  co m
    final SocketAddress remoteAddr = channel.socket().getRemoteSocketAddress();
    final int bytesRead;
    try {
        bytesRead = channel.read(sharedReadBuf);
    } catch (IOException e) {
        LOG.warn("Failed to read data from client: " + remoteAddr, e);
        NIOUtils.close(key);
        return;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Read " + bytesRead + " bytes from a client socket: " + remoteAddr);
    }
    if (bytesRead == -1) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Remote client closed connection: " + remoteAddr);
        }
        NIOUtils.close(key);
        return;
    } else if (bytesRead == 0) {
        return;
    }

    final GridMessageBuffer msgBuf = (GridMessageBuffer) key.attachment();
    sharedReadBuf.flip();
    while (sharedReadBuf.remaining() > 0) {
        msgBuf.read(sharedReadBuf);
        if (msgBuf.isFilled()) {
            exec.execute(new Runnable() {
                public void run() {
                    final GridCommunicationMessage msg = msgBuf.toMessage();
                    msgBuf.reset();
                    if (LOG.isInfoEnabled()) {
                        LOG.info("Recieved a GridCommunicationMessage [" + msg.getMessageId() + "]");
                    }
                    notifier.notifyListener(msg);
                }
            });
            break;
        }
    }
}

From source file:com.bendb.thrifty.testing.ThriftTestHandler.java

@Override
public ByteBuffer testBinary(ByteBuffer thing) throws TException {
    int count = thing.remaining();
    byte[] data = new byte[count];
    thing.get(data);/*w  w  w  .  j  a v  a 2s.  co  m*/

    out.printf("testBinary(\"%s\")\n", Hex.encodeHexString(data));

    return ByteBuffer.wrap(data);
}

From source file:com.github.cambierr.lorawanpacket.semtech.PullResp.java

public PullResp(byte[] _randoms, ByteBuffer _raw) throws MalformedPacketException {
    super(_randoms, PacketType.PULL_RESP);
    _raw.order(ByteOrder.LITTLE_ENDIAN);

    if (_raw.remaining() < 1) {
        throw new MalformedPacketException("too short");
    }//  w w w .j a  v  a2s  .  c o  m

    byte[] json = new byte[_raw.remaining()];
    _raw.get(json);
    JSONObject jo;

    try {
        jo = new JSONObject(new String(json));
    } catch (JSONException ex) {
        throw new MalformedPacketException("malformed json");
    }

    txpks = new ArrayList<>();

    if (!jo.has("txpk")) {
        throw new MalformedPacketException("missing json (txpk)");
    }

    if (!jo.get("txpk").getClass().equals(JSONArray.class)) {
        throw new MalformedPacketException("malformed json (txpk)");
    }
    JSONArray rxpk = jo.getJSONArray("txpk");

    for (int i = 0; i < rxpk.length(); i++) {
        txpks.add(new Txpk(rxpk.getJSONObject(i)));
    }
}

From source file:com.taobao.adfs.distributed.rpc.Server.java

/**
 * This is a wrapper around {@link WritableByteChannel#write(ByteBuffer)}. If the amount of data is large, it writes
 * to channel in smaller chunks. This is to avoid jdk from creating many direct buffers as the size of buffer
 * increases. This also minimizes extra copies in NIO layer as a result of multiple write operations required to write
 * a large buffer./*from w  w w. j ava 2  s  .  co m*/
 * 
 * @see WritableByteChannel#write(ByteBuffer)
 */
private static int channelWrite(WritableByteChannel channel, ByteBuffer buffer) throws IOException {

    return (buffer.remaining() <= NIO_BUFFER_LIMIT) ? channel.write(buffer) : channelIO(null, channel, buffer);
}

From source file:com.taobao.adfs.distributed.rpc.Server.java

/**
 * This is a wrapper around {@link ReadableByteChannel#read(ByteBuffer)}. If the amount of data is large, it writes to
 * channel in smaller chunks. This is to avoid jdk from creating many direct buffers as the size of ByteBuffer
 * increases. There should not be any performance degredation.
 * //from  ww  w.  ja  v a2s. c  o  m
 * @see ReadableByteChannel#read(ByteBuffer)
 */
private static int channelRead(ReadableByteChannel channel, ByteBuffer buffer) throws IOException {

    return (buffer.remaining() <= NIO_BUFFER_LIMIT) ? channel.read(buffer) : channelIO(channel, null, buffer);
}

From source file:Base64Encoder.java

/**
 * Encodes one or more characters into one or more bytes.
 *
 * <p> This method encapsulates the basic encoding loop, encoding as many
 * characters as possible until it either runs out of input, runs out of room
 * in the output buffer, or encounters an encoding error.  This method is
 * invoked by the {@link #encode encode} method, which handles result
 * interpretation and error recovery./*from w  ww .  j a  v  a2  s .  c  o m*/
 *
 * <p> The buffers are read from, and written to, starting at their current
 * positions.  At most {@link Buffer#remaining in.remaining()} characters
 * will be read, and at most {@link Buffer#remaining out.remaining()}
 * bytes will be written.  The buffers' positions will be advanced to
 * reflect the characters read and the bytes written, but their marks and
 * limits will not be modified.
 *
 * <p> This method returns a {@link CoderResult} object to describe its
 * reason for termination, in the same manner as the {@link #encode encode}
 * method.  Most implementations of this method will handle encoding errors
 * by returning an appropriate result object for interpretation by the
 * {@link #encode encode} method.  An optimized implementation may instead
 * examine the relevant error action and implement that action itself.
 *
 * <p> An implementation of this method may perform arbitrary lookahead by
 * returning {@link CoderResult#UNDERFLOW} until it receives sufficient
 * input.  </p>
 *
 * @param  in
 *         The input character buffer
 *
 * @param  out
 *         The output byte buffer
 *
 * @return  A coder-result object describing the reason for termination
 */
public java.nio.charset.CoderResult encodeLoop(java.nio.CharBuffer in, java.nio.ByteBuffer out) {
    if (excessByte != null) {
        if (out.remaining() > 0) {
            out.put(excessByte.byteValue());
            excessByte = null;
        } else
            return CoderResult.OVERFLOW;

    }
    while (in.remaining() > 0) {
        char inch = in.get();
        int code = (int) inch >= encTable.length ? CHARCODE_INVALID : encTable[(int) inch];
        if (encState < 4) {
            switch (code) {
            case CHARCODE_INVALID:
                throw new IllegalArgumentException("Invalid base-64 character'" + inch + "'");
            case CHARCODE_WHITESPACE:
                break;
            case CHARCODE_PADDER:
                if (encState == 1)
                    throw new IllegalArgumentException("Mal-formed base-64 (= after one character");
                encState = 4;
                break;
            default:
                switch (encState) {
                case 0:
                    bits = code << 2;
                    encState = 1;
                    break;
                case 1:
                    encState = 2;
                    int v = bits | ((code >> 4) & 3);
                    bits = (code << 4) & 0xF0;
                    if (!out(out, v))
                        return CoderResult.OVERFLOW;
                    break;
                case 2:
                    encState = 3;
                    v = bits | (code >> 2) & 0x0f;
                    bits = (code << 6) & 0xC0;
                    if (!out(out, v))
                        return CoderResult.OVERFLOW;
                    break;
                case 3:
                    encState = 0;
                    bits |= (code & 0x3f);
                    if (!out(out, bits))
                        return CoderResult.OVERFLOW;
                    break;
                }

                break;
            }

        }
    }
    return CoderResult.UNDERFLOW;
}

From source file:com.github.srgg.yads.impl.context.communication.AbstractTransport.java

protected final int onReceive(final String sender, final String recipient, final ByteBuffer bb)
        throws Exception {
    // -- decode/*from  w w w.  j  a  va 2s  .  com*/
    if (bb.remaining() < 4) {
        return 4;
    }

    bb.mark();
    final int length = bb.getInt();

    if (bb.remaining() < length) {
        bb.reset();
        return length;
    }

    final byte msgCode = bb.get();
    final byte[] p = new byte[length - 1];
    bb.get(p);

    final Class<? extends Message> c = getMessageClass(msgCode);
    final Message msg = payloadMapper.fromBytes(c, p);

    // -- fire
    final Messages.MessageTypes mt = Messages.MessageTypes.valueOf(msgCode);
    if (logger.isTraceEnabled()) {
        logger.trace(MessageUtils.dumpMessage(msg, "[MSG IN] '%s' -> '%s': %s@%s", msg.getSender(), recipient,
                mt, msg.getId()));
    } else {
        logger.debug("[MSG IN]  '{}' -> '{}': {}@{}", sender, recipient, mt, msg.getId());
    }

    boolean isHandled = true;
    if (recipient != null) {
        final CommunicationContext.MessageListener listener = handlerById(recipient);
        checkState(listener != null,
                "Can't process received message '%s' sended by '%s', recipient '%s' is not registered.",
                msgCode, sender, recipient);

        isHandled = listener.onMessage(recipient, mt, msg);
    } else {
        for (Map.Entry<String, CommunicationContext.MessageListener> e : handlers()) {
            if (!e.getValue().onMessage(null, mt, msg)) {
                isHandled = false;
            }
        }
    }

    if (!isHandled) {
        unhandledMessage(sender, recipient, mt, msg);
    }

    return -1;
}

From source file:gridool.communication.transport.tcp.GridNioClient.java

public void sendMessage(SocketAddress sockAddr, GridCommunicationMessage msg) throws GridException {
    final SocketChannel channel;
    try {/* w w  w. j  a  v a  2  s  . c om*/
        channel = SocketChannel.open();
    } catch (IOException e) {
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw new GridException(e);
    }
    final Socket socket = channel.socket();
    try {
        SocketUtils.openSocket(socket, sockAddr, 0, 2000L, 3);
    } catch (IOException e) {
        NetUtils.closeQuietly(socket);
        IOUtils.closeQuietly(channel);
        LOG.error(PrintUtils.prettyPrintStackTrace(e, -1));
        throw new GridException(e);
    }

    final ByteBuffer buf = toBuffer(msg);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Sending a GridCommunicationMessage [" + msg.getMessageId() + " (" + buf.remaining()
                + " bytes)] to a node [" + sockAddr + "] using a channel [" + channel + ']');
    }
    final int written;
    try {
        written = NIOUtils.countingWriteFully(channel, buf);
        NetUtils.shutdownOutputQuietly(socket); // terminate socket output (send FIN)
    } catch (IOException ioe) {
        final String errmsg = "Failed to send a GridCommunicationMessage [" + msg + "] to host [" + sockAddr
                + ']';
        LOG.error(errmsg, ioe);
        throw new GridException(errmsg, ioe);
    } catch (Throwable e) {
        LOG.fatal(e.getMessage(), e);
        throw new GridException("Unexpected exception was caused", e);
    } finally {
        NetUtils.closeQuietly(socket);
        IOUtils.closeQuietly(channel);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Succeeded to send a GridCommunicationMessage (" + written + " bytes) to host [" + sockAddr
                + "]");
    }
}

From source file:com.ebuddy.cassandra.structure.StructureConverter.java

/**
 * @throws DataFormatException is data in the byte buffer is incorrect and cannot be decoded
 *///from  w  w w. j a  va2s  .c o m
public Object fromByteBuffer(ByteBuffer byteBuffer) {
    if (byteBuffer == null) {
        return null;
    }
    byte[] bytes = new byte[byteBuffer.remaining()];
    byteBuffer.get(bytes, 0, bytes.length);
    return decodeBytes(bytes);
}