Example usage for java.nio ByteBuffer putInt

List of usage examples for java.nio ByteBuffer putInt

Introduction

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

Prototype

public abstract ByteBuffer putInt(int value);

Source Link

Document

Writes the given int to the current position and increases the position by 4.

Usage

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  w  w . j a va2 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:org.apache.jackrabbit.oak.plugins.document.persistentCache.BroadcastTest.java

private static void listen() throws InterruptedException {
    String config = "key 123";

    ConsoleAppender<ILoggingEvent> ca = new ConsoleAppender<ILoggingEvent>();
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    ca.setContext(lc);/*from   w w w  .j a v a2 s  .  co m*/
    PatternLayout pl = new PatternLayout();
    pl.setPattern("%msg%n");
    pl.setContext(lc);
    pl.start();
    ca.setLayout(pl);
    ca.start();

    ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory
            .getLogger(TCPBroadcaster.class);
    logger.addAppender(ca);
    logger.setLevel(Level.DEBUG);

    TCPBroadcaster receiver = new TCPBroadcaster(config);
    receiver.addListener(new Broadcaster.Listener() {

        @Override
        public void receive(ByteBuffer buff) {
            int end = buff.position();
            StringBuilder sb = new StringBuilder();
            while (buff.remaining() > 0) {
                char c = (char) buff.get();
                if (c >= ' ' && c < 128) {
                    sb.append(c);
                } else if (c <= 9) {
                    sb.append((char) ('0' + c));
                } else {
                    sb.append('.');
                }
            }
            String dateTime = new Timestamp(System.currentTimeMillis()).toString().substring(0, 19);
            System.out.println(dateTime + " Received " + sb);
            buff.position(end);
        }

    });
    Random r = new Random();
    int x = r.nextInt();
    System.out.println("Sending " + x);
    for (int i = 0; i < 10; i++) {
        Thread.sleep(10);
        ByteBuffer buff = ByteBuffer.allocate(1024);
        buff.putInt(0);
        buff.putInt(x);
        buff.put(new byte[100]);
        buff.flip();
        receiver.send(buff);
        if (!receiver.isRunning()) {
            System.out.println("Did not start or already stopped");
            break;
        }
    }
    Thread.sleep(Integer.MAX_VALUE);
}

From source file:edu.umass.cs.gigapaxos.paxospackets.AcceptPacket.java

@Override
public synchronized byte[] toBytes() {
    long t = System.nanoTime();
    if (!(PaxosPacket.BYTEIFICATION && IntegerMap.allInt()))
        return super.toBytes();

    if (this.getByteifiedSelf() != null)
        return this.getByteifiedSelf();

    // else construct
    byte[] buf = super.toBytes(false);
    byte[] bytes = new byte[buf.length
            // ProposalPacket.slot
            + SIZEOF_PROPOSAL//ww  w. jav  a2 s  . com
            // PValuePacket:ballot, recovery, medianCheckpointedSlot,
            // noCoalesce
            + SIZEOF_PVALUE
            // AcceptPacket.sender
            + SIZEOF_ACCEPT];
    ByteBuffer bbuf = ByteBuffer.wrap(bytes);

    // request
    bbuf.put(buf);
    // proposal
    bbuf.putInt(this.slot)
            // pvalue
            .putInt(this.ballot.ballotNumber).putInt(this.ballot.coordinatorID)
            .put(this.isRecovery() ? (byte) 1 : 0).putInt(this.getMedianCheckpointedSlot()).put((byte) 0)
            // accept
            .putInt(this.sender);

    assert (bbuf.remaining() == 0); // exact alignment

    this.setByteifiedSelf(bytes);

    if (PaxosMessenger.INSTRUMENT_SERIALIZATION && Util.oneIn(100))
        DelayProfiler.updateDelayNano("accept->", t, this.batchSize() + 1);

    return bytes;
}

From source file:org.ros.android.android_acm_serial.AcmDevice.java

public void setLineCoding(BitRate bitRate, StopBits stopBits, Parity parity, DataBits dataBits) {
    ByteBuffer buffer = ByteBuffer.allocate(7);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    buffer.putInt(bitRate.getBitRate());
    buffer.put(stopBits.getStopBits());// w ww. j  a  va 2  s  .co  m
    buffer.put(parity.getParity());
    buffer.put(dataBits.getDataBits());
    setLineCoding(buffer.array());
}

From source file:org.apache.bookkeeper.replication.BookieLedgerIndexTest.java

private LedgerHandle createAndAddEntriesToLedger() throws BKException, InterruptedException {
    int numEntriesToWrite = 20;
    // Create a ledger
    LedgerHandle lh = bkc.createLedger(digestType, "admin".getBytes());
    LOG.info("Ledger ID: " + lh.getId());
    for (int i = 0; i < numEntriesToWrite; i++) {
        ByteBuffer entry = ByteBuffer.allocate(4);
        entry.putInt(rng.nextInt(Integer.MAX_VALUE));
        entry.position(0);/*from ww  w.  j ava 2s  . com*/

        entries.add(entry.array());
        lh.addEntry(entry.array());
    }
    ledgerList.add(lh.getId());
    return lh;
}

From source file:com.openteach.diamond.network.waverider.command.Command.java

/**
 * ByteBuffer/*from www  . j ava  2 s  . c o  m*/
 * @return
 */
public ByteBuffer marshall() {
    int length = getSize();
    ByteBuffer buffer = ByteBuffer.allocate(length);
    buffer.putLong(type);
    buffer.putInt(length);
    buffer.put(payLoad);
    buffer.flip();
    payLoad.clear();
    return buffer;
}

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

public PacketEntityInformation(List<Entity> entities) {
    ByteBuffer tempbuffer = ByteBuffer.allocate(entities.size() * 4);
    for (Entity e : entities) {
        tempbuffer.putInt(e.getEntityId());
    }/*from  w ww .  j a  v  a  2 s .  c o  m*/
    data = tempbuffer.array();
}

From source file:net.jenet.Header.java

public void toBuffer(ByteBuffer buffer) {
    buffer.putShort(peerID);//from  w  w w.j a  v a 2s .c o  m
    buffer.put(flags);
    buffer.put(commandCount);
    buffer.putInt(sentTime);
    buffer.putInt(challenge);
}

From source file:org.hobbit.core.components.AbstractSystemAdapter.java

/**
 * This method sends the given result data for the task with the given task id
 * to the evaluation storage./*from   ww w . j  a va 2  s.  co  m*/
 *
 * @param taskIdString
 *            the id of the task
 * @param data
 *            the data of the task
 * @throws IOException
 *             if there is an error during the sending
 */
protected void sendResultToEvalStorage(String taskIdString, byte[] data) throws IOException {
    byte[] taskIdBytes = taskIdString.getBytes(Charsets.UTF_8);
    // + 4 for taskIdBytes.length
    // + 4 for data.length
    int capacity = 4 + 4 + taskIdBytes.length + data.length;
    ByteBuffer buffer = ByteBuffer.allocate(capacity);
    buffer.putInt(taskIdBytes.length);
    buffer.put(taskIdBytes);
    buffer.putInt(data.length);
    buffer.put(data);
    sender2EvalStore.sendData(buffer.array());
}

From source file:tor.Cell.java

public byte[] getBytes(int protocolVersion) {
    byte cell[];//from   ww w  . j a v  a2  s  .  co  m

    if (cmdId == 7 || cmdId >= 128)
        cell = new byte[(protocolVersion < 4 ? 3 : 5) + 2 + payload.length];
    else
        cell = new byte[protocolVersion < 4 ? 512 : 514];

    ByteBuffer buf = ByteBuffer.wrap(cell);
    buf.order(ByteOrder.BIG_ENDIAN);
    if (protocolVersion < 4)
        buf.putShort((short) circId);
    else
        buf.putInt((int) circId);
    buf.put((byte) cmdId);

    if (cmdId == 7 || cmdId >= 128)
        buf.putShort((short) payload.length);

    if (payload != null)
        buf.put(payload);
    //System.out.println("Sending:" + byteArrayToHex(cell));
    return cell;
}