Example usage for java.nio ByteBuffer allocateDirect

List of usage examples for java.nio ByteBuffer allocateDirect

Introduction

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

Prototype

public static ByteBuffer allocateDirect(int capacity) 

Source Link

Document

Creates a direct byte buffer based on a newly allocated memory block.

Usage

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  www  .  j  a  v a  2  s . co  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:com.intel.chimera.stream.AbstractCryptoStreamTest.java

private void doByteBufferRead(String cipherClass, boolean withChannel) throws Exception {
    // Default buffer size, initial buffer position is 0
    InputStream in = getCryptoInputStream(new ByteArrayInputStream(encData), getCipher(cipherClass),
            defaultBufferSize, iv, withChannel);
    ByteBuffer buf = ByteBuffer.allocate(dataLen + 100);
    byteBufferReadCheck(in, buf, 0);//from  w ww  . j a  va 2s .  c  o  m
    in.close();

    // Default buffer size, initial buffer position is not 0
    in = getCryptoInputStream(new ByteArrayInputStream(encData), getCipher(cipherClass), defaultBufferSize, iv,
            withChannel);
    buf.clear();
    byteBufferReadCheck(in, buf, 11);
    in.close();

    // Small buffer size, initial buffer position is 0
    in = getCryptoInputStream(new ByteArrayInputStream(encData), getCipher(cipherClass), smallBufferSize, iv,
            withChannel);
    buf.clear();
    byteBufferReadCheck(in, buf, 0);
    in.close();

    // Small buffer size, initial buffer position is not 0
    in = getCryptoInputStream(new ByteArrayInputStream(encData), getCipher(cipherClass), smallBufferSize, iv,
            withChannel);
    buf.clear();
    byteBufferReadCheck(in, buf, 11);
    in.close();

    // Direct buffer, default buffer size, initial buffer position is 0
    in = getCryptoInputStream(new ByteArrayInputStream(encData), getCipher(cipherClass), defaultBufferSize, iv,
            withChannel);
    buf = ByteBuffer.allocateDirect(dataLen + 100);
    byteBufferReadCheck(in, buf, 0);
    in.close();

    // Direct buffer, default buffer size, initial buffer position is not 0
    in = getCryptoInputStream(new ByteArrayInputStream(encData), getCipher(cipherClass), defaultBufferSize, iv,
            withChannel);
    buf.clear();
    byteBufferReadCheck(in, buf, 11);
    in.close();

    // Direct buffer, small buffer size, initial buffer position is 0
    in = getCryptoInputStream(new ByteArrayInputStream(encData), getCipher(cipherClass), smallBufferSize, iv,
            withChannel);
    buf.clear();
    byteBufferReadCheck(in, buf, 0);
    in.close();

    // Direct buffer, small buffer size, initial buffer position is not 0
    in = getCryptoInputStream(new ByteArrayInputStream(encData), getCipher(cipherClass), smallBufferSize, iv,
            withChannel);
    buf.clear();
    byteBufferReadCheck(in, buf, 11);
    in.close();
}

From source file:GeometryByReferenceNIOBuffer.java

void createJ3DBuffers() {
    int i;//w w  w  .j  a v a2s .  c o m
    ByteOrder order = ByteOrder.nativeOrder();

    FloatBuffer coord = ByteBuffer.allocateDirect(36 * 4).order(order).asFloatBuffer();
    coord.put(floatVerts, 0, 36);
    floatBufferCoord = new J3DBuffer(coord);

    FloatBuffer color = ByteBuffer.allocateDirect(36 * 4).order(order).asFloatBuffer();
    color.put(floatClrs, 0, 36);
    floatBufferColor = new J3DBuffer(color);

    FloatBuffer indexedCoord = ByteBuffer.allocateDirect(12 * 4).order(order).asFloatBuffer();
    indexedCoord.put(indexedFloatVerts, 0, 12);
    indexedFloatBufferCoord = new J3DBuffer(indexedCoord);

    FloatBuffer indexedColor = ByteBuffer.allocateDirect(12 * 4).order(order).asFloatBuffer();
    indexedColor.put(indexedFloatClrs, 0, 12);
    indexedFloatBufferColor = new J3DBuffer(indexedColor);
}

From source file:org.apache.hadoop.util.NativeStair.java

private static ByteBuffer directify(byte[] readBufs, int dataStart, int dataLen) {
    //LOG.info("directify starts: " + System.nanoTime());
    ByteBuffer newBuf = null;//from   w  w  w.  j av a 2s.c  om
    newBuf = ByteBuffer.allocateDirect(dataLen);
    newBuf.position(0);
    newBuf.mark();
    newBuf.put(readBufs, dataStart, dataLen);
    newBuf.reset();
    newBuf.limit(dataLen);
    //LOG.info("directify ends: " + System.nanoTime());
    return newBuf;
}

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;//from w  w  w  .  j  a v a  2s. c om
    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:net.lightbody.bmp.proxy.jetty.http.nio.ByteBufferInputStream.java

/** Get a buffer to write to this InputStream.
 * The buffer wll either be a new direct buffer or a recycled buffer.
 *//*from  w  ww .j  a va2 s. com*/
public synchronized ByteBuffer getBuffer() {
    ByteBuffer buf = null;
    int s = LazyList.size(_recycle);
    if (s > 0) {
        s--;
        buf = (ByteBuffer) LazyList.get(_recycle, s);
        _recycle = LazyList.remove(_recycle, s);
        buf.clear();
    } else {
        buf = ByteBuffer.allocateDirect(_bufferSize);
    }
    return buf;
}

From source file:com.tinspx.util.io.ChannelSourceTest.java

@Test
public void testMemoizeSource() throws IOException {
    ByteSource source = of(ByteBuffer.allocate(16));
    assertSame(source, ChannelSource.memoize(source));

    source = of(new byte[16]);
    assertSame(source, ChannelSource.memoize(source));

    source = memoize(ByteSource.empty());
    assertSame(source, source);// w  w  w.  j a  va 2s.  co m

    source = memoize(ByteSourceTests.force(of(INPUT)));
    assertTrue(source instanceof ChannelSource.MemoizeChannelSource);
    ByteSourceTests.testByteSource(source, INPUT);

    source = memoize(ByteSourceTests.force(of(ByteBuffer.wrap(INPUT))));
    assertTrue(source instanceof ChannelSource.MemoizeChannelSource);
    ByteSourceTests.testByteSource(source, INPUT);

    source = memoize(ByteSourceTests.force(of(ByteBuffer.wrap(INPUT).asReadOnlyBuffer())));
    assertTrue(source instanceof ChannelSource.MemoizeChannelSource);
    ByteSourceTests.testByteSource(source, INPUT);

    ByteBuffer direct = ByteBuffer.allocateDirect(INPUT.length);
    assertTrue(direct.isDirect());
    direct.put(INPUT).flip();
    source = memoize(ByteSourceTests.force(of(direct)));
    assertTrue(source instanceof ChannelSource.MemoizeChannelSource);
    ByteSourceTests.testByteSource(source, INPUT);

    source = memoize(new BAOutputStream(INPUT, INPUT.length).asByteSource());
    assertTrue(source instanceof ChannelSource.MemoizeChannelSource);
    ByteSourceTests.testByteSource(source, INPUT);

    source = memoize(new ByteSourceTests.ForcedByteArray(INPUT));
    assertTrue(source instanceof ChannelSource.MemoizeChannelSource);
    ByteSourceTests.testByteSource(source, INPUT);

    source = memoize(ByteSource.wrap(INPUT));
    assertTrue(source instanceof ChannelSource.MemoizeChannelSource);
    ByteSourceTests.testByteSource(source, INPUT);

    ByteSourceTests.assertEmpty(memoize(ByteSource.empty()));
    ByteSourceTests.assertEmpty(memoize(ChannelSource.empty()));
}

From source file:com.ibm.crail.tools.CrailBenchmark.java

void writeAsync(String filename, int size, int loop, int batch, int storageClass, int locationClass)
        throws Exception {
    System.out.println("writeAsync, filename " + filename + ", size " + size + ", loop " + loop + ", batch "
            + batch + ", storageClass " + storageClass + ", locationClass " + locationClass);

    ConcurrentLinkedQueue<CrailBuffer> bufferQueue = new ConcurrentLinkedQueue<CrailBuffer>();
    for (int i = 0; i < batch; i++) {
        CrailBuffer buf = null;//from   w  w  w.j  a  v  a2  s.  c  o  m
        if (size == CrailConstants.BUFFER_SIZE) {
            buf = fs.allocateBuffer();
        } else if (size < CrailConstants.BUFFER_SIZE) {
            CrailBuffer _buf = fs.allocateBuffer();
            _buf.clear().limit(size);
            buf = _buf.slice();
        } else {
            buf = OffHeapBuffer.wrap(ByteBuffer.allocateDirect(size));
        }
        bufferQueue.add(buf);
    }

    //warmup
    warmUp(filename, warmup, bufferQueue);

    //benchmark
    System.out.println("starting benchmark...");
    LinkedBlockingQueue<Future<CrailResult>> futureQueue = new LinkedBlockingQueue<Future<CrailResult>>();
    HashMap<Integer, CrailBuffer> futureMap = new HashMap<Integer, CrailBuffer>();
    fs.getStatistics().reset();
    long _loop = (long) loop;
    long _bufsize = (long) CrailConstants.BUFFER_SIZE;
    long _capacity = _loop * _bufsize;
    double sumbytes = 0;
    double ops = 0;
    CrailFile file = fs.create(filename, CrailNodeType.DATAFILE, CrailStorageClass.get(storageClass),
            CrailLocationClass.get(locationClass)).get().asFile();
    CrailOutputStream directStream = file.getDirectOutputStream(_capacity);
    long start = System.currentTimeMillis();
    for (int i = 0; i < batch - 1 && ops < loop; i++) {
        CrailBuffer buf = bufferQueue.poll();
        buf.clear();
        Future<CrailResult> future = directStream.write(buf);
        futureQueue.add(future);
        futureMap.put(future.hashCode(), buf);
        ops = ops + 1.0;
    }
    while (ops < loop) {
        CrailBuffer buf = bufferQueue.poll();
        buf.clear();
        Future<CrailResult> future = directStream.write(buf);
        futureQueue.add(future);
        futureMap.put(future.hashCode(), buf);

        future = futureQueue.poll();
        future.get();
        buf = futureMap.get(future.hashCode());
        bufferQueue.add(buf);

        sumbytes = sumbytes + buf.capacity();
        ops = ops + 1.0;
    }
    while (!futureQueue.isEmpty()) {
        Future<CrailResult> future = futureQueue.poll();
        future.get();
        CrailBuffer buf = futureMap.get(future.hashCode());
        sumbytes = sumbytes + buf.capacity();
        ops = ops + 1.0;
    }
    long end = System.currentTimeMillis();
    double executionTime = ((double) (end - start)) / 1000.0;
    double throughput = 0.0;
    double latency = 0.0;
    double sumbits = sumbytes * 8.0;
    if (executionTime > 0) {
        throughput = sumbits / executionTime / 1000.0 / 1000.0;
        latency = 1000000.0 * executionTime / ops;
    }
    directStream.close();

    System.out.println("execution time " + executionTime);
    System.out.println("ops " + ops);
    System.out.println("sumbytes " + sumbytes);
    System.out.println("throughput " + throughput);
    System.out.println("latency " + latency);

    fs.getStatistics().print("close");
}

From source file:esg.node.components.monitoring.InfoResources.java

InfoResources(String filename, int buffSize_) {
    this.filename = filename;
    this.buffSize = buffSize_;
    System.out.println("InfoResource initializing for " + filename);
    try {/*from  w w  w  .  j  av  a  2 s.c o  m*/
        File procFile = new File(filename);
        if (buffSize < 0) {
            buffSize = (int) procFile.length();
            if (buffSize == 0) {
                buffSize = guestimateSize;
            }
        }
        raf = new RandomAccessFile(procFile, "r");
        fc = raf.getChannel();
        bb = ByteBuffer.allocateDirect(buffSize);

        Charset cs = Charset.forName("8859_1");
        decoder = cs.newDecoder();
        cb = CharBuffer.allocate(buffSize);

        System.out.println("Buffer Size is " + buffSize + " number of bytes");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.example.ex_templete.TouchRotateFragment.java

public Cube() {
    int one = 0x10000;
    int vertices[] = { -one, -one, -one, one, -one, -one, one, one, -one, -one, one, -one, -one, -one, one, one,
            -one, one, one, one, one, -one, one, one, };

    int colors[] = { 0, 0, 0, one, one, 0, 0, one, one, one, 0, one, 0, one, 0, one, 0, 0, one, one, one, 0,
            one, one, one, one, one, one, 0, one, one, one, };

    byte indices[] = { 0, 4, 5, 0, 5, 1, 1, 5, 6, 1, 6, 2, 2, 6, 7, 2, 7, 3, 3, 7, 4, 3, 4, 0, 4, 7, 6, 4, 6, 5,
            3, 0, 1, 3, 1, 2 };//from   w w w  .j av  a 2  s. co m

    // Buffers to be passed to gl*Pointer() functions
    // must be direct, i.e., they must be placed on the
    // native heap where the garbage collector cannot
    // move them.
    //
    // Buffers with multi-byte datatypes (e.g., short, int, float)
    // must have their byte order set to native order

    ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
    vbb.order(ByteOrder.nativeOrder());
    mVertexBuffer = vbb.asIntBuffer();
    mVertexBuffer.put(vertices);
    mVertexBuffer.position(0);

    ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * 4);
    cbb.order(ByteOrder.nativeOrder());
    mColorBuffer = cbb.asIntBuffer();
    mColorBuffer.put(colors);
    mColorBuffer.position(0);

    mIndexBuffer = ByteBuffer.allocateDirect(indices.length);
    mIndexBuffer.put(indices);
    mIndexBuffer.position(0);
}