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:io.undertow.server.WriteTimeoutTestCase.java

@Test
public void testWriteTimeout() throws IOException, InterruptedException {
    DefaultServer.setRootHandler(new HttpHandler() {
        @Override// w  w  w .  java  2 s . c  o m
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            final StreamSinkChannel response = exchange.getResponseChannel();
            try {
                response.setOption(Options.WRITE_TIMEOUT, 10);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            final int capacity = 1 * 1024 * 1024; //1mb

            final ByteBuffer originalBuffer = ByteBuffer.allocateDirect(capacity);
            for (int i = 0; i < capacity; ++i) {
                originalBuffer.put((byte) '*');
            }
            originalBuffer.flip();
            response.getWriteSetter().set(new ChannelListener<Channel>() {

                private ByteBuffer buffer = originalBuffer.duplicate();
                int count = 0;

                @Override
                public void handleEvent(final Channel channel) {
                    do {
                        try {
                            int res = response.write(buffer);
                            if (res == 0) {
                                return;
                            }
                        } catch (IOException e) {
                            exception = e;
                            errorLatch.countDown();
                        }
                        if (!buffer.hasRemaining()) {
                            count++;
                            buffer = originalBuffer.duplicate();
                        }
                    } while (count < 1000);
                    exchange.endExchange();
                }
            });
            response.wakeupWrites();
        }
    });

    final TestHttpClient client = new TestHttpClient();
    try {
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL());
        try {
            HttpResponse result = client.execute(get);
            InputStream content = result.getEntity().getContent();
            byte[] buffer = new byte[512];
            int r = 0;
            while ((r = content.read(buffer)) > 0) {
                Thread.sleep(200);
                if (exception != null) {
                    Assert.assertEquals(WriteTimeoutException.class, exception.getClass());
                    return;
                }
            }
            Assert.fail("Write did not time out");
        } catch (IOException e) {
            if (errorLatch.await(5, TimeUnit.SECONDS)) {
                Assert.assertEquals(WriteTimeoutException.class, exception.getClass());
            } else {
                Assert.fail("Write did not time out");
            }
        }
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:edu.tsinghua.lumaqq.qq.net.AbstractProxy.java

/**
 * //from w  w  w  .j  a va2s  .co m
 * 
 * @throws IOException
 */
public AbstractProxy(IProxyHandler handler) throws IOException {
    this.handler = handler;
    buffer = ByteBuffer.allocateDirect(300);
    username = password = "";
    connected = false;
    udp = false;

    socketChannel = SocketChannel.open();
    socketChannel.configureBlocking(false);
}

From source file:org.apache.hadoop.io.compress.lz4.Lz4Decompressor.java

/**
 * Creates a new compressor./*  w  ww.  j av  a 2 s.  c  o m*/
 *
 * @param directBufferSize size of the direct buffer to be used.
 */
public Lz4Decompressor(int directBufferSize) {
    this.directBufferSize = directBufferSize;

    compressedDirectBuf = ByteBuffer.allocateDirect(directBufferSize);
    uncompressedDirectBuf = ByteBuffer.allocateDirect(directBufferSize);
    uncompressedDirectBuf.position(directBufferSize);

}

From source file:com.bennavetta.appsite.file.ResourceService.java

public Resource create(String path, MediaType mime, ReadableByteChannel src) throws IOException {
    String normalized = PathUtils.normalize(path);
    log.debug("Creating resource {}", normalized);

    AppEngineFile file = fs.createNewBlobFile(mime.toString(), normalized);
    FileWriteChannel channel = fs.openWriteChannel(file, true);

    MessageDigest digest = null;//from   w  ww  .  j a v a  2 s .c o  m
    try {
        digest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("MD5 not available", e);
    }
    ByteBuffer buf = ByteBuffer.allocateDirect(bufferSize.get());
    while (src.read(buf) != -1 || buf.position() != 0) {
        buf.flip();
        int read = channel.write(buf);
        if (read != 0) {
            int origPos = buf.position();
            int origLimit = buf.limit();
            buf.position(origPos - read);
            buf.limit(origPos);
            digest.update(buf);
            buf.limit(origLimit);
            buf.position(origPos);
        }

        buf.compact();
    }

    channel.closeFinally();
    Resource resource = new Resource(normalized, fs.getBlobKey(file).getKeyString(), digest.digest(), mime);
    resource.save();
    return resource;
}

From source file:io.hops.erasure_coding.NativeReedSolomonCode.java

@Override
public void encodeBulk(byte[][] inputs, byte[][] outputs) {

    ByteBuffer[] binputs = new ByteBuffer[inputs.length];
    ByteBuffer[] boutputs = new ByteBuffer[outputs.length];

    int size = inputs[0].length;
    int[] inputOffsets = new int[inputs.length];
    int[] outputOffsets = new int[outputs.length];

    for (int i = 0; i < binputs.length; i++) {
        binputs[i] = ByteBuffer.allocateDirect(size);
        for (int j = 0; j < size; j++) {
            binputs[i].put(inputs[i][j]);
        }//from  w ww  . j  a v  a  2s .  c  o  m
        binputs[i].flip();
    }

    for (int i = 0; i < boutputs.length; i++) {
        boutputs[i] = ByteBuffer.allocateDirect(size);
    }

    encoder.performEncodeImpl(binputs, inputOffsets, size, boutputs, outputOffsets);

    for (int i = 0; i < boutputs.length; i++) {
        for (int j = 0; j < size; j++) {
            try {
                byte b = boutputs[i].get();
                outputs[i][j] = b;

            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
}

From source file:org.apache.tajo.tuple.offheap.OffHeapMemory.java

public void resize(int newSize) {
    Preconditions.checkArgument(newSize > 0, "Size must be greater than 0 bytes");

    if (newSize > limitSpec.limit()) {
        throw new RuntimeException("Resize cannot exceed the size limit");
    }//from   www  .  j av a2s  . c o  m

    if (newSize < memorySize) {
        LOG.warn("The size reduction is ignored.");
    }

    int newBlockSize = UnsafeUtil.alignedSize(newSize);
    ByteBuffer newByteBuf = ByteBuffer.allocateDirect(newBlockSize);
    long newAddress = ((DirectBuffer) newByteBuf).address();

    UNSAFE.copyMemory(this.address, newAddress, memorySize);

    UnsafeUtil.free(buffer);
    this.memorySize = newSize;
    this.buffer = newByteBuf;
    this.address = newAddress;
}

From source file:uk.co.real_logic.aeron.tools.perf_tools.AeronPing.java

public AeronPing(final String[] args) throws Exception {
    parseArgs(args);/*from   www .  j ava2  s  .  co m*/

    final Aeron.Context ctx = new Aeron.Context().newConnectionHandler(this);

    aeron = Aeron.connect(ctx);
    pub = aeron.addPublication(pingChannel, pingStreamId);
    sub = aeron.addSubscription(pongChannel, pongStreamId);
    connectionLatch = new CountDownLatch(1);
    buffer = new UnsafeBuffer(ByteBuffer.allocateDirect(msgLen));
    timestamps = new long[2][numMsgs];

    if (claim) {
        bufferClaim = new BufferClaim();
    }
}

From source file:org.apache.hadoop.io.compress.snappy.SnappyDecompressor.java

/**
 * Creates a new compressor.//from   w  w  w .  ja  v  a 2 s  .  c  o  m
 *
 * @param directBufferSize size of the direct buffer to be used.
 */
public SnappyDecompressor(int directBufferSize) {
    this.directBufferSize = directBufferSize;

    compressedDirectBuf = ByteBuffer.allocateDirect(directBufferSize);
    uncompressedDirectBuf = ByteBuffer.allocateDirect(directBufferSize);
    uncompressedDirectBuf.position(directBufferSize);

}

From source file:edu.csun.ecs.cs.multitouchj.ui.control.Canvas.java

protected ByteBuffer prepareImage(Image image) {
    ByteBuffer imageData = ByteBuffer.allocateDirect(image.getData().length).order(ByteOrder.nativeOrder());
    imageData.put(image.getData());//from www  . j av  a  2s  .  c o m
    imageData.flip();

    return imageData;
}

From source file:org.apache.tajo.storage.thirdparty.orc.ByteBufferAllocatorPool.java

public ByteBuffer getBuffer(boolean direct, int length) {
    TreeMap<Key, ByteBuffer> tree = getBufferTree(direct);
    Map.Entry<Key, ByteBuffer> entry = tree.ceilingEntry(new Key(length, 0));
    if (entry == null) {
        return direct ? ByteBuffer.allocateDirect(length) : ByteBuffer.allocate(length);
    }//from   w w  w . ja va 2 s.  c o m
    tree.remove(entry.getKey());
    return entry.getValue();
}