Example usage for java.nio ByteBuffer get

List of usage examples for java.nio ByteBuffer get

Introduction

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

Prototype

public ByteBuffer get(byte[] dest, int off, int len) 

Source Link

Document

Reads bytes from the current position into the specified byte array, starting at the specified offset, and increases the position by the number of bytes read.

Usage

From source file:com.facebook.infrastructure.net.UdpConnection.java

private byte[] gobbleHeaderAndExtractBody(ByteBuffer buffer) {
    byte[] body = ArrayUtils.EMPTY_BYTE_ARRAY;
    byte[] protocol = new byte[4];
    buffer = buffer.get(protocol, 0, protocol.length);
    int value = BasicUtilities.byteArrayToInt(protocol);

    if (protocol_ != value) {
        logger_.info("Invalid protocol header in the incoming message " + value);
        return body;
    }/*from   www . j a  v a 2  s.com*/
    body = new byte[buffer.remaining()];
    buffer.get(body, 0, body.length);
    return body;
}

From source file:com.ery.ertc.estorm.util.ByteBufferArray.java

/**
 * Transfers bytes from this buffer array into the given destination array
 * /*from  www .  j a v a 2s.c  om*/
 * @param start
 *            start offset of this buffer array
 * @param len
 *            The maximum number of bytes to be written to the given array
 * @param dstArray
 *            The array into which bytes are to be written
 * @param dstOffset
 *            The offset within the given array of the first byte to be written
 */
public void getMultiple(long start, int len, byte[] dstArray, int dstOffset) {
    multiple(start, len, dstArray, dstOffset, new Visitor() {
        public void visit(ByteBuffer bb, byte[] array, int arrayIdx, int len) {
            bb.get(array, arrayIdx, len);
        }
    });
}

From source file:com.n0n3m4.q3e.Q3ECallbackObj.java

public void writeAudio(ByteBuffer audioData, int offset, int len) {
    if (mAudioTrack == null)
        return;//from   w w w  .  j a  v a2 s.c om
    audioData.position(offset);
    audioData.get(mAudioData, 0, len);
    if (sync++ % 128 == 0)
        mAudioTrack.flush();
    mAudioTrack.write(mAudioData, 0, len);
}

From source file:com.openteach.diamond.network.waverider.network.Packet.java

/**
 * ??Packet, ??//  ww  w . j a  v  a 2  s. c om
 * @param inputBuffer
 * @return
 * @throws IOException, InterruptedException
 */
public static Packet parse(BlockingQueue<ByteBuffer> inputBuffer, NetWorkEndPoint endPoint,
        SocketChannel channel) throws IOException, InterruptedException {
    // Buffer for packet header
    byte[] tmpBuf = new byte[NetWorkConstants.DEFAULT_NETWORK_BUFFER_SIZE];
    ByteBuffer header = ByteBuffer.allocate(Packet.getHeaderSize());
    ByteBuffer currentBuffer = null;
    int rest = 0;
    boolean isRemove = false;

    // ?
    while (true) {
        while ((currentBuffer = inputBuffer.peek()) == null) {
            if (!endPoint.notifyRead(channel)) {
                throw new IOException("Socket closed by other thread");
            }
            // ?
            //endPoint.waitMoreData(5);
            // FIXME 2ms
            //Thread.sleep(1);
            Thread.yield();
        }
        isRemove = false;
        rest = header.capacity() - header.position();
        if (currentBuffer.remaining() >= rest) {
            if (currentBuffer.remaining() == rest) {
                isRemove = true;
            }
            currentBuffer.get(tmpBuf, 0, rest);
            header.put(tmpBuf, 0, rest);
            if (isRemove) {
                inputBuffer.remove();
            }
            break;
        } else {
            header.put(currentBuffer);
            inputBuffer.remove();
        }
    }

    header.flip();

    // , ???

    // ?
    Integer size = header.getInt(Packet.getLengthPosition());
    // For test
    /*if(size < 0 || size > 100000) {
       logger.info("Error");
    }*/
    //logger.debug(new StringBuilder("Try to allocate ").append(size).append(" bytes memory"));
    ByteBuffer buffer = ByteBuffer.allocate(size);
    buffer.put(header);
    header.clear();

    // ?
    while (true) {
        while ((currentBuffer = inputBuffer.peek()) == null) {
            endPoint.notifyRead(channel);
            Thread.sleep(1000);
        }
        isRemove = false;
        rest = buffer.capacity() - buffer.position();
        if (currentBuffer.remaining() >= rest) {
            if (currentBuffer.remaining() == rest) {
                isRemove = true;
            }
            currentBuffer.get(tmpBuf, 0, rest);
            buffer.put(tmpBuf, 0, rest);
            if (isRemove) {
                inputBuffer.remove();
            }
            break;
        } else {
            buffer.put(currentBuffer);
            inputBuffer.remove();
        }
    }
    //buffer.position(0);
    buffer.flip();
    Packet packet = Packet.unmarshall(buffer);
    //logger.info("Parse one packet from network");
    //packet.dump();
    return packet;
}

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

/**
 * @throws DataFormatException is data in the byte buffer is incorrect and cannot be decoded
 *//*from   www.  j a  v a2 s. c  om*/
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);
}

From source file:com.serenegiant.media.TLMediaEncoder.java

/**
 * write raw bit stream into specific intermediate file
 * @param out//from ww  w .j  a v  a2s.  c  o  m
 * @param sequence
 * @param frame_number
 * @param info
 * @param buffer
 * @param writeBuffer
 * @throws IOException
 */
private static final void writeStream(final DataOutputStream out, final int sequence, final int frame_number,
        final MediaCodec.BufferInfo info, final ByteBuffer buffer, byte[] writeBuffer) throws IOException {

    if (writeBuffer.length < info.size) {
        writeBuffer = new byte[info.size];
    }
    buffer.position(info.offset);
    buffer.get(writeBuffer, 0, info.size);
    try {
        writeHeader(out, sequence, frame_number, info.presentationTimeUs, info.size, info.flags);
        out.write(writeBuffer, 0, info.size);
    } catch (IOException e) {
        if (DEBUG)
            Log.e(TAG_STATIC, "writeStream:", e);
        throw e;
    }
}

From source file:net.librec.data.convertor.appender.SocialDataAppender.java

/**
 * Read data from the data file. Note that we didn't take care of the
 * duplicated lines./*from  w  ww .  ja v a 2 s .  c  o m*/
 *
 * @param inputDataPath
 *            the path of the data file
 * @throws IOException if I/O error occurs during reading
 */
private void readData(String inputDataPath) throws IOException {
    // Table {row-id, col-id, rate}
    Table<Integer, Integer, Double> dataTable = HashBasedTable.create();
    // Map {col-id, multiple row-id}: used to fast build a rating matrix
    Multimap<Integer, Integer> colMap = HashMultimap.create();
    // BiMap {raw id, inner id} userIds, itemIds
    final List<File> files = new ArrayList<File>();
    final ArrayList<Long> fileSizeList = new ArrayList<Long>();
    SimpleFileVisitor<Path> finder = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            fileSizeList.add(file.toFile().length());
            files.add(file.toFile());
            return super.visitFile(file, attrs);
        }
    };
    Files.walkFileTree(Paths.get(inputDataPath), finder);
    long allFileSize = 0;
    for (Long everyFileSize : fileSizeList) {
        allFileSize = allFileSize + everyFileSize.longValue();
    }
    // loop every dataFile collecting from walkFileTree
    for (File dataFile : files) {
        FileInputStream fis = new FileInputStream(dataFile);
        FileChannel fileRead = fis.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
        int len;
        String bufferLine = new String();
        byte[] bytes = new byte[BSIZE];
        while ((len = fileRead.read(buffer)) != -1) {
            buffer.flip();
            buffer.get(bytes, 0, len);
            bufferLine = bufferLine.concat(new String(bytes, 0, len)).replaceAll("\r", "\n");
            String[] bufferData = bufferLine.split("(\n)+");
            boolean isComplete = bufferLine.endsWith("\n");
            int loopLength = isComplete ? bufferData.length : bufferData.length - 1;
            for (int i = 0; i < loopLength; i++) {
                String line = new String(bufferData[i]);
                String[] data = line.trim().split("[ \t,]+");
                String userA = data[0];
                String userB = data[1];
                Double rate = (data.length >= 3) ? Double.valueOf(data[2]) : 1.0;
                if (userIds.containsKey(userA) && userIds.containsKey(userB)) {
                    int row = userIds.get(userA);
                    int col = userIds.get(userB);
                    dataTable.put(row, col, rate);
                    colMap.put(col, row);
                }
            }
            if (!isComplete) {
                bufferLine = bufferData[bufferData.length - 1];
            }
            buffer.clear();
        }
        fileRead.close();
        fis.close();
    }
    int numRows = userIds.size(), numCols = userIds.size();
    // build rating matrix
    userSocialMatrix = new SparseMatrix(numRows, numCols, dataTable, colMap);
    // release memory of data table
    dataTable = null;
}

From source file:com.mycustomloader.vsamloader.VSAMLoader.java

private void readField(ByteBuffer buf, int fieldID) {
    if (mRequiredColumns == null || (mRequiredColumns.length > fieldID && mRequiredColumns[fieldID])) {
        byte[] bytes = new byte[buf.position()];
        buf.rewind();//from   w ww .j av  a 2s  .c  o  m
        buf.get(bytes, 0, bytes.length);
        mProtoTuple.add(new DataByteArray(bytes));
    }
    buf.clear();
}

From source file:com.serenegiant.media.TLMediaEncoder.java

/**
 * convert ByteBuffer into String/*from w w w. ja  va 2  s  .c  o  m*/
 * @param buffer
 * @return
 */
private static final String asString(final ByteBuffer buffer) {
    final byte[] temp = new byte[16];
    final StringBuilder sb = new StringBuilder();
    int n = (buffer != null ? buffer.limit() : 0);
    if (n > 0) {
        buffer.rewind();
        int sz = (n > 16 ? 16 : n);
        n -= sz;
        for (; sz > 0; sz = (n > 16 ? 16 : n), n -= sz) {
            buffer.get(temp, 0, sz);
            for (int i = 0; i < sz; i++) {
                sb.append(temp[i]).append(',');
            }
        }
    }
    return sb.toString();
}

From source file:com.github.mrstampy.gameboot.otp.websocket.OtpEncryptedWebSocketHandler.java

private byte[] extractArray(WebSocketSession session, BinaryMessage message) throws IOException {
    ByteBuffer buf = message.getPayload();

    if (buf.hasArray())
        return buf.array();

    int size = buf.remaining();

    if (size == 0) {
        log.error("No message, closing session {}", session);
        session.close();//w w  w  .jav a  2 s  . com
        return null;
    }

    byte[] b = new byte[size];

    buf.get(b, 0, b.length);

    return b;
}