Example usage for java.nio ByteBuffer clear

List of usage examples for java.nio ByteBuffer clear

Introduction

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

Prototype

public final Buffer clear() 

Source Link

Document

Clears this buffer.

Usage

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 ww w  .  j a  va 2  s  .  c o  m
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.alexkli.jhb.Worker.java

@Override
public void run() {
    try {//ww  w .j ava  2  s.  co m
        while (true) {
            long start = System.nanoTime();

            QueueItem<HttpRequestBase> item = queue.take();

            idleAvg.add(System.nanoTime() - start);

            if (item.isPoisonPill()) {
                return;
            }

            HttpRequestBase request = item.getRequest();

            if ("java".equals(config.client)) {
                System.setProperty("http.keepAlive", "false");

                item.sent();

                try {
                    HttpURLConnection http = (HttpURLConnection) new URL(request.getURI().toString())
                            .openConnection();
                    http.setConnectTimeout(5000);
                    http.setReadTimeout(5000);
                    int statusCode = http.getResponseCode();

                    consumeAndCloseStream(http.getInputStream());

                    if (statusCode == 200) {
                        item.done();
                    } else {
                        item.failed();
                    }
                } catch (IOException e) {
                    System.err.println("Failed request: " + e.getMessage());
                    e.printStackTrace();
                    //                        System.exit(2);
                    item.failed();
                }
            } else if ("ahc".equals(config.client)) {
                try {
                    item.sent();

                    try (CloseableHttpResponse response = httpClient.execute(request, context)) {
                        int statusCode = response.getStatusLine().getStatusCode();
                        if (statusCode == 200) {
                            item.done();
                        } else {
                            item.failed();
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Failed request: " + e.getMessage());
                    item.failed();
                }
            } else if ("fast".equals(config.client)) {
                try {
                    URI uri = request.getURI();

                    item.sent();

                    InetAddress addr = InetAddress.getByName(uri.getHost());
                    Socket socket = new Socket(addr, uri.getPort());
                    PrintWriter out = new PrintWriter(socket.getOutputStream());
                    //                        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    // send an HTTP request to the web server
                    out.println("GET / HTTP/1.1");
                    out.append("Host: ").append(uri.getHost()).append(":").println(uri.getPort());
                    out.println("Connection: Close");
                    out.println();
                    out.flush();

                    // read the response
                    consumeAndCloseStream(socket.getInputStream());
                    //                        boolean loop = true;
                    //                        StringBuilder sb = new StringBuilder(8096);
                    //                        while (loop) {
                    //                            if (in.ready()) {
                    //                                int i = 0;
                    //                                while (i != -1) {
                    //                                    i = in.read();
                    //                                    sb.append((char) i);
                    //                                }
                    //                                loop = false;
                    //                            }
                    //                        }
                    item.done();
                    socket.close();

                } catch (IOException e) {
                    e.printStackTrace();
                    item.failed();
                }
            } else if ("nio".equals(config.client)) {
                URI uri = request.getURI();

                item.sent();

                String requestBody = "GET / HTTP/1.1\n" + "Host: " + uri.getHost() + ":" + uri.getPort() + "\n"
                        + "Connection: Close\n\n";

                try {
                    InetSocketAddress addr = new InetSocketAddress(uri.getHost(), uri.getPort());
                    SocketChannel channel = SocketChannel.open();
                    channel.socket().setSoTimeout(5000);
                    channel.connect(addr);

                    ByteBuffer msg = ByteBuffer.wrap(requestBody.getBytes());
                    channel.write(msg);
                    msg.clear();

                    ByteBuffer buf = ByteBuffer.allocate(1024);

                    int count;
                    while ((count = channel.read(buf)) != -1) {
                        buf.flip();

                        byte[] bytes = new byte[count];
                        buf.get(bytes);

                        buf.clear();
                    }
                    channel.close();

                    item.done();

                } catch (IOException e) {
                    e.printStackTrace();
                    item.failed();
                }
            }
        }
    } catch (InterruptedException e) {
        System.err.println("Worker thread [" + this.toString() + "] was interrupted: " + e.getMessage());
    }
}

From source file:com.hadoop.compression.fourmc.Lz4Compressor.java

/**
 * Reallocates a direct byte buffer by freeing the old one and allocating
 * a new one, unless the size is the same, in which case it is simply
 * cleared and returned.//from   ww w.  j ava  2s.c  o  m
 * <p/>
 * NOTE: this uses unsafe APIs to manually free memory - if anyone else
 * has a reference to the 'buf' parameter they will likely read random
 * data or cause a segfault by accessing it.
 */
private ByteBuffer realloc(ByteBuffer buf, int newSize) {
    if (buf != null) {
        if (buf.capacity() == newSize) {
            // Can use existing buffer
            buf.clear();
            return buf;
        }

        DirectBufferPool.getInstance().release(buf);
    }
    return DirectBufferPool.getInstance().allocate(newSize);
}

From source file:me.schiz.jmeter.ring.udp.sampler.UDPRingSampler.java

@Override
public SampleResult sample(Entry entry) {
    boolean idling = false;
    SampleResult newSampleResult = new SampleResult();
    newSampleResult.setSampleLabel(getName());

    ConcurrentLinkedQueue<SampleResult> queue = tlQueue.get();
    if (queue == null) {
        queue = new ConcurrentLinkedQueue<SampleResult>();
        tlQueue.set(queue);//w w  w. j  ava  2  s  . c  o  m
    }

    Ring ring = UDPRingSourceElement.get(getSource());
    Token t;
    int tid = -1;
    byte[] request_in_bytes = new byte[0];

    ByteBuffer request = tlRequest.get();
    if (request == null) {
        request = tlBuffer.get();
        if (request == null) {
            request = ByteBuffer.allocateDirect(8 * 1024 * 1024);
            tlBuffer.set(request);
        }
        request.clear();

        if (isHex()) {
            try {
                request_in_bytes = Hex.decodeHex(getRequest().toCharArray());
            } catch (DecoderException e) {
                log.error("can't decode request", e);
                idling = true;
            }
        } else {
            request_in_bytes = getRequest().getBytes();
        }
        request.put(request_in_bytes);
    }
    if (!idling) {
        try {
            request.flip();
            while (tid == -1) {
                tid = ring.acquire();
            }
            t = ring.get(tid);
            t.lock.lock();
            if (isHex())
                t.ishex = true;
            newSampleResult.sampleStart();
            try {
                //t.socketChannel.write(request);
                t.sampleResult = newSampleResult;
                t.queue = queue;
                ring.write(tid, request);
                request.clear();
                newSampleResult.setSuccessful(true);
            } catch (IOException e) {
                newSampleResult.setSuccessful(false);
                ring.reset(tid);
                log.warn("IOException", e);
            } finally {
                t.lock.unlock();
            }

        } catch (Exception e) {
            log.error("Exception", e);
            newSampleResult.setSuccessful(false);
            newSampleResult.setResponseCode(e.getClass().getName());
            while (!queue.offer(newSampleResult)) {
            }
            if (tid != -1)
                ring.reset(tid);
        } finally {
            newSampleResult.setRequestHeaders(getRequest());
        }
    }
    SampleResult sampleResult = queue.poll();
    return sampleResult;
}

From source file:org.apache.hadoop.hbase.io.BoundedByteBufferPool.java

public ByteBuffer getBuffer() {
    ByteBuffer bb = null;
    lock.lock();// ww w.ja  v  a 2s.  co  m
    try {
        bb = this.buffers.poll();
        if (bb != null) {
            this.totalReservoirCapacity -= bb.capacity();
        }
    } finally {
        lock.unlock();
    }
    if (bb != null) {
        // Clear sets limit == capacity. Postion == 0.
        bb.clear();
    } else {
        bb = ByteBuffer.allocate(this.runningAverage);
        this.allocations.incrementAndGet();
    }
    if (LOG.isTraceEnabled()) {
        LOG.trace("runningAverage=" + this.runningAverage + ", totalCapacity=" + this.totalReservoirCapacity
                + ", count=" + this.buffers.size() + ", alloctions=" + this.allocations.get());
    }
    return bb;
}

From source file:com.saasovation.common.port.adapter.messaging.slothmq.SlothWorker.java

protected String receive() {
    SocketChannel socketChannel = null;

    try {//  ww w  . j a va 2 s .c  o  m
        socketChannel = this.socket.accept();

        if (socketChannel == null) {
            return null; // if non-blocking
        }

        ReadableByteChannel readByteChannel = Channels.newChannel(socketChannel.socket().getInputStream());

        ByteArrayOutputStream byteArray = new ByteArrayOutputStream();

        ByteBuffer readBuffer = ByteBuffer.allocate(8);

        while (readByteChannel.read(readBuffer) != -1) {
            readBuffer.flip();

            while (readBuffer.hasRemaining()) {
                byteArray.write(readBuffer.get());
            }

            readBuffer.clear();
        }

        return new String(byteArray.toByteArray());

    } catch (IOException e) {
        logger.error("Failed to receive because: {}: Continuing...", e.getMessage(), e);
        return null;

    } finally {
        if (socketChannel != null) {
            try {
                socketChannel.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

From source file:org.neo4j.io.pagecache.impl.SingleFilePageSwapperTest.java

private byte[] array(ByteBuffer target) {
    target.clear();
    byte[] array = new byte[target.capacity()];
    while (target.position() < target.capacity()) {
        array[target.position()] = target.get();
    }/*  w  w w .ja v a2s . c om*/
    return array;
}

From source file:edu.usc.pgroup.floe.client.FloeClient.java

/**
 * Uploads the file to the coordinator.//from ww w  .j a va 2 s .c o  m
 * The file is uploaded relative to the coordinator's scratch folder.
 *
 * @param fileName name of the file to be stored on the coordinator.
 * @return the base fileName which may be used for downloading the file
 * later.
 */
public final String uploadFileSync(final String fileName) {
    String baseFile = FilenameUtils.getName(fileName);
    try {
        int fid = getClient().beginFileUpload(baseFile);
        ReadableByteChannel inChannel = Channels.newChannel(new FileInputStream(fileName));
        ByteBuffer buffer = ByteBuffer.allocate(Utils.Constants.BUFFER_SIZE);
        while (inChannel.read(buffer) > 0) {
            buffer.flip();
            getClient().uploadChunk(fid, buffer);
            buffer.clear();
        }
        inChannel.close();
        getClient().finishUpload(fid);
    } catch (TException e) {
        LOGGER.error(e.getMessage());
        throw new RuntimeException(e);
    } catch (FileNotFoundException e) {
        LOGGER.error(e.getMessage());
        throw new RuntimeException(e);
    } catch (IOException e) {
        LOGGER.error(e.getMessage());
        throw new RuntimeException(e);
    }
    return baseFile;
}

From source file:com.gamesalutes.utils.ByteUtils.java

/**
 * Extends the size of <code>buf</code> to at least meet <code>minCap</code>.
 * If <code>buf</code> is too small, then a new buffer is allocated and
 * any existing contents in <code>buf</code> will be transfered.  The position
 * of the new buffer will be that of the old buffer if it was not <code>null</code>, and
 * the previous mark will be discarded if one was set.
 * /* www . j  av  a2s .  c  o  m*/
 * @param buf the input <code>ByteBuffer</code>
 * @param minCap the minimum capacity
 * @return a <code>ByteBuffer</code> that can meet <code>minCap</code>
 */
public static ByteBuffer growBuffer(ByteBuffer buf, int minCap) {
    int myLimit = buf != null ? buf.limit() : 0;
    // limit can accomidate capacity requirements
    if (buf != null && myLimit >= minCap)
        return buf;
    int myCap = buf != null ? buf.capacity() : 0;
    // capacity can accomidate but limit is too small
    if (buf != null && myCap >= minCap) {
        buf.limit(myCap);
        return buf;
    } else //if(myCap < minCap)
    {
        ByteBuffer newBuffer = null;
        if (myCap == 0)
            myCap = 1;
        while (myCap < minCap)
            myCap <<= 1;
        if (buf != null && buf.isDirect())
            newBuffer = ByteBuffer.allocateDirect(myCap);
        else
            newBuffer = ByteBuffer.allocate(myCap);
        // copy contents of original buffer
        if (buf != null) {
            int pos = buf.position();
            buf.clear();
            newBuffer.put(buf);
            newBuffer.position(pos);
        }
        return newBuffer;

    }
}

From source file:Main.java

public final static void giveBack(ByteBuffer bb) {
    if (bb != null) {
        final int capacity = bb.capacity();
        if (capacity == MAX_LINE_BYTES_SMALL) {
            if (!byteBuffersPoolSmall.contains(bb) && byteBuffersPoolSmall.size() < MAX_BUFFER_SIZE) {
                byteBuffersPoolSmall.add(bb);
            }// w  w w.j  a v  a2s .  c  o  m
        } else if (capacity == MAX_LINE_BYTES_MEDIUM) {
            if (!byteBuffersPoolMedium.contains(bb) && byteBuffersPoolMedium.size() < MAX_BUFFER_SIZE) {
                byteBuffersPoolMedium.add(bb);
            }
        } else if (capacity == MAX_LINE_BYTES_NORMAL) {
            if (!byteBuffersPoolNormal.contains(bb) && byteBuffersPoolNormal.size() < MAX_BUFFER_SIZE) {
                byteBuffersPoolNormal.add(bb);
            }
        } else if (capacity == MAX_LINE_BYTES_LARGE) {
            if (!byteBuffersPoolLarge.contains(bb) && byteBuffersPoolLarge.size() < MAX_BUFFER_SIZE) {
                byteBuffersPoolLarge.add(bb);
            }
        } else if (capacity == MAX_LINE_BYTES_VERY_LARGE) {
            if (!byteBuffersPoolLarge.contains(bb) && byteBuffersPoolLarge.size() < 2) {
                byteBuffersPoolLarge.add(bb);
            }
        } else {
            throw new IllegalArgumentException("Non compatible byte buffer size: " + capacity);
        }
        bb.clear();
    }
}