Example usage for java.nio ByteBuffer put

List of usage examples for java.nio ByteBuffer put

Introduction

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

Prototype

public ByteBuffer put(ByteBuffer src) 

Source Link

Document

Writes all the remaining bytes of the src byte buffer to this buffer's current position, and increases both buffers' position by the number of bytes copied.

Usage

From source file:edu.cmu.cylab.starslinger.transaction.WebEngine.java

/**
 * get a message meta-data, based on the retrieval id from the server
 * /*  w w w  .j  a va  2s.c o  m*/
 * @throws MessageNotFoundException
 */
public byte[] getMessage(byte[] msgHashBytes) throws ExchangeException, MessageNotFoundException {

    ByteBuffer msg = ByteBuffer.allocate(mVersionLen //
            + 4 + msgHashBytes.length //
    );
    msg.putInt(mVersion);
    msg.putInt(msgHashBytes.length);
    msg.put(msgHashBytes);

    byte[] resp = doPost(mUrlPrefix + mHost + "/getMessage" + mUrlSuffix, msg.array());

    resp = handleResponseExceptions(resp, 0);

    return resp;
}

From source file:net.beaconpe.jraklib.server.Session.java

private void handleSplit(EncapsulatedPacket packet) throws IOException {
    if (packet.splitCount >= 128) {
        return;//from w w  w  .ja  va  2s.  c  o  m
    }

    if (!splitPackets.containsKey(packet.splitID)) {
        Map<Integer, EncapsulatedPacket> map = new ConcurrentHashMap<>();
        map.put(packet.splitIndex, packet);
        splitPackets.put(packet.splitID, map);
    } else {
        Map<Integer, EncapsulatedPacket> map = splitPackets.get(packet.splitID);
        map.put(packet.splitIndex, packet);
        splitPackets.put(packet.splitID, map);
    }

    if (splitPackets.get(packet.splitID).values().size() == packet.splitCount) {
        EncapsulatedPacket pk = new EncapsulatedPacket();
        ByteBuffer bb = ByteBuffer.allocate(1024 * 1024);
        for (int i = 0; i < packet.splitCount; i++) {
            bb.put(splitPackets.get(packet.splitID).get(i).buffer);
        }
        pk.buffer = ArrayUtils.subarray(bb.array(), 0, bb.position());
        bb = null;

        pk.length = pk.buffer.length;
        splitPackets.remove(packet.splitID);

        handleEncapsulatedPacketRoute(pk);
    }
}

From source file:com.kylinolap.common.hll.HyperLogLogPlusCounter.java

public void writeRegisters(final ByteBuffer out) throws IOException {
    int startPos = out.position();

    final int indexLen = getRegisterIndexSize();
    int size = size();

    // decide output scheme -- map (3*size bytes) or array (2^p bytes)
    byte scheme;/*from   w w  w  .j  a  v a2 s . c  om*/
    if ((indexLen + 1) * size < m)
        scheme = 0; // map
    else
        scheme = 1; // array
    out.put(scheme);

    if (scheme == 0) { // map scheme
        BytesUtil.writeVInt(size, out);
        for (int i = 0; i < m; i++) {
            if (registers[i] > 0) {
                BytesUtil.writeUnsigned(i, indexLen, out);
                out.put(registers[i]);
            }
        }
    } else { // array scheme
        for (int i = 0; i < m; i++) {
            out.put(registers[i]);
        }
    }

    // do compression if needed
    int len = out.position() - startPos;
    if (len < COMPRESSION_THRESHOLD)
        return;

    scheme |= COMPRESSION_FLAG;
    byte[] compressed = DEFAULT_COMPRESSOR.compress(out, startPos + 1, len - 1);
    out.position(startPos);
    out.put(scheme);
    BytesUtil.writeVInt(compressed.length, out);
    out.put(compressed);
}

From source file:com.cinchapi.concourse.server.plugin.PluginManager.java

/**
 * Create a {@link SharedMemory} segment over which the PluginManager will
 * stream real-time {@link Packet packets} that contain writes.
 * /*  ww w  .j  a  va  2 s .  c o  m*/
 * @param id the plugin id
 */
private void initRealTimeStream(String id) {
    String streamFile = FileSystem.tempFile();
    SharedMemory stream = new SharedMemory(streamFile);
    ByteBuffer payload = ByteBuffers.fromString(streamFile);
    ByteBuffer message = ByteBuffer.allocate(payload.capacity() + 4);
    message.putInt(Instruction.MESSAGE.ordinal());
    message.put(payload);
    SharedMemory fromServer = (SharedMemory) router.get(id, PluginInfoColumn.FROM_SERVER);
    fromServer.write(ByteBuffers.rewind(message));
    streams.add(stream);
}

From source file:net.beaconpe.jraklib.protocol.AcknowledgePacket.java

@Override
protected void _encode() {
    ByteBuffer payload = ByteBuffer.allocate(1024);
    int count = packets.length;
    int records = 0;

    if (count > 0) {
        int pointer = 0;
        int start = packets[0];
        int last = packets[0];

        while (pointer + 1 < count) {
            int current = packets[pointer++];
            int diff = current - last;
            if (diff == 1) {
                last = current;//from  ww w. ja  v a  2 s .  c o m
            } else if (diff > 1) { //Forget about duplicated packets (bad queues?)
                if (start == last) {
                    payload.put((byte) 0x01);
                    payload.put(Binary.writeLTriad(start));
                    start = last = current;
                } else {
                    payload.put((byte) 0x00);
                    payload.put(Binary.writeLTriad(start));
                    payload.put(Binary.writeLTriad(last));
                    start = last = current;
                }
                records = records + 1;
            }
        }

        if (start == last) {
            payload.put((byte) 0x01);
            payload.put(Binary.writeLTriad(start));
        } else {
            payload.put((byte) 0x00);
            payload.put(Binary.writeLTriad(start));
            payload.put(Binary.writeLTriad(last));
        }
        records = records + 1;
    }
    putShort((short) records);
    put(ArrayUtils.subarray(payload.array(), 0, payload.position()));
}

From source file:com.nordicsemi.nrfUARTv2.MainActivity.java

private short bytesToShort(byte b1, byte b2) {
    ByteBuffer bb = ByteBuffer.allocate(2);
    bb.order(ByteOrder.LITTLE_ENDIAN);
    bb.put(b1);
    bb.put(b2);// ww  w  .  j av a  2 s .co  m
    short shortVal = bb.getShort(0);
    return shortVal;
}

From source file:com.cinchapi.concourse.server.plugin.PluginManager.java

/**
 * Invoke {@code method} that is defined in the plugin endpoint inside of
 * {@clazz}. The provided {@code creds}, {@code transaction} token and
 * {@code environment} are used to ensure proper alignment with the
 * corresponding client session on the server.
 * //  ww w  .  j  a  v a2 s. c o  m
 * @param clazz the {@link Plugin} endpoint class
 * @param method the name of the method to invoke
 * @param args a list of arguments to pass to the method
 * @param creds the {@link AccessToken} submitted to ConcourseServer via the
 *            invokePlugin method
 * @param transaction the {@link TransactionToken} submitted to
 *            ConcourseServer via the invokePlugin method
 * @param environment the environment submitted to ConcourseServer via the
 *            invokePlugin method
 * @return the response from the plugin
 */
public ComplexTObject invoke(String clazz, String method, List<ComplexTObject> args, final AccessToken creds,
        TransactionToken transaction, String environment) {
    SharedMemory fromServer = (SharedMemory) router.get(clazz, PluginInfoColumn.FROM_SERVER);
    RemoteMethodRequest request = new RemoteMethodRequest(method, creds, transaction, environment, args);
    ByteBuffer data0 = Serializables.getBytes(request);
    ByteBuffer data = ByteBuffer.allocate(data0.capacity() + 4);
    data.putInt(Plugin.Instruction.REQUEST.ordinal());
    data.put(data0);
    fromServer.write(ByteBuffers.rewind(data));
    ConcurrentMap<AccessToken, RemoteMethodResponse> fromPluginResponses = (ConcurrentMap<AccessToken, RemoteMethodResponse>) router
            .get(clazz, PluginInfoColumn.FROM_PLUGIN_RESPONSES);
    RemoteMethodResponse response = ConcurrentMaps.waitAndRemove(fromPluginResponses, creds);
    if (!response.isError()) {
        return response.response;
    } else {
        throw Throwables.propagate(response.error);
    }
}

From source file:com.inductiveautomation.xopc.drivers.modbus2.requests.WriteMultipleRegistersRequest.java

public WriteMultipleRegistersRequest(List<WriteItem> items, ChannelWriter channelWriter,
        ModbusTransport transport, boolean zeroBased, byte unitId, int timeout, Logger log, boolean swapWords,
        boolean rightJustifyStrings, boolean reverseStringByteOrder,
        CommunicationCallback communicationCallback) {
    super(items, channelWriter, transport, zeroBased, unitId, timeout, log, communicationCallback);

    this.swapWords = swapWords;
    this.rightJustifyStrings = rightJustifyStrings;
    this.reverseStringByteOrder = reverseStringByteOrder;

    RequestOffsets offsets = new RequestOffsets.Calculator(items).calculate();

    // Multiply by two since each unit of length is one 16-bit register.
    ByteBuffer buffer = ByteBuffer.allocate(offsets.getLength() * 2);

    Iterator<? extends WriteItem> iter = items.iterator();

    while (iter.hasNext()) {
        WriteItem item = iter.next();/*from   w  w w  .j a va  2 s  . c o  m*/
        ModbusAddress address = (ModbusAddress) item.getAddressObject();

        int offset = (address.getStartAddress() - offsets.getStartAddress()) * 2;
        buffer.position(offset);

        byte[] bs = getValue(item, address);
        buffer.put(bs);
    }

    short startAddress = (short) offsets.getStartAddress();
    short quantity = (short) offsets.getLength();
    byte byteCount = (byte) buffer.limit();
    byte[] values = buffer.array();

    if (zeroBased) {
        startAddress--;
    }

    request = new WriteMultipleRegisters.Request(startAddress, quantity, byteCount, values);
}

From source file:com.mycustomloader.vsamloader.VSAMLoader.java

@Override
public Tuple getNext() throws IOException {
    mProtoTuple = new ArrayList<Object>();

    boolean inField = false;
    boolean inQuotedField = false;
    boolean evenQuotesSeen = true;

    if (!mRequiredColumnsInitialized) {
        if (signature != null) {
            Properties p = UDFContext.getUDFContext().getUDFProperties(this.getClass());
            mRequiredColumns = (boolean[]) ObjectSerializer.deserialize(p.getProperty(signature));
        }/*from  ww  w. j a v a  2 s.c o  m*/
        mRequiredColumnsInitialized = true;
    }
    try {
        if (!in.nextKeyValue()) {
            return null;
        }
        Text value = (Text) in.getCurrentValue();
        byte[] buf = value.getBytes();
        int len = value.getLength();
        int fieldID = 0;

        ByteBuffer fieldBuffer = ByteBuffer.allocate(len);

        for (int i = 0; i < len; i++) {
            byte b = buf[i];
            inField = true;
            if (inQuotedField) {
                if (b == DOUBLE_QUOTE) {
                    evenQuotesSeen = !evenQuotesSeen;
                    if (evenQuotesSeen) {
                        fieldBuffer.put(DOUBLE_QUOTE);
                    }
                } else if (!evenQuotesSeen && (b == FIELD_DEL || b == RECORD_DEL)) {
                    inQuotedField = false;
                    inField = false;
                    readField(fieldBuffer, fieldID++);
                } else {
                    fieldBuffer.put(b);
                }
            } else if (b == DOUBLE_QUOTE) {
                inQuotedField = true;
                evenQuotesSeen = true;
            } else if (b == FIELD_DEL) {
                inField = false;
                readField(fieldBuffer, fieldID++); // end of the field
            } else {
                evenQuotesSeen = true;
                fieldBuffer.put(b);
            }
        }
        if (inField)
            readField(fieldBuffer, fieldID++);
    } catch (InterruptedException e) {
        int errCode = 6018;
        String errMsg = "Error while reading input";
        throw new ExecException(errMsg, errCode, PigException.REMOTE_ENVIRONMENT, e);
    }

    Tuple t = mTupleFactory.newTupleNoCopy(mProtoTuple);
    return t;
}

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

@Override
protected void putBody(ByteBuffer buf) {
    if (!requestSend) {
        // 2. 8//w ww.  j  a v  a 2  s. c  om
        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);
    }
}