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:org.springframework.amqp.rabbit.junit.BrokerRunning.java

/**
 * Generate the connection id for the connection used by the rule's
 * connection factory.//www  .j a  v a2s . c om
 * @return the id.
 */
public String generateId() {
    UUID uuid = UUID.randomUUID();
    ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
    bb.putLong(uuid.getMostSignificantBits()).putLong(uuid.getLeastSignificantBits());
    return "SpringBrokerRunning." + Base64Utils.encodeToUrlSafeString(bb.array()).replaceAll("=", "");
}

From source file:net.dv8tion.jda.core.audio.AudioWebSocket.java

private void setupKeepAlive(final int keepAliveInterval) {
    if (keepAliveHandle != null)
        LOG.fatal("Setting up a KeepAlive runnable while the previous one seems to still be active!!");

    Runnable keepAliveRunnable = () -> {
        if (socket.isOpen() && socket.isOpen() && !udpSocket.isClosed()) {
            send(new JSONObject().put("op", 3).put("d", System.currentTimeMillis()).toString());

            long seq = 0;
            try {
                ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES + 1);
                buffer.put((byte) 0xC9);
                buffer.putLong(seq);
                DatagramPacket keepAlivePacket = new DatagramPacket(buffer.array(), buffer.array().length,
                        address);//  w w w .  j a  v  a  2  s  .  c  o m
                udpSocket.send(keepAlivePacket);

            } catch (NoRouteToHostException e) {
                LOG.warn("Closing AudioConnection due to inability to ping audio packets.");
                LOG.warn("Cannot send audio packet because JDA navigate the route to Discord.\n"
                        + "Are you sure you have internet connection? It is likely that you've lost connection.");
                AudioWebSocket.this.close(ConnectionStatus.ERROR_LOST_CONNECTION);
            } catch (IOException e) {
                LOG.log(e);
            }
        }
    };

    try {
        keepAliveHandle = keepAlivePool.scheduleAtFixedRate(keepAliveRunnable, 0, keepAliveInterval,
                TimeUnit.MILLISECONDS);
    } catch (RejectedExecutionException ignored) {
    } //ignored because this is probably caused due to a race condition
      // related to the threadpool shutdown.
}

From source file:com.linkedin.pinot.core.startree.MmapLinkedListStarTreeTable.java

@Override
protected ByteBuffer toByteBuffer(StarTreeTableRow row) {
    ByteBuffer buffer = getNextBuffer();

    for (int i = 0; i < dimensionTypes.size(); i++) {
        buffer.putInt(row.getDimensions().get(i));
    }//from  w ww .j av  a  2  s  . c o m

    for (int i = 0; i < metricTypes.size(); i++) {
        switch (metricTypes.get(i)) {
        case SHORT:
            buffer.putShort(row.getMetrics().get(i).shortValue());
            break;
        case INT:
            buffer.putInt(row.getMetrics().get(i).intValue());
            break;
        case LONG:
            buffer.putLong(row.getMetrics().get(i).longValue());
            break;
        case FLOAT:
            buffer.putFloat(row.getMetrics().get(i).floatValue());
            break;
        case DOUBLE:
            buffer.putDouble(row.getMetrics().get(i).doubleValue());
            break;
        default:
            throw new IllegalArgumentException("Unsupported metric type " + metricTypes.get(i));
        }
    }

    return buffer;
}

From source file:xbird.storage.io.RemoteVarSegments.java

private void sendRequest(final ByteChannel channel, final long... idxs) throws IOException {
    byte[] bFilePath = StringUtils.getBytes(_filePath);
    final int size = idxs.length;
    int buflen = bFilePath.length + 16 + (Primitives.LONG_BYTES * size);//+ 4 + 4 + 4 + 4 + 8n;
    if (buflen > RemotePagingService.MAX_COMMAND_BUFLEN) {
        throw new IllegalStateException("command size exceeds limit in MAX_COMMAND_BUFLEN("
                + RemotePagingService.MAX_COMMAND_BUFLEN + "): " + buflen + " bytes");
    }//from  w  w w.j a v a 2 s.c o m
    ByteBuffer oprBuf = ByteBuffer.allocate(buflen);
    oprBuf.putInt(buflen - 4);
    oprBuf.putInt(RemotePagingService.COMMAND_TRACK_READ);
    oprBuf.putInt(bFilePath.length); // #1
    oprBuf.put(bFilePath); // #2
    oprBuf.putInt(size); // #3
    for (int i = 0; i < size; i++) {
        oprBuf.putLong(idxs[i]); // #4
    }
    oprBuf.flip();
    NIOUtils.writeFully(channel, oprBuf);
}

From source file:org.opendaylight.lispflowmapping.lisp.serializer.MapNotifySerializer.java

public ByteBuffer serialize(MapNotify mapNotify) {
    int size = Length.HEADER_SIZE;
    if (mapNotify.getAuthenticationData() != null) {
        size += mapNotify.getAuthenticationData().length;
    }/*from w  w  w  . java2 s . c o m*/
    if (mapNotify.isXtrSiteIdPresent() != null && mapNotify.isXtrSiteIdPresent()) {
        size += org.opendaylight.lispflowmapping.lisp.serializer.MapRegisterSerializer.Length.XTRID_SIZE
                + org.opendaylight.lispflowmapping.lisp.serializer.MapRegisterSerializer.Length.SITEID_SIZE;
    }
    for (MappingRecordItem mappingRecord : mapNotify.getMappingRecordItem()) {
        size += MappingRecordSerializer.getInstance().getSerializationSize(mappingRecord.getMappingRecord());
    }

    ByteBuffer replyBuffer = ByteBuffer.allocate(size);
    replyBuffer.put((byte) (MessageType.MapNotify.getIntValue() << 4));
    replyBuffer.position(replyBuffer.position() + Length.RES);
    replyBuffer.put(ByteUtil.boolToBit(BooleanUtils.isTrue(mapNotify.isMergeEnabled()), Flags.MERGE_ENABLED));
    if (mapNotify.getMappingRecordItem() != null) {
        replyBuffer.put((byte) mapNotify.getMappingRecordItem().size());
    } else {
        replyBuffer.put((byte) 0);
    }
    replyBuffer.putLong(NumberUtil.asLong(mapNotify.getNonce()));
    replyBuffer.putShort(NumberUtil.asShort(mapNotify.getKeyId()));
    if (mapNotify.getAuthenticationData() != null) {
        replyBuffer.putShort((short) mapNotify.getAuthenticationData().length);
        replyBuffer.put(mapNotify.getAuthenticationData());
    } else {
        replyBuffer.putShort((short) 0);
    }

    if (mapNotify.getMappingRecordItem() != null) {
        for (MappingRecordItem mappingRecord : mapNotify.getMappingRecordItem()) {
            MappingRecordSerializer.getInstance().serialize(replyBuffer, mappingRecord.getMappingRecord());
        }
    }

    if (mapNotify.isXtrSiteIdPresent() != null && mapNotify.isXtrSiteIdPresent()) {
        replyBuffer.put(mapNotify.getXtrId().getValue());
        replyBuffer.put(mapNotify.getSiteId().getValue());
    }
    replyBuffer.clear();
    return replyBuffer;
}

From source file:org.opendaylight.lispflowmapping.implementation.serializer.MapReplySerializer.java

public ByteBuffer serialize(MapReply mapReply) {
    int size = Length.HEADER_SIZE;
    for (EidToLocatorRecord eidToLocatorRecord : mapReply.getEidToLocatorRecord()) {
        size += EidToLocatorRecordSerializer.getInstance().getSerializationSize(eidToLocatorRecord);
    }/* www  . j  av  a2s.  c  o  m*/

    ByteBuffer replyBuffer = ByteBuffer.allocate(size);

    replyBuffer.put((byte) ((LispMessageEnum.MapReply.getValue() << 4) | //
            (BooleanUtils.isTrue(mapReply.isProbe()) ? Flags.PROBE : 0x00) | //
            (BooleanUtils.isTrue(mapReply.isEchoNonceEnabled()) ? Flags.ECHO_NONCE_ENABLED : 0x00)));

    replyBuffer.position(replyBuffer.position() + Length.RES);
    if (mapReply.getEidToLocatorRecord() != null) {
        replyBuffer.put((byte) mapReply.getEidToLocatorRecord().size());
    } else {
        replyBuffer.put((byte) 0);

    }
    replyBuffer.putLong(NumberUtil.asLong(mapReply.getNonce()));
    if (mapReply.getEidToLocatorRecord() != null) {
        for (EidToLocatorRecord eidToLocatorRecord : mapReply.getEidToLocatorRecord()) {
            EidToLocatorRecordSerializer.getInstance().serialize(replyBuffer, eidToLocatorRecord);
        }
    }
    return replyBuffer;
}

From source file:org.opendaylight.lispflowmapping.lisp.serializer.MapReplySerializer.java

public ByteBuffer serialize(MapReply mapReply) {
    int size = Length.HEADER_SIZE;
    for (MappingRecordItem eidToLocatorRecord : mapReply.getMappingRecordItem()) {
        size += MappingRecordSerializer.getInstance()
                .getSerializationSize(eidToLocatorRecord.getMappingRecord());
    }/*from   www. ja va2s.c  om*/

    ByteBuffer replyBuffer = ByteBuffer.allocate(size);

    replyBuffer.put((byte) ((MessageType.MapReply.getIntValue() << 4) | //
            (BooleanUtils.isTrue(mapReply.isProbe()) ? Flags.PROBE : 0x00) | //
            (BooleanUtils.isTrue(mapReply.isEchoNonceEnabled()) ? Flags.ECHO_NONCE_ENABLED : 0x00)));

    replyBuffer.position(replyBuffer.position() + Length.RES);
    if (mapReply.getMappingRecordItem() != null) {
        replyBuffer.put((byte) mapReply.getMappingRecordItem().size());
    } else {
        replyBuffer.put((byte) 0);

    }
    replyBuffer.putLong(NumberUtil.asLong(mapReply.getNonce()));
    if (mapReply.getMappingRecordItem() != null) {
        for (MappingRecordItem eidToLocatorRecord : mapReply.getMappingRecordItem()) {
            MappingRecordSerializer.getInstance().serialize(replyBuffer, eidToLocatorRecord.getMappingRecord());
        }
    }
    return replyBuffer;
}

From source file:com.btoddb.fastpersitentqueue.FpqIT.java

@Test
public void testThreading() throws Exception {
    final int numEntries = 1000;
    final int numPushers = 4;
    final int numPoppers = 4;
    final int entrySize = 1000;
    fpq1.setMaxTransactionSize(2000);// ww w  . j av a  2s  .  c  o m
    final int popBatchSize = 100;
    fpq1.setMaxMemorySegmentSizeInBytes(10000000);
    fpq1.setMaxJournalFileSize(10000000);
    fpq1.setMaxJournalDurationInMs(30000);
    fpq1.setFlushPeriodInMs(1000);
    fpq1.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();

    fpq1.init();

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

                        fpq1.beginTransaction();
                        fpq1.push(bb.array());
                        fpq1.commit();
                        if ((x + 1) % 500 == 0) {
                            System.out.println("pushed ID = " + x);
                        }
                        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 || !fpq1.isEmpty()) {
                    try {
                        fpq1.beginTransaction();
                        try {
                            Collection<FpqEntry> entries = fpq1.pop(popBatchSize);
                            if (null == entries) {
                                Thread.sleep(100);
                                continue;
                            }

                            for (FpqEntry entry : entries) {
                                ByteBuffer bb = ByteBuffer.wrap(entry.getData());
                                popSum.addAndGet(bb.getLong());
                                if (entry.getId() % 500 == 0) {
                                    System.out.println("popped ID = " + entry.getId());
                                }
                            }
                            numPops.addAndGet(entries.size());
                            fpq1.commit();
                            entries.clear();
                        } finally {
                            if (fpq1.isTransactionActive()) {
                                fpq1.rollback();
                            }
                        }
                        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(fpq1.getNumberOfEntries(), is(0L));
    assertThat(pushSum.get(), is(popSum.get()));
    assertThat(fpq1.getMemoryMgr().getNumberOfActiveSegments(), is(1));
    assertThat(fpq1.getMemoryMgr().getSegments(), hasSize(1));
    assertThat(fpq1.getJournalMgr().getJournalFiles().entrySet(), hasSize(1));
    assertThat(FileUtils.listFiles(fpq1.getPagingDirectory(), TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE),
            is(empty()));
    assertThat(
            FileUtils.listFiles(fpq1.getJournalDirectory(), TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE),
            hasSize(1));
}

From source file:org.apache.bookkeeper.bookie.BookieJournalTest.java

/**
 * Generate fence entry//from   w w w  .j a v a 2s .c  om
 */
private ByteBuffer generateFenceEntry(long ledgerId) {
    ByteBuffer bb = ByteBuffer.allocate(8 + 8);
    bb.putLong(ledgerId);
    bb.putLong(Bookie.METAENTRY_ID_FENCE_KEY);
    bb.flip();
    return bb;
}

From source file:edu.umn.cs.spatialHadoop.nasa.HDFRasterLayer.java

@Override
public void write(DataOutput out) throws IOException {
    super.write(out);
    out.writeLong(timestamp);/*from www  .  j  a  va  2 s.  c  o m*/
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzos = new GZIPOutputStream(baos);
    ByteBuffer bbuffer = ByteBuffer.allocate(getHeight() * 2 * 8 + 8);
    bbuffer.putInt(getWidth());
    bbuffer.putInt(getHeight());
    gzos.write(bbuffer.array(), 0, bbuffer.position());
    for (int x = 0; x < getWidth(); x++) {
        bbuffer.clear();
        for (int y = 0; y < getHeight(); y++) {
            bbuffer.putLong(sum[x][y]);
            bbuffer.putLong(count[x][y]);
        }
        gzos.write(bbuffer.array(), 0, bbuffer.position());
    }
    gzos.close();

    byte[] serializedData = baos.toByteArray();
    out.writeInt(serializedData.length);
    out.write(serializedData);
}