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.l2jfree.gameserver.geodata.pathfinding.geonodes.GeoPathFinding.java

private Node readNode(short node_x, short node_y, byte layer) {
    short regoffset = getRegionOffset(getRegionX(node_x), getRegionY(node_y));
    if (!pathNodesExist(regoffset))
        return null;
    short nbx = getNodeBlock(node_x);
    short nby = getNodeBlock(node_y);
    int idx = _pathNodesIndex.get(regoffset).get((nby << 8) + nbx);
    ByteBuffer pn = _pathNodes.get(regoffset);
    //reading//  w  ww  .jav  a  2  s .  com
    byte nodes = pn.get(idx);
    idx += layer * 10 + 1;//byte + layer*10byte
    if (nodes < layer) {
        _log.warn("SmthWrong!");
    }
    short node_z = pn.getShort(idx);
    idx += 2;
    return new GeoNode(node_x, node_y, node_z, idx);
}

From source file:com.l2jfree.gameserver.geodata.pathfinding.geonodes.GeoPathFinding.java

private Node readNode(int gx, int gy, short z) {
    short node_x = getNodePos(gx);
    short node_y = getNodePos(gy);
    short regoffset = getRegionOffset(getRegionX(node_x), getRegionY(node_y));
    if (!pathNodesExist(regoffset))
        return null;
    short nbx = getNodeBlock(node_x);
    short nby = getNodeBlock(node_y);
    int idx = _pathNodesIndex.get(regoffset).get((nby << 8) + nbx);
    ByteBuffer pn = _pathNodes.get(regoffset);
    //reading/*  www.j av a2 s  .c  o  m*/
    byte nodes = pn.get(idx++);
    int idx2 = 0; //create index to nearlest node by z
    short last_z = Short.MIN_VALUE;
    while (nodes > 0) {
        short node_z = pn.getShort(idx);
        if (Math.abs(last_z - z) > Math.abs(node_z - z)) {
            last_z = node_z;
            idx2 = idx + 2;
        }
        idx += 10; //short + 8 byte
        nodes--;
    }
    return new GeoNode(node_x, node_y, last_z, idx2);
}

From source file:gridool.memcached.gateway.BinaryCommandProxy.java

private static void xferResponse(final byte opcode, final SocketChannel src, final Channel dst,
        final String key) throws IOException {
    ByteBuffer headerBuf = ByteBuffer.allocate(BinaryProtocol.HEADER_LENGTH);
    int headerRead = NIOUtils.readFully(src, headerBuf, BinaryProtocol.HEADER_LENGTH);
    assert (headerRead == BinaryProtocol.HEADER_LENGTH) : headerRead;
    headerBuf.flip();//from  w w w . java  2 s. c  o  m

    if (BinaryProtocol.surpressSuccessResponse(opcode)) {
        // piggyback will never happens 
        final short status = headerBuf.getShort(6);
        if (status == 0) {
            return;
        }
    }

    ChannelBuffer res;
    int totalBody = headerBuf.getInt(8);
    if (totalBody > 0) {
        ByteBuffer bodyBuf = ByteBuffer.allocate(totalBody);
        int bodyRead = NIOUtils.readFully(src, bodyBuf, totalBody);
        assert (bodyRead == totalBody) : "bodyRead (" + bodyRead + ") != totalBody (" + totalBody + ")";
        bodyBuf.flip();
        res = ChannelBuffers.wrappedBuffer(headerBuf, bodyBuf);
    } else {
        res = ChannelBuffers.wrappedBuffer(headerBuf);
    }
    String opname = BinaryProtocol.resolveName(headerBuf.get(1));
    if (LOG.isDebugEnabled()) {
        Header header = new Header();
        header.decode(headerBuf);
        LOG.debug(
                "Start sending memcached response [" + opname + "] " + res.readableBytes() + " bytes for key '"
                        + key + "'\n" + header + '\n' + Arrays.toString(res.toByteBuffer().array()));
    }
    dst.write(res).addListener(new VerboseListener("sendResponse [" + opname + "] for key: " + key));
}

From source file:com.linkedin.pinot.core.indexsegment.utils.MmapMemoryManagerTest.java

@Test
public void testLargeBlocks() throws Exception {
    final String segmentName = "someSegment";
    PinotDataBufferMemoryManager memoryManager = new MmapMemoryManager(_tmpDir, segmentName);
    final long s1 = 2 * MmapMemoryManager.getDefaultFileLength();
    final long s2 = 1000;
    final String col1 = "col1";
    final String col2 = "col2";
    final byte value = 34;
    PinotDataBuffer buf1 = memoryManager.allocate(s1, col1);

    // Verify that we can write to and read from the buffer
    ByteBuffer b1 = buf1.toDirectByteBuffer(0, (int) s1);
    b1.putLong(0, s1);//from  w w  w. j  a va 2  s  .  c  om
    Assert.assertEquals(b1.getLong(0), s1);
    b1.put((int) s1 - 1, value);
    Assert.assertEquals(b1.get((int) s1 - 1), value);

    PinotDataBuffer buf2 = memoryManager.allocate(s2, col2);
    ByteBuffer b2 = buf2.toDirectByteBuffer(0, (int) s2);
    b2.putLong(0, s2);
    Assert.assertEquals(b2.getLong(0), s2);

    File dir = new File(_tmpDir);
    File[] files = dir.listFiles();
    Assert.assertEquals(files.length, 2);

    Arrays.sort(files, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });

    String fileName = files[0].getName();
    Assert.assertTrue(fileName.contains(segmentName));

    fileName = files[1].getName();
    Assert.assertTrue(fileName.contains(segmentName));

    buf1.close();
    buf2.close();

    memoryManager.close();

    List<Pair<MmapUtils.AllocationContext, Integer>> allocationContexts = MmapUtils.getAllocationsAndSizes();
    Assert.assertEquals(allocationContexts.size(), 0);
    Assert.assertEquals(new File(_tmpDir).listFiles().length, 0);
}

From source file:com.taobao.common.tfs.comm.TfsClient.java

public Object invoke(final BasePacket packet, final long timeout) throws TfsException {
    if (isDebugEnabled) {
        log.debug("send request [" + packet.getChid() + "],time is:" + System.currentTimeMillis());
    }//w  ww.j  a  v a2 s  .c o  m
    ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(1);
    responses.put(packet.getChid(), queue);
    ByteBuffer bb = packet.getByteBuffer();
    bb.flip();
    byte[] data = new byte[bb.remaining()];
    bb.get(data);
    WriteFuture writeFuture = session.write(data);
    writeFuture.addListener(new IoFutureListener() {

        public void operationComplete(IoFuture future) {

            WriteFuture wfuture = (WriteFuture) future;
            if (wfuture.isWritten()) {
                return;
            }
            String error = "send message to tfs server error [" + packet.getChid() + "], tfs server: "
                    + session.getRemoteAddress() + ", maybe because this connection closed: "
                    + !session.isConnected();

            try {
                putResponse(packet.getChid(), new TfsException(error));
            } catch (TfsException e) {
                // should never happen
                log.error("put response fail", e);
            }

            // close this session
            if (session.isConnected()) {
                session.close();
            } else {
                TfsClientFactory.getInstance().removeClient(key);
            }
        }

    });

    Object response = null;
    try {
        response = queue.poll(timeout, TimeUnit.MILLISECONDS);
        if (response == null) { // timeout
            return null;
        } else if (response instanceof TfsException) {
            throw (TfsException) response;
        }
    } catch (InterruptedException e) {
        throw new TfsException("tfs client invoke error", e);
    } finally {
        responses.remove(packet.getChid());
        // For GC
        queue = null;
    }
    if (isDebugEnabled) {
        log.debug("return response [" + packet.getChid() + "],time is:" + System.currentTimeMillis());
    }

    // do decode here
    if (response instanceof BasePacket) {
        ((BasePacket) response).decode();
    }
    return response;
}

From source file:com.taobao.tair.comm.TairClient.java

public Object invoke(final BasePacket packet, final long timeout) throws TairClientException {
    if (isDebugEnabled) {
        LOGGER.debug("send request [" + packet.getChid() + "],time is:" + System.currentTimeMillis());
    }//from w  ww .  j  a  va  2s  . com
    ArrayBlockingQueue<Object> queue = new ArrayBlockingQueue<Object>(1);
    responses.put(packet.getChid(), queue);
    ByteBuffer bb = packet.getByteBuffer();
    bb.flip();
    byte[] data = new byte[bb.remaining()];
    bb.get(data);
    WriteFuture writeFuture = session.write(data);
    writeFuture.addListener(new IoFutureListener() {

        public void operationComplete(IoFuture future) {
            WriteFuture wfuture = (WriteFuture) future;
            if (wfuture.isWritten()) {
                return;
            }
            String error = "send message to tair server error [" + packet.getChid() + "], tair server: "
                    + session.getRemoteAddress() + ", maybe because this connection closed :"
                    + !session.isConnected();
            LOGGER.warn(error);
            TairResponse response = new TairResponse();
            response.setRequestId(packet.getChid());
            response.setResponse(new TairClientException(error));
            try {
                putResponse(packet.getChid(), response.getResponse());
            } catch (TairClientException e) {
                // IGNORE,should not happen
            }
            // close this session
            if (session.isConnected())
                session.close();
            else
                clientFactory.removeClient(key);
        }

    });
    Object response = null;
    try {
        response = queue.poll(timeout, TimeUnit.MILLISECONDS);
        if (response == null) {
            throw new TairClientException("tair client invoke timeout,timeout is: " + timeout
                    + ",requestId is: " + packet.getChid() + "request type:" + packet.getClass().getName());
        } else if (response instanceof TairClientException) {
            throw (TairClientException) response;
        }
    } catch (InterruptedException e) {
        throw new TairClientException("tair client invoke error", e);
    } finally {
        responses.remove(packet.getChid());
        // For GC
        queue = null;
    }
    if (isDebugEnabled) {
        LOGGER.debug("return response [" + packet.getChid() + "],time is:" + System.currentTimeMillis());
        LOGGER.debug("current responses size: " + responses.size());
    }

    // do decode here
    if (response instanceof BasePacket) {
        ((BasePacket) response).decode();
    }
    return response;
}

From source file:client.MultiplexingClient.java

private String bufferToString(ByteBuffer bb) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < bb.limit(); i++) {
        sb.append((char) bb.get(i));
    }/*  w ww  . j  av  a2s  .  c  o  m*/
    return sb.toString();
}

From source file:org.ojai.beans.jackson.DocumentParser.java

@Override
public byte[] getBinaryValue(Base64Variant bv) throws IOException {
    ByteBuffer buf = r.getBinary();
    byte[] result = new byte[buf.remaining()];
    buf.get(result);
    return result;
}

From source file:de.csdev.ebus.command.EBusCommandRegistry.java

/**
 * Checks if the given command method is acceptable for the unescaped telegram
 *
 * @param command//from  w  w w. j  av  a 2 s  .co  m
 * @param data
 * @return
 */
public boolean matchesCommand(IEBusCommandMethod command, ByteBuffer data) {

    Byte sourceAddress = (Byte) ObjectUtils.defaultIfNull(command.getSourceAddress(),
            Byte.valueOf((byte) 0x00));

    Byte targetAddress = (Byte) ObjectUtils.defaultIfNull(command.getDestinationAddress(),
            Byte.valueOf((byte) 0x00));

    try {

        ByteBuffer masterTelegram = EBusCommandUtils.buildMasterTelegram(command, sourceAddress, targetAddress,
                null);

        ByteBuffer mask = command.getMasterTelegramMask();

        for (int i = 0; i < mask.limit(); i++) {
            byte b = mask.get(i);

            if (b == (byte) 0xFF) {
                if (masterTelegram.get(i) != data.get(i)) {
                    break;
                }
            }
            if (i == mask.limit() - 1) {
                return true;
            }
        }
    } catch (EBusTypeException e) {
        logger.error("error!", e);
    }

    return false;
}

From source file:org.apache.solr.handler.TestBlobHandler.java

private void compareInputAndOutput(String url, byte[] bytarr) throws IOException {

    HttpClient httpClient = cloudClient.getLbClient().getHttpClient();

    HttpGet httpGet = new HttpGet(url);
    HttpResponse entity = httpClient.execute(httpGet);
    ByteBuffer b = SimplePostTool.inputStreamToByteArray(entity.getEntity().getContent());
    try {//www .  j  a va 2 s  .  c o  m
        assertEquals(b.limit(), bytarr.length);
        for (int i = 0; i < bytarr.length; i++) {
            assertEquals(b.get(i), bytarr[i]);
        }
    } finally {
        httpGet.releaseConnection();
    }

}