Example usage for java.nio ByteBuffer putLong

List of usage examples for java.nio ByteBuffer putLong

Introduction

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

Prototype

public abstract ByteBuffer putLong(long value);

Source Link

Document

Writes the given long to the current position and increases the position by 8.

Usage

From source file:edu.tsinghua.lumaqq.qq.packets.out._05.TransferPacket.java

@Override
protected void putBody(ByteBuffer buf) {
    if (!requestSend) {
        // 2. 8/*w  w w . ja  va  2s .  c  o m*/
        buf.putLong(0x0100000000000000L);
        // 3. session id, 4           
        buf.putInt(sessionId);
        // 4
        buf.putInt(0);
        // ??
        if (dataReply) {
            buf.putChar((char) 0x0001);
            buf.put((byte) 0x02);
        } else {
            buf.putChar((char) 0x04);
            buf.putInt(0);
        }
    } else if (data) {
        // 2. 8??0x1000000000000001?
        if (last)
            buf.putLong(0x0100000000000000L);
        else
            buf.putLong(0x0100000000000001L);
        // 3. session id, 4
        buf.putInt(sessionId);
        // 4. 4
        buf.putInt(0);
        // 5. ?2
        buf.putChar((char) fragment.length);
        // 6. ?
        buf.put(fragment);
    } else {
        // 2. 8
        buf.putLong(0x0100000000000000L);
        // 3. session id, 4
        buf.putInt(sessionId);
        // 4. 4
        buf.putInt(0);
        // 5. ???2
        buf.putChar((char) 0);
        // 6. 25?
        int pos = buf.position();
        buf.putChar((char) 0);
        // 7. md5
        buf.put(md5);
        // 8. ??md5
        byte[] fileNameBytes = fileName.getBytes();
        buf.put(md5(fileNameBytes));
        // 9. 4
        buf.putInt(imageLength);
        // 10. ??2
        buf.putChar((char) fileName.length());
        // 11. ??
        buf.put(fileNameBytes);
        // 12. 8
        buf.putLong(0);

        char len = (char) (buf.position() - pos);
        buf.putChar(pos - 2, len);
        buf.putChar(pos, len);
    }
}

From source file:voldemort.store.cachestore.impl.LogChannel.java

private void writeIndexBlock(long keyOffset2Len, int record, long dataOffset2Len, short nodeId,
        long block2Version, byte status) throws IOException {
    long pos = OFFSET + (long) record * RECORD_SIZE;
    checkFileSize(pos, RECORD_SIZE);/*w  w  w  .ja v a  2s . co  m*/
    ByteBuffer buf = ByteBuffer.allocate(RECORD_SIZE);
    buf.put(status);
    buf.putLong(keyOffset2Len);
    buf.putLong(dataOffset2Len);
    buf.putLong(block2Version);
    buf.putShort(nodeId);
    buf.flip();
    getIndexChannel().write(buf, pos);
}

From source file:com.btoddb.fastpersitentqueue.flume.FpqChannelTest.java

@Test
public void testThreading() throws Exception {
    final int numEntries = 1000;
    final int numPushers = 4;
    final int numPoppers = 4;
    final int entrySize = 1000;
    channel.setMaxTransactionSize(2000);
    final int popBatchSize = 100;
    channel.setMaxMemorySegmentSizeInBytes(10000000);
    channel.setMaxJournalFileSize(10000000);
    channel.setMaxJournalDurationInMs(30000);
    channel.setFlushPeriodInMs(1000);/*from www .j  a  v  a 2  s .co  m*/
    channel.setNumberOfFlushWorkers(4);

    final Random pushRand = new Random(1000L);
    final Random popRand = new Random(1000000L);
    final AtomicInteger pusherFinishCount = new AtomicInteger();
    final AtomicInteger numPops = new AtomicInteger();
    final AtomicLong counter = new AtomicLong();
    final AtomicLong pushSum = new AtomicLong();
    final AtomicLong popSum = new AtomicLong();

    channel.start();

    ExecutorService execSrvc = Executors.newFixedThreadPool(numPushers + numPoppers);

    Set<Future> futures = new HashSet<Future>();

    // start pushing
    for (int i = 0; i < numPushers; i++) {
        Future future = execSrvc.submit(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < numEntries; i++) {
                    try {
                        long x = counter.getAndIncrement();
                        pushSum.addAndGet(x);
                        ByteBuffer bb = ByteBuffer.wrap(new byte[entrySize]);
                        bb.putLong(x);

                        Transaction tx = channel.getTransaction();
                        tx.begin();
                        MyEvent event1 = new MyEvent();
                        event1.addHeader("x", String.valueOf(x)).setBody(new byte[numEntries - 8]); // take out size of long
                        channel.put(event1);
                        tx.commit();
                        tx.close();

                        Thread.sleep(pushRand.nextInt(5));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                pusherFinishCount.incrementAndGet();
            }
        });
        futures.add(future);
    }

    // start popping
    for (int i = 0; i < numPoppers; i++) {
        Future future = execSrvc.submit(new Runnable() {
            @Override
            public void run() {
                while (pusherFinishCount.get() < numPushers || !channel.isEmpty()) {
                    try {
                        Transaction tx = channel.getTransaction();
                        tx.begin();

                        Event event;
                        int count = popBatchSize;
                        while (null != (event = channel.take()) && count-- > 0) {
                            popSum.addAndGet(Long.valueOf(event.getHeaders().get("x")));
                            numPops.incrementAndGet();
                        }

                        tx.commit();
                        tx.close();

                        Thread.sleep(popRand.nextInt(10));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        futures.add(future);
    }

    boolean finished = false;
    while (!finished) {
        try {
            for (Future f : futures) {
                f.get();
            }
            finished = true;
        } catch (InterruptedException e) {
            // ignore
            Thread.interrupted();
        }
    }

    assertThat(numPops.get(), is(numEntries * numPushers));
    assertThat(channel.isEmpty(), is(true));
    assertThat(pushSum.get(), is(popSum.get()));
}

From source file:com.sm.connector.server.ServerStore.java

private void writeIndexBlock(CacheBlock<byte[]> block, long keyOffset2Len, FileChannel channel)
        throws IOException {
    long pos = OFFSET + (long) block.getRecordNo() * RECORD_SIZE;
    checkFileSize(pos, RECORD_SIZE);//from   ww  w .j  a  v a  2s  .c om
    ByteBuffer buf = ByteBuffer.allocate(RECORD_SIZE);
    buf.put(block.getStatus());
    buf.putLong(keyOffset2Len);
    buf.putLong(block.getDataOffset2Len());
    buf.putLong(block.getBlock2Version());
    buf.putShort(block.getNode());
    buf.flip();
    channel.write(buf, pos);
}

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

private void readvertise() {
    if (advertiseCallback != null) {
        bluetoothLeAdvertise.stopAdvertising(advertiseCallback);
        advertiseCallback = null;//from   w w  w .  ja  v a  2s. c o  m
    }
    if (advertisements.size() == 0) {
        return;
    }

    int hash = advertisements.hashCode();

    AdvertiseData.Builder builder = new AdvertiseData.Builder();
    ByteBuffer buf = ByteBuffer.allocate(9);
    buf.put((byte) 8);
    buf.putLong(hash);
    builder.addManufacturerData(1001, buf.array());
    AdvertiseSettings.Builder settingsBuilder = new AdvertiseSettings.Builder();
    settingsBuilder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY);
    settingsBuilder.setConnectable(true);
    advertiseCallback = new AdvertiseCallback() {
        @Override
        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
            Log.i("vanadium", "Successfully started " + settingsInEffect);
        }

        @Override
        public void onStartFailure(int errorCode) {
            Log.i("vanadium", "Failed to start advertising " + errorCode);
        }
    };
    bluetoothLeAdvertise.startAdvertising(settingsBuilder.build(), builder.build(), advertiseCallback);
}

From source file:mobisocial.musubi.nearby.GpsBroadcastTask.java

@Override
protected Void doInBackground(Void... params) {
    if (DBG)/*from ww w  .  j a  v a  2  s  . c  o m*/
        Log.d(TAG, "Uploading group for nearby gps...");
    while (!mmLocationScanComplete) {
        synchronized (mmLocationResult) {
            if (!mmLocationScanComplete) {
                try {
                    if (DBG)
                        Log.d(TAG, "Waiting for location results...");
                    mmLocationResult.wait();
                } catch (InterruptedException e) {
                }
            }
        }
    }
    if (DBG)
        Log.d(TAG, "Got location " + mmLocation);
    if (isCancelled()) {
        return null;
    }

    try {
        SQLiteOpenHelper db = App.getDatabaseSource(mContext);
        FeedManager fm = new FeedManager(db);
        IdentitiesManager im = new IdentitiesManager(db);
        String group_name = UiUtil.getFeedNameFromMembersList(fm, mFeed);
        byte[] group_capability = mFeed.capability_;
        List<MIdentity> owned = im.getOwnedIdentities();
        MIdentity sharer = null;
        for (MIdentity i : owned) {
            if (i.type_ != Authority.Local) {
                sharer = i;
                break;
            }
        }
        String sharer_name = UiUtil.safeNameForIdentity(sharer);
        byte[] sharer_hash = sharer.principalHash_;

        byte[] thumbnail = fm.getFeedThumbnailForId(mFeed.id_);
        if (thumbnail == null)
            thumbnail = im.getMusubiThumbnail(sharer) != null ? sharer.musubiThumbnail_
                    : im.getThumbnail(sharer);
        int member_count = fm.getFeedMemberCount(mFeed.id_);

        JSONObject group = new JSONObject();
        group.put("group_name", group_name);
        group.put("group_capability", Base64.encodeToString(group_capability, Base64.DEFAULT));
        group.put("sharer_name", sharer_name);
        group.put("sharer_type", sharer.type_.ordinal());
        group.put("sharer_hash", Base64.encodeToString(sharer_hash, Base64.DEFAULT));
        if (thumbnail != null)
            group.put("thumbnail", Base64.encodeToString(thumbnail, Base64.DEFAULT));
        group.put("member_count", member_count);

        byte[] key = Util.sha256(("happysalt621" + mmPassword).getBytes());
        byte[] data = group.toString().getBytes();
        byte[] iv = new byte[16];
        new SecureRandom().nextBytes(iv);

        byte[] partial_enc_data;
        Cipher cipher;
        AlgorithmParameterSpec iv_spec;
        SecretKeySpec sks;
        try {
            cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        } catch (Exception e) {
            throw new RuntimeException("AES not supported on this platform", e);
        }
        try {
            iv_spec = new IvParameterSpec(iv);
            sks = new SecretKeySpec(key, "AES");
            cipher.init(Cipher.ENCRYPT_MODE, sks, iv_spec);
        } catch (Exception e) {
            throw new RuntimeException("bad iv or key", e);
        }
        try {
            partial_enc_data = cipher.doFinal(data);
        } catch (Exception e) {
            throw new RuntimeException("body encryption failed", e);
        }

        TByteArrayList bal = new TByteArrayList(iv.length + partial_enc_data.length);
        bal.add(iv);
        bal.add(partial_enc_data);
        byte[] enc_data = bal.toArray();

        if (DBG)
            Log.d(TAG, "Posting to gps server...");

        Uri uri = Uri.parse("http://bumblebee.musubi.us:6253/nearbyapi/0/sharegroup");

        StringBuffer sb = new StringBuffer();
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(uri.toString());
        httpPost.addHeader("Content-Type", "application/json");
        JSONArray buckets = new JSONArray();
        JSONObject descriptor = new JSONObject();

        double lat = mmLocation.getLatitude();
        double lng = mmLocation.getLongitude();
        long[] coords = GridHandler.getGridCoords(lat, lng, 5280 / 2);
        for (long c : coords) {
            MessageDigest md;
            try {
                byte[] obfuscate = ("sadsalt193s" + mmPassword).getBytes();
                md = MessageDigest.getInstance("SHA-256");
                ByteBuffer b = ByteBuffer.allocate(8 + obfuscate.length);
                b.putLong(c);
                b.put(obfuscate);
                String secret_bucket = Base64.encodeToString(md.digest(b.array()), Base64.DEFAULT);
                buckets.put(buckets.length(), secret_bucket);
            } catch (NoSuchAlgorithmException e) {
                throw new RuntimeException("your platform does not support sha256", e);
            }
        }
        descriptor.put("buckets", buckets);
        descriptor.put("data", Base64.encodeToString(enc_data, Base64.DEFAULT));
        descriptor.put("expiration", new Date().getTime() + 1000 * 60 * 60);

        httpPost.setEntity(new StringEntity(descriptor.toString()));
        try {
            HttpResponse execute = client.execute(httpPost);
            InputStream content = execute.getEntity().getContent();
            BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
            String s = "";
            while ((s = buffer.readLine()) != null) {
                if (isCancelled()) {
                    return null;
                }
                sb.append(s);
            }
            if (sb.toString().equals("ok"))
                mSucceeded = true;
            else {
                System.err.println(sb);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //TODO: report failures etc
    } catch (Exception e) {
        Log.e(TAG, "Failed to broadcast group", e);
    }
    return null;
}

From source file:org.cosmo.common.util.Util.java

public static short[] longToShorts2(long value) {
    short[] shorts = new short[4];
    ByteBuffer b = ByteBuffer.allocate(8);
    b.putLong(value);

    b.rewind();/*from   w ww  .jav  a 2  s . c  o m*/
    shorts[0] = b.getShort();
    shorts[1] = b.getShort();
    shorts[2] = b.getShort();
    shorts[3] = b.getShort();
    return shorts;

}

From source file:org.apache.hadoop.hbase.filter.DirectoryRowFilter.java

/**
 * Serialize the filter//  w w  w. ja v  a2s  . c o  m
 */
@Override
public byte[] toByteArray() throws IOException {

    ByteBuffer bb = ByteBuffer.wrap(new byte[4 * 8]).order(ByteOrder.BIG_ENDIAN);

    bb.putLong(instanceModulus);
    bb.putLong(instanceRemainder);
    bb.putLong(threadModulus);
    bb.putLong(threadRemainder);

    return bb.array();
}

From source file:org.jboss.dashboard.workspace.WorkspacesManager.java

/**
 * Generate a unique workspace identifier
 *///from  w w w .j  a v  a  2s .com
public synchronized String generateWorkspaceId() throws Exception {
    UUID uuid = UUID.randomUUID();
    ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
    bb.putLong(uuid.getMostSignificantBits());
    bb.putLong(uuid.getLeastSignificantBits());
    return Base64.encodeBase64URLSafeString(bb.array());
}

From source file:com.openteach.diamond.network.waverider.network.Packet.java

/**
 * ByteBuffer/*from   w w w .j a  v  a2 s.  c  om*/
 * @return
 */
public ByteBuffer marshall() {
    int size = getSize();
    ByteBuffer buffer = ByteBuffer.allocate(size);
    buffer.put(magic.getBytes());
    buffer.putLong(sequence);
    buffer.putLong(type);
    buffer.putInt(size);
    buffer.put(payLoad);
    buffer.flip();
    return buffer;
}