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();

Source Link

Document

Returns the long at the current position and increases the position by 8.

Usage

From source file:com.google.cloud.bigtable.hbase.TestIncrement.java

/**
 * Requirement 6.6/*from  w w  w .  j  a v a  2 s .c om*/
 */
@Test
public void testIncrementEightBytes() throws IOException {
    // Initialize
    Table table = getConnection().getTable(TABLE_NAME);
    byte[] rowKey = dataHelper.randomData("testrow-");
    byte[] qual = dataHelper.randomData("qual-");
    byte[] value = new byte[8];
    new Random().nextBytes(value);
    ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE);
    buffer.put(value);
    buffer.flip();
    long equivalentValue = buffer.getLong();

    // Put the bytes in
    Put put = new Put(rowKey).addColumn(COLUMN_FAMILY, qual, value);
    table.put(put);

    // Increment
    Increment increment = new Increment(rowKey).addColumn(COLUMN_FAMILY, qual, 1L);
    Result result = table.increment(increment);
    Assert.assertEquals("Should have incremented the bytes like a long", equivalentValue + 1L,
            Bytes.toLong(CellUtil.cloneValue(result.getColumnLatestCell(COLUMN_FAMILY, qual))));
}

From source file:io.stallion.dataAccess.file.FilePersisterBase.java

/**
 * Derives a Long id by hashing the file path and then taking the first 8 bytes
 * of the path./*  ww  w .  j ava 2s .c  o m*/
 *
 * This is used if the model object doesn't have a defined id field.
 *
 * @param path
 * @return
 */
public Long makeIdFromFilePath(String path) {
    path = path.toLowerCase();
    path = path.replace(getBucketFolderPath().toLowerCase(), "");
    path = StringUtils.stripStart(path, "/");
    path = getBucket() + "-----" + path;
    // Derive a long id by hashing the file path
    byte[] bs = Arrays.copyOfRange(DigestUtils.md5(path), 0, 6);
    bs = ArrayUtils.addAll(new byte[] { 0, 0 }, bs);
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    buffer.put(bs);
    buffer.flip();//need flip
    Long l = buffer.getLong();
    if (l < 0) {
        l = -l;
    }
    Log.finest("calculated id is {0}", l);
    return l;
}

From source file:com.netflix.aegisthus.pig.AegisthusLoadCaster.java

private long getNumber(byte[] arg0) throws Exception {
    byte[] by = hex.decode(arg0);
    ByteBuffer bb = ByteBuffer.allocate(by.length);
    bb.put(by);/*w  w  w.  j  a v  a  2 s.  co m*/
    bb.position(0);
    switch (by.length) {
    case 1:
        return (long) bb.get();
    case 2:
        return (long) bb.getShort();
    case 4:
        return (long) bb.getInt();
    case 8:
        return (long) bb.getLong();
    }
    throw new UnexpectedException("couldn't determine datatype");
}

From source file:com.yahoo.omid.tso.persistence.BookKeeperStateBuilder.java

/**
 * Builds state from a ledger.//from   ww  w. j a  v a 2s.co  m
 * 
 * 
 * @param data
 * @param ctx
 * @return
 */
private void buildStateFromLedger(byte[] data, Object ctx) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Building state from ledger");
    }

    if (data == null) {
        LOG.error("No data on znode, can't determine ledger id");
        ((BookKeeperStateBuilder.Context) ctx).setState(null);
    }

    /*
     * Instantiates LoggerProtocol        
     */
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating logger protocol object");
    }
    try {
        this.lp = new LoggerProtocol(timestampOracle);
    } catch (Exception e) {
        LOG.error("Error while creating state logger for logger protocol.", e);
        ((BookKeeperStateBuilder.Context) ctx).setState(null);
    }

    /*
     * Open ledger for reading.
     */

    ByteBuffer bb = ByteBuffer.wrap(data);
    long ledgerId = bb.getLong();

    bk.asyncOpenLedger(ledgerId, BookKeeper.DigestType.CRC32, "flavio was here".getBytes(), new OpenCallback() {
        public void openComplete(int rc, LedgerHandle lh, Object ctx) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Open complete, ledger id: " + lh.getId());
            }
            if (rc != BKException.Code.OK) {
                LOG.error("Could not open ledger for reading." + BKException.getMessage(rc));
                ((BookKeeperStateBuilder.Context) ctx).setState(null);
            } else {
                long counter = lh.getLastAddConfirmed();
                while (counter >= 0) {
                    try {
                        throttleReads.acquire();
                    } catch (InterruptedException e) {
                        LOG.error("Couldn't build state", e);
                        ((Context) ctx).abort();
                        break;
                    }
                    if (((Context) ctx).isReady())
                        break;
                    ((Context) ctx).incrementPending();
                    long nextBatch = Math.max(counter - BKREADBATCHSIZE + 1, 0);
                    lh.asyncReadEntries(nextBatch, counter, new LoggerExecutor(), ctx);
                    counter -= BKREADBATCHSIZE;
                }
            }
        }
    }, ctx);

}

From source file:org.projectnyx.network.mcpe.raknet.RakNetInterface.java

private void handleDataPacket(RawDataPacket packet) {
    ByteBuffer buffer = ByteBuffer.wrap(packet.buffer).order(ByteOrder.BIG_ENDIAN);
    byte pid = buffer.get();

    if (pid == DATA_PING) {
        long pingId = buffer.getLong();
        Pong pong = new Pong();
        pong.pingId = pingId;//from w  w  w . j a  v a  2  s . co m
        RawDataPacket pk = new RawDataPacket();
        pk.reliability = 0;
        pk.buffer = pong.write().array();
        queueDataPacket(pk);
        return;
    }
    if (pid == DATA_PONG) {
        long pingId = buffer.getLong();
        Ping ping = pingMap.remove(pingId);
        if (ping == null) {
            Nyx.getLog().error(String.format("Client from %s sent PONG with unknown ping ID %d",
                    client.getAddress(), pingId));
            return;
        }
        client.getPingStats().addDatum(ping.sendTimeNano, true);
        return;
    }
    if (pid == DATA_CLIENT_DISCONNECT) {
        client.close(Client.CloseReason.CLIENT_DISCONNECT);
    }

    if (client.getLoginStep() == LOGIN_STEP_WAIT_CONNECT) {
        if (pid != DATA_CLIENT_CONENCT) {
            client.unexpectedPacket(packet);
            return;
        }
        ClientConnect request = new ClientConnect(buffer);
        ServerHandshake response = new ServerHandshake();
        response.address = client.getSession().getAddress();
        response.ping = request.pingTime;
        response.pong = request.pingTime + 1000;
        RawDataPacket pk = new RawDataPacket();
        pk.reliability = 0;
        pk.buffer = response.write().array();
        queueDataPacket(pk);
        flushDataPacketQueue();
        client.setLoginStep(LOGIN_STEP_WAIT_HANDSHAKE);
    } else if (client.getLoginStep() == LOGIN_STEP_WAIT_HANDSHAKE) {
        if (pid != DATA_CLIENT_HANDSHAKE) {
            client.unexpectedPacket(packet);
            return;
        }
        ClientHandshake handshake = new ClientHandshake(buffer);
        // TODO log referrer?
        // TODO check port?
        client.setLoginStep(LOGIN_STEP_IN_GAME);
        Nyx.getLog().debug(String.format("Client %s is now logging in!", client.getAddress()));
    } else if (client.getLoginStep() != LOGIN_STEP_IN_GAME) {
        client.unexpectedPacket(packet);
    } else {
        if (pid != RakNetConsts.DATA_MCPE) {
            client.unexpectedPacket(packet);
            return;
        }

        client.handleDataPacket(buffer);
    }
}

From source file:io.v.android.libs.discovery.ble.BlePlugin.java

private void updateScanning() {
    if (isScanning && scanCancellationThreads.size() == 0) {
        isScanning = false;/*from   w w w. j a v  a  2s .  co m*/
        bluetoothLeScanner.stopScan(scanCallback);
        return;
    }

    if (!isScanning && scanCancellationThreads.size() > 0) {
        isScanning = true;
        ScanFilter.Builder builder = new ScanFilter.Builder();
        byte[] manufacturerData = {};
        byte[] manufacturerMask = {};

        builder.setManufacturerData(1001, manufacturerData, manufacturerMask);
        final List<ScanFilter> scanFilter = new ArrayList<>();
        scanFilter.add(builder.build());

        scanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                // in L the only value for callbackType is CALLBACK_TYPE_ALL_MATCHES, so
                // we don't look at its value.
                ScanRecord record = result.getScanRecord();
                // Use 1001 to denote that this is a Vanadium device.  We picked an id that is
                // currently not in use.
                byte[] data = record.getManufacturerSpecificData(1001);
                ByteBuffer buffer = ByteBuffer.wrap(data);
                final long hash = buffer.getLong();
                final String deviceId = result.getDevice().getAddress();
                if (cachedDevices.haveSeenHash(hash, deviceId)) {
                    return;
                }
                synchronized (scannerLock) {
                    if (pendingCalls.contains(deviceId)) {
                        Log.d("vanadium", "not connecting to " + deviceId + " because of pending connection");
                        return;
                    }
                    pendingCalls.add(deviceId);
                }
                BluetoothGattClientCallback.Callback ccb = new BluetoothGattClientCallback.Callback() {
                    @Override
                    public void handle(Map<UUID, Map<UUID, byte[]>> services) {
                        Set<Advertisement> advs = new HashSet<>();
                        for (Map.Entry<UUID, Map<UUID, byte[]>> entry : services.entrySet()) {
                            try {
                                Advertisement adv = BleAdvertisementConverter
                                        .bleAttrToVAdvertisement(entry.getValue());
                                advs.add(adv);
                            } catch (IOException e) {
                                Log.e("vanadium", "Failed to convert advertisement" + e);
                            }
                        }
                        cachedDevices.saveDevice(hash, advs, deviceId);
                        synchronized (scannerLock) {
                            pendingCalls.remove(deviceId);
                        }
                        bluetoothLeScanner.startScan(scanFilter,
                                new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).build(),
                                scanCallback);
                    }
                };
                BluetoothGattClientCallback cb = new BluetoothGattClientCallback(ccb);
                bluetoothLeScanner.stopScan(scanCallback);
                Log.d("vanadium", "connecting to " + result.getDevice());
                result.getDevice().connectGatt(androidContext, false, cb);
            }

            @Override
            public void onBatchScanResults(List<ScanResult> results) {
            }

            @Override
            public void onScanFailed(int errorCode) {
            }
        };
        bluetoothLeScanner.startScan(scanFilter,
                new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).build(), scanCallback);
    }
}

From source file:au.org.ala.delta.io.BinFile.java

public long readLong() {
    ByteBuffer b = readByteBuffer(8);
    _stats.ReadLong++;
    return b.getLong();
}

From source file:com.yahoo.omid.tso.persistence.LoggerProtocol.java

/**
 * Execute a logged entry (several logged ops)
 * @param bb Serialized operations//w ww  .ja  v a2  s .c o m
 */
void execute(ByteBuffer bb) {
    boolean done = !bb.hasRemaining();
    while (!done) {
        byte op = bb.get();
        long timestamp, startTimestamp, commitTimestamp;
        if (LOG.isTraceEnabled()) {
            LOG.trace("Operation: " + op);
        }
        switch (op) {
        case TIMESTAMPORACLE:
            timestamp = bb.getLong();
            this.getSO().initialize(timestamp);
            this.initialize();
            oracle = true;
            break;
        case COMMIT:
            startTimestamp = bb.getLong();
            commitTimestamp = bb.getLong();
            processCommit(startTimestamp, commitTimestamp);
            if (commitTimestamp < largestDeletedTimestamp) {
                commits = true;
            }
            break;
        case LARGESTDELETEDTIMESTAMP:
            timestamp = bb.getLong();
            processLargestDeletedTimestamp(timestamp);

            break;
        case ABORT:
            timestamp = bb.getLong();
            processAbort(timestamp);

            break;
        case FULLABORT:
            timestamp = bb.getLong();
            processFullAbort(timestamp);

            break;
        case LOGSTART:
            consumed = true;
            break;
        case SNAPSHOT:
            int snapshot = (int) bb.getLong();
            if (snapshot > this.snapshot) {
                this.snapshot = snapshot;
                this.hasSnapshot = true;
            }
            if (hasSnapshot && snapshot < this.snapshot) {
                this.aborts = true;
            }
            break;
        }
        if (bb.remaining() == 0)
            done = true;
    }
}

From source file:com.codefollower.lealone.omid.tso.persistence.LoggerProtocol.java

/**
 * Execute a logged entry (several logged ops)
 * @param bb Serialized operations/*from ww w .j a va 2  s  .com*/
 */
void execute(ByteBuffer bb) {
    boolean done = !bb.hasRemaining();
    while (!done) {
        byte op = bb.get();
        long timestamp, startTimestamp, commitTimestamp;
        if (LOG.isTraceEnabled()) {
            LOG.trace("Operation: " + op);
        }
        switch (op) {
        case TIMESTAMP_ORACLE:
            timestamp = bb.getLong();
            this.getTimestampOracle().initialize(timestamp);
            this.initialize();
            oracle = true;
            break;
        case COMMIT:
            startTimestamp = bb.getLong();
            commitTimestamp = bb.getLong();
            processCommit(startTimestamp, commitTimestamp);
            if (commitTimestamp < largestDeletedTimestamp) {
                commits = true;
            }
            break;
        case LARGEST_DELETED_TIMESTAMP:
            timestamp = bb.getLong();
            processLargestDeletedTimestamp(timestamp);

            break;
        case ABORT:
            timestamp = bb.getLong();
            processHalfAbort(timestamp);

            break;
        case FULL_ABORT:
            timestamp = bb.getLong();
            processFullAbort(timestamp);

            break;
        case LOG_START:
            consumed = true;
            break;
        case SNAPSHOT:
            int snapshot = (int) bb.getLong();
            if (snapshot > this.snapshot) {
                this.snapshot = snapshot;
                this.hasSnapshot = true;
            }
            if (hasSnapshot && snapshot < this.snapshot) {
                this.aborts = true;
            }
            break;
        }
        if (bb.remaining() == 0)
            done = true;
    }
}

From source file:org.wso2.carbon.analytics.datasource.core.util.GenericUtils.java

public static Map<String, Object> decodeRecordValues(byte[] data, Set<String> columns)
        throws AnalyticsException {
    /* using LinkedHashMap to retain the column order */
    Map<String, Object> result = new LinkedHashMap<>();
    int type, size;
    String colName;/*from   w  w w  .j a v a 2 s.  c  o  m*/
    Object value;
    byte[] buff;
    byte boolVal;
    byte[] binData;
    try {
        ByteBuffer buffer = ByteBuffer.wrap(data);
        while (buffer.remaining() > 0) {
            size = buffer.getInt();
            if (size == 0) {
                break;
            }
            buff = new byte[size];
            buffer.get(buff, 0, size);
            colName = new String(buff, StandardCharsets.UTF_8);
            type = buffer.get();
            switch (type) {
            case DATA_TYPE_STRING:
                size = buffer.getInt();
                buff = new byte[size];
                buffer.get(buff, 0, size);
                value = new String(buff, StandardCharsets.UTF_8);
                break;
            case DATA_TYPE_LONG:
                value = buffer.getLong();
                break;
            case DATA_TYPE_DOUBLE:
                value = buffer.getDouble();
                break;
            case DATA_TYPE_BOOLEAN:
                boolVal = buffer.get();
                if (boolVal == BOOLEAN_TRUE) {
                    value = true;
                } else if (boolVal == BOOLEAN_FALSE) {
                    value = false;
                } else {
                    throw new AnalyticsException("Invalid encoded boolean value: " + boolVal);
                }
                break;
            case DATA_TYPE_INTEGER:
                value = buffer.getInt();
                break;
            case DATA_TYPE_FLOAT:
                value = buffer.getFloat();
                break;
            case DATA_TYPE_BINARY:
                size = buffer.getInt();
                binData = new byte[size];
                buffer.get(binData);
                value = binData;
                break;
            case DATA_TYPE_OBJECT:
                size = buffer.getInt();
                binData = new byte[size];
                buffer.get(binData);
                value = GenericUtils.deserializeObject(binData);
                break;
            case DATA_TYPE_NULL:
                value = null;
                break;
            default:
                throw new AnalyticsException("Unknown encoded data source type : " + type);
            }
            if (columns == null || columns.contains(colName)) {
                result.put(colName, value);
            }
        }
    } catch (Exception e) {
        throw new AnalyticsException("Error in decoding record values: " + e.getMessage(), e);
    }
    return result;
}