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 abstract byte get(int index);

Source Link

Document

Returns the byte at the specified index and does not change the position.

Usage

From source file:com.chicm.cmraft.rpc.PacketUtils.java

public static RpcCall parseRpcRequestFromChannel(AsynchronousSocketChannel channel, BlockingService service)
        throws InterruptedException, ExecutionException, IOException {
    RpcCall call = null;/*from www.  j a v a  2  s  .  com*/
    long t = System.currentTimeMillis();
    InputStream in = Channels.newInputStream(channel);
    byte[] datasize = new byte[MESSAGE_LENGHT_FIELD_SIZE];
    in.read(datasize);
    int nDataSize = bytes2Int(datasize);

    int len = 0;
    ByteBuffer buf = ByteBuffer.allocateDirect(nDataSize);
    for (; len < nDataSize;) {
        len += channel.read(buf).get();
    }
    if (len < nDataSize) {
        LOG.error("SOCKET READ FAILED, len:" + len);
        return call;
    }
    byte[] data = new byte[nDataSize];
    buf.flip();
    buf.get(data);
    int offset = 0;
    CodedInputStream cis = CodedInputStream.newInstance(data, offset, nDataSize - offset);
    int headerSize = cis.readRawVarint32();
    offset += cis.getTotalBytesRead();
    RequestHeader header = RequestHeader.newBuilder().mergeFrom(data, offset, headerSize).build();

    offset += headerSize;
    cis.skipRawBytes(headerSize);
    cis.resetSizeCounter();
    int bodySize = cis.readRawVarint32();
    offset += cis.getTotalBytesRead();
    //LOG.debug("header parsed:" + header.toString());

    MethodDescriptor md = service.getDescriptorForType().findMethodByName(header.getRequestName());
    Builder builder = service.getRequestPrototype(md).newBuilderForType();
    Message body = null;
    if (builder != null) {
        body = builder.mergeFrom(data, offset, bodySize).build();
        //LOG.debug("server : request parsed:" + body.toString());
    }
    call = new RpcCall(header.getId(), header, body, md);
    if (LOG.isTraceEnabled()) {
        LOG.trace("Parse Rpc request from socket: " + call.getCallId() + ", takes"
                + (System.currentTimeMillis() - t) + " ms");
    }

    return call;
}

From source file:com.chicm.cmraft.rpc.PacketUtils.java

public static RpcCall parseRpcResponseFromChannel(AsynchronousSocketChannel channel, BlockingService service)
        throws InterruptedException, ExecutionException, IOException {
    RpcCall call = null;/*from  www . ja va2s .co  m*/
    long t = System.currentTimeMillis();
    InputStream in = Channels.newInputStream(channel);
    byte[] datasize = new byte[MESSAGE_LENGHT_FIELD_SIZE];
    in.read(datasize);
    int nDataSize = bytes2Int(datasize);

    LOG.debug("message size: " + nDataSize);

    int len = 0;
    ByteBuffer buf = ByteBuffer.allocateDirect(nDataSize);
    for (; len < nDataSize;) {
        len += channel.read(buf).get();
    }
    if (len < nDataSize) {
        LOG.error("SOCKET READ FAILED, len:" + len);
        return call;
    }
    byte[] data = new byte[nDataSize];
    buf.flip();
    buf.get(data);
    int offset = 0;
    CodedInputStream cis = CodedInputStream.newInstance(data, offset, nDataSize - offset);
    int headerSize = cis.readRawVarint32();
    offset += cis.getTotalBytesRead();
    ResponseHeader header = ResponseHeader.newBuilder().mergeFrom(data, offset, headerSize).build();

    offset += headerSize;
    cis.skipRawBytes(headerSize);
    cis.resetSizeCounter();
    int bodySize = cis.readRawVarint32();
    offset += cis.getTotalBytesRead();

    MethodDescriptor md = service.getDescriptorForType().findMethodByName(header.getResponseName());
    Builder builder = service.getResponsePrototype(md).newBuilderForType();
    Message body = null;
    if (builder != null) {
        body = builder.mergeFrom(data, offset, bodySize).build();
    }
    call = new RpcCall(header.getId(), header, body, md);
    if (LOG.isTraceEnabled()) {
        LOG.trace("Parse Rpc response from socket: " + call.getCallId() + ", takes"
                + (System.currentTimeMillis() - t) + " ms");
    }

    return call;
}

From source file:com.googlecode.mp4parser.boxes.microsoft.XtraBox.java

private static String readAsciiString(ByteBuffer content, int length) {
    byte s[] = new byte[length];
    content.get(s);
    try {/*from  w ww . j ava  2  s . co  m*/
        return new String(s, "US-ASCII");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("Shouldn't happen", e);
    }
}

From source file:de.csdev.ebus.utils.EBusUtils.java

/**
 * Generates a string hex dump from a ByteBuffer
 *
 * @param data The source/*w  w  w  .java  2 s.co m*/
 * @return The StringBuilder with hex dump
 */
static public StringBuilder toHexDumpString(ByteBuffer data) {

    int size = 0;
    if (data.position() == 0) {
        size = data.limit();
    } else {
        size = data.position();
    }

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < size; i++) {
        byte c = data.get(i);
        if (i > 0) {
            sb.append(' ');
        }
        sb.append(toHexDumpString(c));
    }
    return sb;
}

From source file:jsave.Utils.java

/**
 * Returns an unsigned byte.//from w  ww . j a  v a2  s . c o m
 * 
 * Since java does not provide unsigned primitive types, each unsigned
 * value read from the buffer is promoted up to the next bigger primitive
 * data type : getUnsignedByte() returns a short.     
 *
 * @param bb the array of bytes in the buffer
 * @return an unsigned byte as short
 */
public static short getUnsignedByte(ByteBuffer bb) {
    return ((short) (bb.get(0) & 0xff));
}

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

/**
 * ByteBuffer??/*  w  w  w  .jav a2  s .  c  o m*/
 * @param buffer
 * @return
 */
public static Packet unmarshall(ByteBuffer buffer) {
    if (buffer.remaining() < getHeaderSize()) {
        throw new RuntimeException("Wrong packet.");
    }

    Packet packet = new Packet();
    byte[] str = new byte[NetWorkConstants.WAVERIDER_MAGIC.getBytes().length];
    buffer.get(str);
    packet.setMagic(new String(str));

    if (!NetWorkConstants.WAVERIDER_MAGIC.equals(packet.getMagic())) {
        throw new RuntimeException("Wrong packet.");
    }

    packet.setSequence(buffer.getLong());
    packet.setType(buffer.getLong());
    packet.setLength(buffer.getInt());
    packet.setPayLoad(buffer.slice());
    return packet;
}

From source file:net.servicestack.client.Utils.java

public static UUID fromGuidBytes(byte[] guidBytes) {
    ByteBuffer buf = ByteBuffer.wrap(guidBytes);

    byte[] first4 = new byte[4];
    buf.get(first4);
    reverse(first4);//from  w ww .j  a v  a 2s  .  c  o  m

    byte[] second2 = new byte[2];
    buf.get(second2);
    reverse(second2);

    byte[] third2 = new byte[2];
    buf.get(third2);
    reverse(third2);

    long lsb = buf.getLong();

    buf = ByteBuffer.wrap(new byte[8]).put(first4).put(second2).put(third2);

    buf.rewind();
    long msb = buf.getLong();

    return new UUID(msb, lsb);
}

From source file:com.unister.semweb.drums.TestUtils.java

/**
 * Reads from the given numbe of elements (<code>numberOfElementsToRead</code>) from the given file from the
 * beginning./*from w w  w . j  a  va  2  s . c om*/
 */
public static List<DummyKVStorable> readFrom(String filename, int numberOfElementsToRead) throws Exception {
    HeaderIndexFile<DummyKVStorable> file = new HeaderIndexFile<DummyKVStorable>(filename, AccessMode.READ_ONLY,
            1, TestUtils.gp);
    ByteBuffer dataBuffer = ByteBuffer.allocate(numberOfElementsToRead * TestUtils.gp.getElementSize());
    file.read(0, dataBuffer);
    dataBuffer.flip();

    List<DummyKVStorable> readData = new ArrayList<DummyKVStorable>();
    while (dataBuffer.position() < dataBuffer.limit()) {
        byte[] oneLinkData = new byte[TestUtils.gp.getElementSize()];
        dataBuffer.get(oneLinkData);
        DummyKVStorable oneDate = TestUtils.gp.getPrototype().fromByteBuffer(ByteBuffer.wrap(oneLinkData));
        readData.add(oneDate);
    }
    file.close();
    return readData;
}

From source file:com.google.flatbuffers.Table.java

/**
 * Check if a {@link ByteBuffer} contains a file identifier.
 *
 * @param bb A {@code ByteBuffer} to check if it contains the identifier
 * `ident`./* w w  w  . j  ava2  s .com*/
 * @param ident A `String` identifier of the FlatBuffer file.
 * @return True if the buffer contains the file identifier
 */
protected static boolean __has_identifier(ByteBuffer bb, String ident) {
    if (ident.length() != FILE_IDENTIFIER_LENGTH)
        throw new AssertionError("FlatBuffers: file identifier must be length " + FILE_IDENTIFIER_LENGTH);
    for (int i = 0; i < FILE_IDENTIFIER_LENGTH; i++) {
        if (ident.charAt(i) != (char) bb.get(bb.position() + SIZEOF_INT + i))
            return false;
    }
    return true;
}

From source file:com.linkedin.pinot.perf.ForwardIndexReaderBenchmark.java

public static void multiValuedReadBenchMarkV1(File file, int numDocs, int totalNumValues, int maxEntriesPerDoc,
        int columnSizeInBits) throws Exception {
    System.out.println("******************************************************************");
    System.out.println("Analyzing " + file.getName() + " numDocs:" + numDocs + ", totalNumValues:"
            + totalNumValues + ", maxEntriesPerDoc:" + maxEntriesPerDoc + ", numBits:" + columnSizeInBits);
    long start, end;
    boolean readFile = true;
    boolean randomRead = true;
    boolean contextualRead = true;
    boolean signed = false;
    boolean isMmap = false;
    PinotDataBuffer heapBuffer = PinotDataBuffer.fromFile(file, ReadMode.mmap, FileChannel.MapMode.READ_ONLY,
            "benchmarking");
    BaseSingleColumnMultiValueReader reader = new com.linkedin.pinot.core.io.reader.impl.v1.FixedBitMultiValueReader(
            heapBuffer, numDocs, totalNumValues, columnSizeInBits, signed);

    int[] intArray = new int[maxEntriesPerDoc];
    File outfile = new File("/tmp/" + file.getName() + ".raw");
    FileWriter fw = new FileWriter(outfile);
    for (int i = 0; i < numDocs; i++) {
        int length = reader.getIntArray(i, intArray);
        StringBuilder sb = new StringBuilder();
        String delim = "";
        for (int j = 0; j < length; j++) {
            sb.append(delim);/*  w  ww  . ja va2 s.c om*/
            sb.append(intArray[j]);
            delim = ",";
        }
        fw.write(sb.toString());
        fw.write("\n");
    }
    fw.close();

    // sequential read
    if (readFile) {
        DescriptiveStatistics stats = new DescriptiveStatistics();
        RandomAccessFile raf = new RandomAccessFile(file, "rw");
        ByteBuffer buffer = ByteBuffer.allocateDirect((int) file.length());
        raf.getChannel().read(buffer);
        for (int run = 0; run < MAX_RUNS; run++) {
            long length = file.length();
            start = System.currentTimeMillis();
            for (int i = 0; i < length; i++) {
                byte b = buffer.get(i);
            }
            end = System.currentTimeMillis();
            stats.addValue((end - start));
        }
        System.out.println("v1 multi value read bytes stats for " + file.getName());
        System.out.println(
                stats.toString().replaceAll("\n", ", ") + " raw:" + Arrays.toString(stats.getValues()));

        raf.close();
    }
    if (randomRead) {
        DescriptiveStatistics stats = new DescriptiveStatistics();
        for (int run = 0; run < MAX_RUNS; run++) {
            start = System.currentTimeMillis();
            for (int i = 0; i < numDocs; i++) {
                int length = reader.getIntArray(i, intArray);
            }
            end = System.currentTimeMillis();
            stats.addValue((end - start));
        }
        System.out.println("v1 multi value sequential read one stats for " + file.getName());
        System.out.println(
                stats.toString().replaceAll("\n", ", ") + " raw:" + Arrays.toString(stats.getValues()));
    }

    if (contextualRead) {
        DescriptiveStatistics stats = new DescriptiveStatistics();
        for (int run = 0; run < MAX_RUNS; run++) {
            MultiValueReaderContext context = (MultiValueReaderContext) reader.createContext();
            start = System.currentTimeMillis();
            for (int i = 0; i < numDocs; i++) {
                int length = reader.getIntArray(i, intArray, context);
            }
            end = System.currentTimeMillis();
            // System.out.println("RUN:" + run + "Time:" + (end-start));
            stats.addValue((end - start));
        }
        System.out.println("v1 multi value sequential read one with context stats for " + file.getName());
        System.out.println(
                stats.toString().replaceAll("\n", ", ") + " raw:" + Arrays.toString(stats.getValues()));

    }
    reader.close();
    heapBuffer.close();
    System.out.println("******************************************************************");

}