Example usage for java.nio ByteBuffer compact

List of usage examples for java.nio ByteBuffer compact

Introduction

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

Prototype

public abstract ByteBuffer compact();

Source Link

Document

Compacts this byte buffer.

Usage

From source file:net.kungfoo.grizzly.proxy.impl.ConnectingHandler.java

public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) {
    System.out.println(conn + " [proxy<-origin] input ready");

    HttpContext context = conn.getContext();
    ProxyProcessingInfo proxyTask = (ProxyProcessingInfo) context.getAttribute(ProxyProcessingInfo.ATTRIB);

    synchronized (proxyTask) {
        ConnState connState = proxyTask.getOriginState();
        if (connState != ConnState.RESPONSE_RECEIVED && connState != ConnState.RESPONSE_BODY_STREAM) {
            throw new IllegalStateException("Illegal target connection state: " + connState);
        }/*from  ww w .j  av  a 2s  . c o m*/

        final Response response = proxyTask.getResponse();
        try {

            ByteBuffer dst = proxyTask.getOutBuffer();
            int bytesRead = decoder.read(dst);
            if (bytesRead > 0) {
                dst.flip();
                final ByteChunk chunk = new ByteChunk(bytesRead);
                final byte[] buf = new byte[bytesRead];
                dst.get(buf);
                chunk.setBytes(buf, 0, bytesRead);
                dst.compact();
                try {
                    response.doWrite(chunk);
                } catch (ClassCastException e) {
                    System.err.println("gone bad: " + e.getMessage());
                    e.printStackTrace(System.err);
                }
                response.flush();
                System.out.println(conn + " [proxy<-origin] " + bytesRead + " bytes read");
                System.out.println(conn + " [proxy<-origin] " + decoder);
            }
            if (!dst.hasRemaining()) {
                // Output buffer is full. Suspend origin input until
                // the client handler frees up some space in the buffer
                conn.suspendInput();
            }
            /*
                    // If there is some content in the buffer make sure client output
                    // is active
                    if (dst.position() > 0) {
                      proxyTask.getClientIOControl().requestOutput();
                    }
            */

            if (decoder.isCompleted()) {
                System.out.println(conn + " [proxy<-origin] response body received");
                proxyTask.setOriginState(ConnState.RESPONSE_BODY_DONE);
                if (!this.connStrategy.keepAlive(conn.getHttpResponse(), context)) {
                    System.out.println(conn + " [proxy<-origin] close connection");
                    proxyTask.setOriginState(ConnState.CLOSING);
                    conn.close();
                }
                proxyTask.getCompletion().run();
            } else {
                proxyTask.setOriginState(ConnState.RESPONSE_BODY_STREAM);
            }

        } catch (IOException ex) {
            shutdownConnection(conn);
        }
    }
}

From source file:net.timewalker.ffmq4.transport.tcp.nio.NIOTcpMultiplexer.java

protected boolean readAndProcessChannelData(NIOClientSocketHandler clientHandler) {
    try {/*from   www .j  a v a 2s. co m*/
        ByteBuffer inputBuffer = clientHandler.getInputBuffer();
        int readAmount = clientHandler.getSocketChannel().read(inputBuffer);
        if (readAmount <= 0) {
            log.debug("[" + clientHandler.getId() + "] Cannot read, channel socket was closed");
            return false;
        }

        inputBuffer.flip(); // Prepare for reading
        boolean status = clientHandler.handleIncomingData();
        inputBuffer.compact(); // Restore pointers

        return status;
    } catch (IOException e) {
        log.debug("[" + clientHandler.getId() + "] Read failed : " + e.getMessage());
        return false;
    } catch (Exception e) {
        log.error("[" + clientHandler.getId() + "] Could not read channel data", e);
        return false;
    }
}

From source file:org.apache.nifi.processor.util.listen.handler.socket.StandardSocketChannelHandler.java

@Override
public void run() {
    boolean eof = false;
    SocketChannel socketChannel = null;

    try {// w ww .ja  v  a2  s  .c om
        int bytesRead;
        socketChannel = (SocketChannel) key.channel();

        final SocketChannelAttachment attachment = (SocketChannelAttachment) key.attachment();
        final ByteBuffer socketBuffer = attachment.getByteBuffer();

        // read until the buffer is full
        while ((bytesRead = socketChannel.read(socketBuffer)) > 0) {
            // prepare byte buffer for reading
            socketBuffer.flip();
            // mark the current position as start, in case of partial message read
            socketBuffer.mark();
            // process the contents that have been read into the buffer
            processBuffer(socketChannel, socketBuffer);

            // Preserve bytes in buffer for next call to run
            // NOTE: This code could benefit from the  two ByteBuffer read calls to avoid
            // this compact for higher throughput
            socketBuffer.reset();
            socketBuffer.compact();
            logger.debug("bytes read {}", new Object[] { bytesRead });
        }

        // Check for closed socket
        if (bytesRead < 0) {
            eof = true;
            logger.debug("Reached EOF, closing connection");
        } else {
            logger.debug("No more data available, returning for selection");
        }
    } catch (ClosedByInterruptException | InterruptedException e) {
        logger.debug("read loop interrupted, closing connection");
        // Treat same as closed socket
        eof = true;
    } catch (ClosedChannelException e) {
        // ClosedChannelException doesn't have a message so handle it separately from IOException
        logger.error("Error reading from channel due to channel being closed", e);
        // Treat same as closed socket
        eof = true;
    } catch (IOException e) {
        logger.error("Error reading from channel due to {}", new Object[] { e.getMessage() }, e);
        // Treat same as closed socket
        eof = true;
    } finally {
        if (eof == true) {
            IOUtils.closeQuietly(socketChannel);
            dispatcher.completeConnection(key);
        } else {
            dispatcher.addBackForSelection(key);
        }
    }
}

From source file:org.uberfire.io.CommonIOServiceDotFileTest.java

private String readSbc(SeekableByteChannel sbc) {
    ByteBuffer byteBuffer = ByteBuffer.allocate(100);
    StringBuilder content = new StringBuilder();
    byteBuffer.clear();//from  w  ww  .ja v  a 2  s. co  m
    try {
        while ((sbc.read(byteBuffer)) > 0) {
            byteBuffer.flip();
            content.append(new String(byteBuffer.array(), 0, byteBuffer.remaining()));
            byteBuffer.compact();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return content.toString();
}

From source file:net.timewalker.ffmq4.transport.tcp.nio.NIOTcpMultiplexer.java

protected boolean writeAndProcessChannelData(NIOClientSocketHandler clientHandler) {
    try {//from  w w w .j  a  v a 2  s.  com
        if (!clientHandler.appendOutgoingData())
            return false;

        ByteBuffer outputBuffer = clientHandler.getOutputBuffer();
        outputBuffer.flip(); // Prepare for reading
        int writeAmount;
        try {
            writeAmount = clientHandler.getSocketChannel().write(outputBuffer);
            if (writeAmount <= 0)
                log.debug("[" + clientHandler.getId() + "] Cannot write, channel socket was closed");
        } catch (IOException e) {
            log.error("[" + clientHandler.getId() + "] Write failed : " + e.getMessage());
            writeAmount = -1;
        }
        outputBuffer.compact(); // Restore pointers

        return (writeAmount > 0);
    } catch (Exception e) {
        log.error("[" + clientHandler.getId() + "] Could not process data", e);
        return false;
    }
}

From source file:org.celstec.arlearn2.upload.BlobStoreServlet.java

private BlobKey storeBlob(String contentType, String fileName, InputStream stream) throws IOException {
    FileService fileService = FileServiceFactory.getFileService();
    AppEngineFile file = fileService.createNewBlobFile(contentType, fileName);

    boolean lock = true;
    FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
    ByteBuffer buf = ByteBuffer.allocateDirect(10);

    byte[] bytes = new byte[1024];
    int count = 0;
    int index = 0;

    // Continue writing bytes until there are no more
    while (count >= 0) {
        if (index == count) {
            count = stream.read(bytes);//from   ww w. java  2 s .c o  m
            index = 0;
        }
        // Fill ByteBuffer
        while (index < count && buf.hasRemaining()) {
            buf.put(bytes[index++]);
        }

        // Set the limit to the current position and the
        // position to 0
        // making the new bytes visible for write()
        buf.flip();

        // Write the bytes to the channel
        int numWritten = writeChannel.write(buf);

        // Check if all bytes were written
        if (buf.hasRemaining()) {
            buf.compact();
        } else {
            buf.clear();
        }
    }

    writeChannel.closeFinally();
    return fileService.getBlobKey(file);
}

From source file:org.celstec.arlearn2.upload.BlobStoreServletIncremental.java

private AppEngineFile storeBlob(String contentType, String fileName, InputStream stream, boolean last,
        String serverPath) throws IOException {

    AppEngineFile file;/*w ww . j  av  a 2  s .c o m*/
    if (serverPath == null) {
        file = fileService.createNewBlobFile(contentType, fileName);
    } else {
        file = new AppEngineFile(serverPath);
    }

    //      boolean lock = true;
    log.warning("last is" + last + "file fullpath " + file.getFullPath());
    FileWriteChannel writeChannel = fileService.openWriteChannel(file, last);
    ByteBuffer buf = ByteBuffer.allocateDirect(10);

    byte[] bytes = new byte[1024];
    int count = 0;
    int index = 0;

    // Continue writing bytes until there are no more
    while (count >= 0) {
        if (index == count) {
            count = stream.read(bytes);
            index = 0;
        }
        // Fill ByteBuffer
        while (index < count && buf.hasRemaining()) {
            buf.put(bytes[index++]);
        }

        // Set the limit to the current position and the
        // position to 0
        // making the new bytes visible for write()
        buf.flip();

        // Write the bytes to the channel
        int numWritten = writeChannel.write(buf);

        // Check if all bytes were written
        if (buf.hasRemaining()) {
            buf.compact();
        } else {
            buf.clear();
        }
    }
    writeChannel.close();
    if (last)
        writeChannel.closeFinally();
    return file;
    //      return fileService.getBlobKey(file);
}

From source file:org.alfresco.contentstore.CassandraContentStore.java

private ByteBuffer getBlock(long globalBlockId) {
    ByteBuffer bb = null;

    ResultSet rs = cassandraSession.getCassandraSession().execute(getBlockStatement.bind(globalBlockId));
    Row row = rs.one();//from   www.ja v  a2s .c  o m
    if (row != null) {
        bb = row.getBytes("data");
        bb.compact();
        bb.flip();
    }

    return bb;
}

From source file:org.alfresco.contentstore.CassandraContentStore.java

private ByteBuffer getNodeBlock(Node node, long rangeId, int size) {
    ByteBuffer bb = null;

    String nodeId = node.getNodeId();
    long nodeVersion = node.getNodeVersion();
    MimeType mimeType = node.getMimeType();

    ResultSet rs = cassandraSession.getCassandraSession()
            .execute(getNodeBlockStatement.bind(nodeId, nodeVersion, mimeType.getMimetype(), rangeId));
    Row row = rs.one();//from  www . j  av a  2  s. c om
    if (row != null) {
        bb = row.getBytes("data");
        bb.compact();
        bb.flip();
        if (bb.limit() > size) {
            bb.limit(size);
        }
    }

    return bb;
}

From source file:net.kungfoo.grizzly.proxy.impl.ConnectingHandler.java

public void outputReady(final NHttpClientConnection conn, final ContentEncoder encoder) {
    System.out.println(conn + " [proxy->origin] output ready");

    HttpContext context = conn.getContext();
    ProxyProcessingInfo proxyTask = (ProxyProcessingInfo) context.getAttribute(ProxyProcessingInfo.ATTRIB);

    synchronized (proxyTask) {
        ConnState connState = proxyTask.getOriginState();
        if (connState != ConnState.REQUEST_SENT && connState != ConnState.REQUEST_BODY_STREAM) {
            throw new IllegalStateException("Illegal target connection state: " + connState);
        }// ww  w. j  a va  2  s.  co  m

        try {

            // TODO: propper handling of POST
            ByteBuffer src = proxyTask.getInBuffer();
            final int srcSize = src.limit();
            if (src.position() != 0) {
                System.out.println(conn + " [proxy->origin] buff not consumed yet");
                return;
            }
            ByteChunk chunk = new ByteChunk(srcSize);
            Request originalRequest = proxyTask.getOriginalRequest();
            int read;
            int encRead = 0;
            long bytesWritten = 0;
            while ((read = originalRequest.doRead(chunk)) != -1) {
                System.out.println(conn + " [proxy->origin] " + read + " bytes read");
                if (read > srcSize) {
                    src = ByteBuffer.wrap(chunk.getBytes(), chunk.getOffset(), read);
                } else {
                    src.put(chunk.getBytes(), chunk.getOffset(), read);
                }
                src.flip();
                encRead = encoder.write(src);
                bytesWritten += encRead;
                src.compact();
                chunk.reset();
                if (encRead == 0) {
                    System.out.println(conn + " [proxy->origin] encoder refused to consume more");
                    break;
                } else {
                    System.out.println(conn + " [proxy->origin] " + encRead + " consumed by encoder");
                }
            }
            System.out.println(conn + " [proxy->origin] " + bytesWritten + " bytes written");
            System.out.println(conn + " [proxy->origin] " + encoder);
            src.compact();

            if (src.position() == 0 && encRead != 0) {
                encoder.complete();
            }
            // Update connection state
            if (encoder.isCompleted()) {
                System.out.println(conn + " [proxy->origin] request body sent");
                proxyTask.setOriginState(ConnState.REQUEST_BODY_DONE);
            } else {
                proxyTask.setOriginState(ConnState.REQUEST_BODY_STREAM);
            }

        } catch (IOException ex) {
            shutdownConnection(conn);
        }
    }
}