Example usage for java.nio ByteBuffer getLong

List of usage examples for java.nio ByteBuffer getLong

Introduction

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

Prototype

public abstract long getLong(int index);

Source Link

Document

Returns the long at the specified index.

Usage

From source file:org.daxplore.presenter.shared.Base64Test.java

/**
 * Test encoding and decoding of longs, which was added for the Daxplore
 * project./*  w  w  w. jav a  2  s.co m*/
 * @throws UnsupportedEncodingException 
 */
@Test
public void testLongRandom() throws UnsupportedEncodingException {
    org.apache.commons.codec.binary.Base64 apacheCoder = new org.apache.commons.codec.binary.Base64();

    Random rnd = new Random(0x8af3411e);
    for (int i = 0; i < 1000; i++) {
        long testLong;
        switch (i) {
        case 0:
            testLong = 0;
            break;
        case 1:
            testLong = -1;
            break;
        case 2:
            testLong = Long.MAX_VALUE;
            break;
        case 3:
            testLong = Long.MIN_VALUE;
            break;
        default:
            testLong = rnd.nextLong();
        }

        String e1 = Base64.encodeLong(testLong);
        long d1 = Base64.decodeLong(e1);
        assertEquals(testLong, d1);

        byte[] bytes = ByteBuffer.allocate(8).putLong(testLong).array();
        int firstRelevantByte = 0;
        for (; firstRelevantByte < bytes.length && bytes[firstRelevantByte] == 0; firstRelevantByte++) {
            // increase firstRelevantByte to reach non-zero byte or end 
        }
        bytes = Arrays.copyOfRange(bytes, firstRelevantByte, bytes.length);
        String e2 = new String(apacheCoder.encode(bytes), "UTF-8");

        bytes = apacheCoder.decode(e2.getBytes("UTF-8"));
        ByteBuffer bb = ByteBuffer.allocate(8);
        bb.position(8 - bytes.length);
        bb.put(bytes);
        assertEquals(testLong, bb.getLong(0));

        assertEquals(e2, e1);
    }
}

From source file:org.spoutcraft.client.packet.PacketEntityInformation.java

public void run(int playerId) {
    if (Minecraft.theMinecraft.theWorld instanceof WorldClient) {
        ByteBuffer rawData = ByteBuffer.allocate(data.length);
        rawData.put(data);//from ww w.  j av a2s.c o m
        for (int i = 0; i < data.length / 20; i++) {
            int index = i * 20;
            long lsb = rawData.getLong(index);
            long msb = rawData.getLong(index + 8);
            int id = rawData.getInt(index + 16);

            net.minecraft.src.Entity e = SpoutClient.getInstance().getEntityFromId(id);
            if (e != null) {
                e.uniqueId = new UUID(msb, lsb);
            }
        }
    }
}

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

@Test
public void testSmallBlocksForSameColumn() throws Exception {
    final String segmentName = "someSegment";
    PinotDataBufferMemoryManager memoryManager = new MmapMemoryManager(_tmpDir, segmentName);
    final long s1 = 500;
    final long s2 = 1000;
    final String col1 = "col1";
    PinotDataBuffer buf1 = memoryManager.allocate(s1, col1);

    PinotDataBuffer buf2 = memoryManager.allocate(s2, col1);

    ByteBuffer b1 = buf1.toDirectByteBuffer(0, (int) s1);
    b1.putLong(0, s1);//from  www .  j  av a2  s.  co  m

    ByteBuffer b2 = buf2.toDirectByteBuffer(0, (int) s2);
    b2.putLong(0, s2);

    Assert.assertEquals(b1.getLong(0), s1);
    Assert.assertEquals(b2.getLong(0), s2);

    File dir = new File(_tmpDir);
    Assert.assertEquals(dir.listFiles().length, 1);

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

    memoryManager.close();

    List<Pair<MmapUtils.AllocationContext, Integer>> allocationContexts = MmapUtils.getAllocationsAndSizes();
    Assert.assertEquals(allocationContexts.size(), 0);

    Assert.assertEquals(dir.listFiles().length, 0);
}

From source file:tagtime.random.RandomSequenceGenerator.java

/**
 * Returns the random value at the given position in the sequence.
 * @return A pseudo-random value between 0 and 1.
 *//*from w  w w  .j  a va 2 s. co  m*/
public double getValue(long position) {
    ByteBuffer outputBytes = ByteBuffer.allocate(16);
    try {
        cipher.doFinal((ByteBuffer) ByteBuffer.allocate(8).putLong(position).rewind(), outputBytes);
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }

    //convert the bytes to a double between 0 and 1
    return 0.5 + 0.5 * ((double) outputBytes.getLong(0) / Long.MAX_VALUE);
}

From source file:com.mbientlab.metawear.app.AccelerometerFragment.java

private void writeDataToFile() {
    dataFilename = String.format(Locale.US, "metawear_accelerometer_data-%s-%s.csv",
            FullScaleRange.values()[accelConfig.fsrPos()].toString(),
            OutputDataRate.values()[accelConfig.odrPos()].toString());
    try {/*from   w  ww. j a  v a 2s  .  c  om*/
        FileOutputStream fos = getActivity().openFileOutput(dataFilename, Context.MODE_PRIVATE);
        fos.write(CSV_HEADER.getBytes());

        for (byte[] dataBytes : accelConfig.polledBytes()) {
            ByteBuffer buffer = ByteBuffer.wrap(dataBytes);
            double tickInS = (double) (buffer.getLong(6) / 1000.0);
            float xAccel, yAccel, zAccel;

            if (accelConfig.firmwarePos() == 0) {
                xAccel = buffer.getShort(0) / 1000.0f;
                yAccel = buffer.getShort(2) / 1000.0f;
                zAccel = buffer.getShort(4) / 1000.0f;
            } else {
                xAccel = BytesInterpreter.bytesToGs(accelConfig.getSamplingConfig(), buffer.getShort(0));
                yAccel = BytesInterpreter.bytesToGs(accelConfig.getSamplingConfig(), buffer.getShort(2));
                zAccel = BytesInterpreter.bytesToGs(accelConfig.getSamplingConfig(), buffer.getShort(4));
            }

            fos.write(String.format(Locale.US, "%.3f,%.3f,%.3f,%.3f%n", tickInS, xAccel, yAccel, zAccel)
                    .getBytes());
        }

        fos.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.apache.cassandra.db.context.CounterContextTest.java

@Test
public void testMerge() {
    // note: local counts aggregated; remote counts are reconciled (i.e. take max)
    ContextState left = ContextState.allocate(4, 1);
    left.writeElement(NodeId.fromInt(1), 1L, 1L);
    left.writeElement(NodeId.fromInt(2), 2L, 2L);
    left.writeElement(NodeId.fromInt(4), 6L, 3L);
    left.writeElement(NodeId.getLocalId(), 7L, 3L, true);

    ContextState right = ContextState.allocate(3, 1);
    right.writeElement(NodeId.fromInt(4), 4L, 4L);
    right.writeElement(NodeId.fromInt(5), 5L, 5L);
    right.writeElement(NodeId.getLocalId(), 2L, 9L, true);

    ByteBuffer merged = cc.merge(left.context, right.context);
    int hd = 4;/*from   ww w. j  ava2 s . c om*/

    assertEquals(hd + 5 * stepLength, merged.remaining());
    // local node id's counts are aggregated
    assert Util.equalsNodeId(NodeId.getLocalId(), merged, hd + 4 * stepLength);
    assertEquals(9L, merged.getLong(hd + 4 * stepLength + idLength));
    assertEquals(12L, merged.getLong(hd + 4 * stepLength + idLength + clockLength));

    // remote node id counts are reconciled (i.e. take max)
    assert Util.equalsNodeId(NodeId.fromInt(4), merged, hd + 2 * stepLength);
    assertEquals(6L, merged.getLong(hd + 2 * stepLength + idLength));
    assertEquals(3L, merged.getLong(hd + 2 * stepLength + idLength + clockLength));

    assert Util.equalsNodeId(NodeId.fromInt(5), merged, hd + 3 * stepLength);
    assertEquals(5L, merged.getLong(hd + 3 * stepLength + idLength));
    assertEquals(5L, merged.getLong(hd + 3 * stepLength + idLength + clockLength));

    assert Util.equalsNodeId(NodeId.fromInt(2), merged, hd + 1 * stepLength);
    assertEquals(2L, merged.getLong(hd + 1 * stepLength + idLength));
    assertEquals(2L, merged.getLong(hd + 1 * stepLength + idLength + clockLength));

    assert Util.equalsNodeId(NodeId.fromInt(1), merged, hd + 0 * stepLength);
    assertEquals(1L, merged.getLong(hd + 0 * stepLength + idLength));
    assertEquals(1L, merged.getLong(hd + 0 * stepLength + idLength + clockLength));
}

From source file:org.apache.jackrabbit.oak.plugins.segment.file.TarReader.java

@CheckForNull
private List<UUID> getReferences(TarEntry entry, UUID id, Map<UUID, List<UUID>> graph) throws IOException {
    if (graph != null) {
        return graph.get(id);
    } else {/*w  w  w.j ava2  s.c  o  m*/
        // a pre-compiled graph is not available, so read the
        // references directly from this segment
        ByteBuffer segment = access.read(entry.offset(), Math.min(entry.size(), 16 * 256));
        int pos = segment.position();
        int refCount = segment.get(pos + REF_COUNT_OFFSET) & 0xff;
        int refEnd = pos + 16 * (refCount + 1);
        List<UUID> refIds = newArrayList();
        for (int refPos = pos + 16; refPos < refEnd; refPos += 16) {
            refIds.add(new UUID(segment.getLong(refPos), segment.getLong(refPos + 8)));
        }
        return refIds;
    }
}

From source file:org.apache.jackrabbit.oak.segment.file.TarReader.java

@Nonnull
private List<UUID> getReferences(TarEntry entry, UUID id, Map<UUID, List<UUID>> graph) throws IOException {
    if (graph != null) {
        List<UUID> uuids = graph.get(id);
        return uuids == null ? Collections.<UUID>emptyList() : uuids;
    } else {//from w ww  . j a  va  2s  .c  o  m
        // a pre-compiled graph is not available, so read the
        // references directly from this segment
        ByteBuffer segment = access.read(entry.offset(), Math.min(entry.size(), 16 * 256));
        int pos = segment.position();
        int refCount = segment.get(pos + REF_COUNT_OFFSET) & 0xff;
        int refEnd = pos + 16 * (refCount + 1);
        List<UUID> refIds = newArrayList();
        for (int refPos = pos + 16; refPos < refEnd; refPos += 16) {
            refIds.add(new UUID(segment.getLong(refPos), segment.getLong(refPos + 8)));
        }
        return refIds;
    }
}

From source file:com.healthmarketscience.jackcess.Column.java

/**
 * Decodes "Currency" values./*  w ww.  ja v  a2  s  .  co  m*/
 * 
 * @param buffer Column value that points to currency data
 * @return BigDecimal representing the monetary value
 * @throws IOException if the value cannot be parsed 
 */
private static BigDecimal readCurrencyValue(ByteBuffer buffer) throws IOException {
    if (buffer.remaining() != 8) {
        throw new IOException("Invalid money value.");
    }

    return new BigDecimal(BigInteger.valueOf(buffer.getLong(0)), 4);
}

From source file:org.apache.cassandra.db.CounterColumnTest.java

@Test
public void testReconcile() throws UnknownHostException {
    IColumn left;/*from ww w . j a va 2  s .  c o  m*/
    IColumn right;
    IColumn reconciled;

    ByteBuffer context;

    // tombstone + tombstone
    left = new DeletedColumn(ByteBufferUtil.bytes("x"), 1, 1L);
    right = new DeletedColumn(ByteBufferUtil.bytes("x"), 2, 2L);

    assert left.reconcile(right).getMarkedForDeleteAt() == right.getMarkedForDeleteAt();
    assert right.reconcile(left).getMarkedForDeleteAt() == right.getMarkedForDeleteAt();

    // tombstone > live
    left = new DeletedColumn(ByteBufferUtil.bytes("x"), 1, 2L);
    right = new CounterColumn(ByteBufferUtil.bytes("x"), 0L, 1L);

    assert left.reconcile(right) == left;

    // tombstone < live last delete
    left = new DeletedColumn(ByteBufferUtil.bytes("x"), 1, 1L);
    right = new CounterColumn(ByteBufferUtil.bytes("x"), 0L, 4L, 2L);

    assert left.reconcile(right) == right;

    // tombstone == live last delete
    left = new DeletedColumn(ByteBufferUtil.bytes("x"), 1, 2L);
    right = new CounterColumn(ByteBufferUtil.bytes("x"), 0L, 4L, 2L);

    assert left.reconcile(right) == right;

    // tombstone > live last delete
    left = new DeletedColumn(ByteBufferUtil.bytes("x"), 1, 4L);
    right = new CounterColumn(ByteBufferUtil.bytes("x"), 0L, 9L, 1L);

    reconciled = left.reconcile(right);
    assert reconciled.name() == right.name();
    assert reconciled.value() == right.value();
    assert reconciled.timestamp() == right.timestamp();
    assert ((CounterColumn) reconciled).timestampOfLastDelete() == left.getMarkedForDeleteAt();

    // live < tombstone
    left = new CounterColumn(ByteBufferUtil.bytes("x"), 0L, 1L);
    right = new DeletedColumn(ByteBufferUtil.bytes("x"), 1, 2L);

    assert left.reconcile(right) == right;

    // live last delete > tombstone
    left = new CounterColumn(ByteBufferUtil.bytes("x"), 0L, 4L, 2L);
    right = new DeletedColumn(ByteBufferUtil.bytes("x"), 1, 1L);

    assert left.reconcile(right) == left;

    // live last delete == tombstone
    left = new CounterColumn(ByteBufferUtil.bytes("x"), 0L, 4L, 2L);
    right = new DeletedColumn(ByteBufferUtil.bytes("x"), 1, 2L);

    assert left.reconcile(right) == left;

    // live last delete < tombstone
    left = new CounterColumn(ByteBufferUtil.bytes("x"), 0L, 9L, 1L);
    right = new DeletedColumn(ByteBufferUtil.bytes("x"), 1, 4L);

    reconciled = left.reconcile(right);
    assert reconciled.name() == left.name();
    assert reconciled.value() == left.value();
    assert reconciled.timestamp() == left.timestamp();
    assert ((CounterColumn) reconciled).timestampOfLastDelete() == right.getMarkedForDeleteAt();

    // live < live last delete
    left = new CounterColumn(ByteBufferUtil.bytes("x"), cc.create(NodeId.fromInt(1), 2L, 3L, false), 1L,
            Long.MIN_VALUE);
    right = new CounterColumn(ByteBufferUtil.bytes("x"), cc.create(NodeId.fromInt(1), 1L, 1L, false), 4L, 3L);

    assert left.reconcile(right) == right;

    // live last delete > live
    left = new CounterColumn(ByteBufferUtil.bytes("x"), cc.create(NodeId.fromInt(1), 2L, 3L, false), 6L, 5L);
    right = new CounterColumn(ByteBufferUtil.bytes("x"), cc.create(NodeId.fromInt(1), 1L, 1L, false), 4L, 3L);

    assert left.reconcile(right) == left;

    // live + live
    left = new CounterColumn(ByteBufferUtil.bytes("x"), cc.create(NodeId.fromInt(1), 1L, 1L, false), 4L,
            Long.MIN_VALUE);
    right = new CounterColumn(ByteBufferUtil.bytes("x"), cc.create(NodeId.fromInt(1), 2L, 3L, false), 1L,
            Long.MIN_VALUE);

    reconciled = left.reconcile(right);
    assert reconciled.name().equals(left.name());
    assert ((CounterColumn) reconciled).total() == 3L;
    assert reconciled.timestamp() == 4L;

    left = reconciled;
    right = new CounterColumn(ByteBufferUtil.bytes("x"), cc.create(NodeId.fromInt(2), 1L, 5L, false), 2L,
            Long.MIN_VALUE);

    reconciled = left.reconcile(right);
    assert reconciled.name().equals(left.name());
    assert ((CounterColumn) reconciled).total() == 8L;
    assert reconciled.timestamp() == 4L;

    left = reconciled;
    right = new CounterColumn(ByteBufferUtil.bytes("x"), cc.create(NodeId.fromInt(2), 2L, 2L, false), 6L,
            Long.MIN_VALUE);

    reconciled = left.reconcile(right);
    assert reconciled.name().equals(left.name());
    assert ((CounterColumn) reconciled).total() == 5L;
    assert reconciled.timestamp() == 6L;

    context = reconciled.value();
    int hd = 2; // header
    assert hd + 2 * stepLength == context.remaining();

    assert Util.equalsNodeId(NodeId.fromInt(1), context, hd + 0 * stepLength);
    assert 2L == context.getLong(hd + 0 * stepLength + idLength);
    assert 3L == context.getLong(hd + 0 * stepLength + idLength + clockLength);

    assert Util.equalsNodeId(NodeId.fromInt(2), context, hd + 1 * stepLength);
    assert 2L == context.getLong(hd + 1 * stepLength + idLength);
    assert 2L == context.getLong(hd + 1 * stepLength + idLength + clockLength);

    assert ((CounterColumn) reconciled).timestampOfLastDelete() == Long.MIN_VALUE;
}