Example usage for java.nio ByteBuffer putShort

List of usage examples for java.nio ByteBuffer putShort

Introduction

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

Prototype

public abstract ByteBuffer putShort(short value);

Source Link

Document

Writes the given short to the current position and increases the position by 2.

Usage

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

public ByteBuffer serialize(MapRegister mapRegister) {
    int size = Length.HEADER_SIZE;
    if (mapRegister.getAuthenticationData() != null) {
        size += mapRegister.getAuthenticationData().length;
    }/*from w  ww  .j  a v a  2 s.  c  o  m*/
    if (mapRegister.isXtrSiteIdPresent() != null && mapRegister.isXtrSiteIdPresent()) {
        size += Length.XTRID_SIZE + Length.SITEID_SIZE;
    }
    for (EidToLocatorRecord eidToLocatorRecord : mapRegister.getEidToLocatorRecord()) {
        size += EidToLocatorRecordSerializer.getInstance().getSerializationSize(eidToLocatorRecord);
    }

    ByteBuffer registerBuffer = ByteBuffer.allocate(size);
    registerBuffer.put((byte) ((byte) (LispMessageEnum.MapRegister.getValue() << 4)
            | ByteUtil.boolToBit(BooleanUtils.isTrue(mapRegister.isProxyMapReply()), Flags.PROXY)
            | ByteUtil.boolToBit(BooleanUtils.isTrue(mapRegister.isXtrSiteIdPresent()), Flags.XTRSITEID)));
    registerBuffer.position(registerBuffer.position() + Length.RES);
    registerBuffer
            .put(ByteUtil.boolToBit(BooleanUtils.isTrue(mapRegister.isWantMapNotify()), Flags.WANT_MAP_REPLY));
    registerBuffer.put((byte) mapRegister.getEidToLocatorRecord().size());
    registerBuffer.putLong(NumberUtil.asLong(mapRegister.getNonce()));
    registerBuffer.putShort(NumberUtil.asShort(mapRegister.getKeyId()));

    if (mapRegister.getAuthenticationData() != null) {
        registerBuffer.putShort((short) mapRegister.getAuthenticationData().length);
        registerBuffer.put(mapRegister.getAuthenticationData());
    } else {
        registerBuffer.putShort((short) 0);
    }
    for (EidToLocatorRecord eidToLocatorRecord : mapRegister.getEidToLocatorRecord()) {
        EidToLocatorRecordSerializer.getInstance().serialize(registerBuffer, eidToLocatorRecord);
    }

    if (mapRegister.isXtrSiteIdPresent() != null && mapRegister.isXtrSiteIdPresent()) {
        registerBuffer.put(mapRegister.getXtrId());
        registerBuffer.put(mapRegister.getSiteId());
    }
    registerBuffer.clear();
    return registerBuffer;
}

From source file:com.github.ambry.commons.BlobIdTest.java

/**
 * Build a string that resembles a bad blobId.
 * @param version The version number to be embedded in the blobId.
 * @param type The {@link BlobIdType} of the blobId.
 * @param datacenterId The datacenter id to be embedded in the blobId.
 * @param accountId The account id to be embedded in the blobId.
 * @param containerId The container id to be embedded in the blobId.
 * @param partitionId The partition id to be embedded in the blobId.
 * @param uuidLength The length of the uuid.
 * @param uuid The UUID to be embedded in the blobId.
 * @param extraChars Extra characters to put at the end of the ID.
 * @return a base-64 encoded {@link String} representing the blobId.
 *///from   ww  w  .  j  av a 2 s.com
private String buildBadBlobId(short version, BlobIdType type, Byte datacenterId, Short accountId,
        Short containerId, PartitionId partitionId, int uuidLength, String uuid, String extraChars) {
    int idLength;
    ByteBuffer idBuf;
    switch (version) {
    case BLOB_ID_V1:
        idLength = 2 + partitionId.getBytes().length + 4 + uuid.length() + extraChars.length();
        idBuf = ByteBuffer.allocate(idLength);
        idBuf.putShort(version);
        break;
    case BLOB_ID_V2:
        idLength = 2 + 1 + 1 + 2 + 2 + partitionId.getBytes().length + 4 + uuid.length() + extraChars.length();
        idBuf = ByteBuffer.allocate(idLength);
        idBuf.putShort(version);
        idBuf.put((byte) 0);
        idBuf.put(datacenterId);
        idBuf.putShort(accountId);
        idBuf.putShort(containerId);
        break;
    case BLOB_ID_V3:
    case BLOB_ID_V4:
    case BLOB_ID_V5:
    case BLOB_ID_V6:
        idLength = 2 + 1 + 1 + 2 + 2 + partitionId.getBytes().length + 4 + uuid.length() + extraChars.length();
        idBuf = ByteBuffer.allocate(idLength);
        idBuf.putShort(version);
        idBuf.put((byte) type.ordinal());
        idBuf.put(datacenterId);
        idBuf.putShort(accountId);
        idBuf.putShort(containerId);
        break;
    default:
        idLength = 2 + partitionId.getBytes().length + 4 + uuid.length() + extraChars.length();
        idBuf = ByteBuffer.allocate(idLength);
        idBuf.putShort(version);
        break;
    }
    idBuf.put(partitionId.getBytes());
    switch (version) {
    case BLOB_ID_V6:
        UUID uuidObj = UUID.fromString(uuid);
        idBuf.putLong(uuidObj.getMostSignificantBits());
        idBuf.putLong(uuidObj.getLeastSignificantBits());
        break;
    default:
        idBuf.putInt(uuidLength);
        idBuf.put(uuid.getBytes());
    }
    idBuf.put(extraChars.getBytes());
    return Base64.encodeBase64URLSafeString(idBuf.array());
}

From source file:it.anyplace.sync.bep.BlockExchangeConnectionHandler.java

private Future sendHelloMessage(final byte[] payload) {
    return outExecutorService.submit(new Runnable() {
        @Override//  w  ww .j av  a 2 s. c  om
        public void run() {
            try {
                logger.trace("sending message");
                ByteBuffer header = ByteBuffer.allocate(6);
                header.putInt(MAGIC);
                header.putShort((short) payload.length);
                out.write(header.array());
                out.write(payload);
                out.flush();
                logger.trace("sent message");
            } catch (IOException ex) {
                if (outExecutorService.isShutdown()) {
                    return;
                }
                logger.error("error writing to output stream", ex);
                closeBg();
            }
        }
    });
}

From source file:io.druid.hll.HyperLogLogCollectorTest.java

private ByteBuffer makeCollectorBuffer(int offset, byte[] initialBytes, int remainingBytes) {
    short numNonZero = 0;
    for (byte initialByte : initialBytes) {
        numNonZero += computeNumNonZero(initialByte);
    }/*www .  j a  v  a 2  s  .c  om*/

    final short numNonZeroInRemaining = computeNumNonZero((byte) remainingBytes);
    numNonZero += (short) ((HyperLogLogCollector.NUM_BYTES_FOR_BUCKETS - initialBytes.length)
            * numNonZeroInRemaining);

    ByteBuffer biggerOffset = ByteBuffer.allocate(HyperLogLogCollector.getLatestNumBytesForDenseStorage());
    biggerOffset.put(HLLCV1.VERSION);
    biggerOffset.put((byte) offset);
    biggerOffset.putShort(numNonZero);
    biggerOffset.put((byte) 0);
    biggerOffset.putShort((short) 0);
    biggerOffset.put(initialBytes);
    while (biggerOffset.hasRemaining()) {
        biggerOffset.put((byte) remainingBytes);
    }
    biggerOffset.clear();
    return biggerOffset.asReadOnlyBuffer();
}

From source file:org.springframework.integration.ip.tcp.serializer.ByteArrayLengthHeaderSerializer.java

/**
 * Writes the header, according to the header format.
 * @param outputStream//www .j  a v a  2s . c o  m
 * @param length
 * @throws IOException
 */
protected void writeHeader(OutputStream outputStream, int length) throws IOException {
    ByteBuffer lengthPart = ByteBuffer.allocate(this.headerSize);
    switch (this.headerSize) {
    case HEADER_SIZE_INT:
        lengthPart.putInt(length);
        break;
    case HEADER_SIZE_UNSIGNED_BYTE:
        if (length > 0xff) {
            throw new IllegalArgumentException(
                    "Length header:" + headerSize + " too short to accommodate message length:" + length);
        }
        lengthPart.put((byte) length);
        break;
    case HEADER_SIZE_UNSIGNED_SHORT:
        if (length > 0xffff) {
            throw new IllegalArgumentException(
                    "Length header:" + headerSize + " too short to accommodate message length:" + length);
        }
        lengthPart.putShort((short) length);
        break;
    default:
        throw new IllegalArgumentException("Bad header size:" + headerSize);
    }
    outputStream.write(lengthPart.array());
}

From source file:ru.jts_dev.common.tcp.ProtocolByteArrayLengthHeaderSerializer.java

@Override
protected void writeHeader(OutputStream outputStream, int length) throws IOException {
    ByteBuffer lengthPart = ByteBuffer.allocate(this.headerSize).order(LITTLE_ENDIAN);
    length += headerSize; // Protocol thing, length represent header size + data size
    switch (this.headerSize) {
    case HEADER_SIZE_INT:
        lengthPart.putInt(length);//w  w w .ja  v a 2 s . c om
        break;
    case HEADER_SIZE_UNSIGNED_BYTE:
        if (length > 0xff) {
            throw new IllegalArgumentException(
                    "Length header:" + headerSize + " too short to accommodate message length:" + length);
        }
        lengthPart.put((byte) length);
        break;
    case HEADER_SIZE_UNSIGNED_SHORT:
        if (length > 0xffff) {
            throw new IllegalArgumentException(
                    "Length header:" + headerSize + " too short to accommodate message length:" + length);
        }
        lengthPart.putShort((short) length);
        break;
    default:
        throw new IllegalArgumentException("Bad header size:" + headerSize);
    }
    outputStream.write(lengthPart.array());
}

From source file:org.apache.carbondata.processing.store.writer.AbstractFactDataWriter.java

/**
 * Below method will be used to update the no dictionary start and end key
 *
 * @param key key to be updated/*from   w  ww.  j  ava 2s  .  c o  m*/
 * @return return no dictionary key
 */
protected byte[] updateNoDictionaryStartAndEndKey(byte[] key) {
    if (key.length == 0) {
        return key;
    }
    // add key to byte buffer remove the length part of the data
    ByteBuffer buffer = ByteBuffer.wrap(key, 2, key.length - 2);
    // create a output buffer without length
    ByteBuffer output = ByteBuffer.allocate(key.length - 2);
    short numberOfByteToStorLength = 2;
    // as length part is removed, so each no dictionary value index
    // needs to be reshuffled by 2 bytes
    for (int i = 0; i < dataWriterVo.getNoDictionaryCount(); i++) {
        output.putShort((short) (buffer.getShort() - numberOfByteToStorLength));
    }
    // copy the data part
    while (buffer.hasRemaining()) {
        output.put(buffer.get());
    }
    output.rewind();
    return output.array();
}

From source file:org.apache.druid.hll.HyperLogLogCollectorTest.java

private ByteBuffer makeCollectorBuffer(int offset, byte[] initialBytes, int remainingBytes) {
    short numNonZero = 0;
    for (byte initialByte : initialBytes) {
        numNonZero += computeNumNonZero(initialByte);
    }//w w w.  ja  v a 2s  .  co  m

    final short numNonZeroInRemaining = computeNumNonZero((byte) remainingBytes);
    numNonZero += (short) ((HyperLogLogCollector.NUM_BYTES_FOR_BUCKETS - initialBytes.length)
            * numNonZeroInRemaining);

    ByteBuffer biggerOffset = ByteBuffer.allocate(HyperLogLogCollector.getLatestNumBytesForDenseStorage());
    biggerOffset.put(VersionOneHyperLogLogCollector.VERSION);
    biggerOffset.put((byte) offset);
    biggerOffset.putShort(numNonZero);
    biggerOffset.put((byte) 0);
    biggerOffset.putShort((short) 0);
    biggerOffset.put(initialBytes);
    while (biggerOffset.hasRemaining()) {
        biggerOffset.put((byte) remainingBytes);
    }
    biggerOffset.clear();
    return biggerOffset.asReadOnlyBuffer();
}

From source file:com.linkedin.databus.core.DbusEventV2.java

public static int serializeEvent(DbusEventKey key, ByteBuffer buf, DbusEventInfo dbusEventInfo) {
    // Serialize a DbusEventV2 that has exact same contents as a DbusEventV1.
    final int start = buf.position();
    buf.put(DbusEventFactory.DBUS_EVENT_V2);
    buf.putInt(MAGIC);//from   w ww  . j  av a2s  .  c om
    buf.putInt(0); // Header len placeholder
    buf.putInt(0); // Header crc placeholder
    buf.putInt(0); // Body CRC placeholder
    buf.putInt(0); // total length placeholder

    short attributes = 0;
    attributes = setOpCode(dbusEventInfo.getOpCode(), attributes, dbusEventInfo.getSrcId());
    attributes = setKeyType(key, attributes);
    if (dbusEventInfo.isEnableTracing()) {
        attributes |= FLAG_TRACE_ON;
    }

    if (dbusEventInfo.isReplicated()) {
        attributes |= FLAG_IS_REPLICATED;
    }

    DbusEventPart metadata = dbusEventInfo.getMetadata();
    if (shouldEncodePayloadPart(dbusEventInfo)) {
        attributes |= FLAG_HAS_PAYLOAD_PART;
    }
    if (metadata != null) {
        attributes |= FLAG_HAS_PAYLOAD_METADATA_PART;
    }
    buf.putShort(attributes);
    buf.putLong(dbusEventInfo.getTimeStampInNanos());
    buf.putInt(dbusEventInfo.getSrcId());
    buf.putShort(dbusEventInfo.getpPartitionId());
    buf.putLong(dbusEventInfo.getSequenceId());

    // Fixed part of header is done. Now for the variable header part
    setKey(buf, key);
    final int hdrEndPos = buf.position();

    if (metadata != null) {
        metadata.encode(buf);
    }

    if ((attributes & FLAG_HAS_PAYLOAD_PART) != 0) {
        ByteBuffer bb = dbusEventInfo.getValueByteBuffer();
        if (bb == null) {
            // Special case to encode when there is no data.
            bb = ByteBuffer.allocate(1).order(buf.order());
            bb.limit(0);
        }
        DbusEventPart valuePart = new DbusEventPart(SchemaDigestType.MD5, dbusEventInfo.getSchemaId(),
                dbusEventInfo.getPayloadSchemaVersion(), bb);
        valuePart.encode(buf);
    }
    final int end = buf.position();
    buf.putInt(start + HeaderLenOffset, hdrEndPos - start);
    buf.putInt(start + TotalLenOffset, end - start);

    long bodyCrc = ByteBufferCRC32.getChecksum(buf, hdrEndPos, end - hdrEndPos);
    Utils.putUnsignedInt(buf, start + BodyCrcOffset, bodyCrc);
    // Header CRC
    if (dbusEventInfo.isAutocommit()) {
        // Do the body CRC first, since that is included in the header CRC
        long hdrCrc = ByteBufferCRC32.getChecksum(buf, start + BodyCrcOffset,
                hdrEndPos - start - BodyCrcOffset);
        Utils.putUnsignedInt(buf, start + HeaderCrcOffset, hdrCrc);
    }
    return buf.position() - start;
}

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

public ByteBuffer serialize(MapRegister mapRegister) {
    int size = Length.HEADER_SIZE;
    if (mapRegister.getAuthenticationData() != null) {
        size += mapRegister.getAuthenticationData().length;
    }//from  www .  j av a 2s . c om
    if (mapRegister.isXtrSiteIdPresent() != null && mapRegister.isXtrSiteIdPresent()) {
        size += Length.XTRID_SIZE + Length.SITEID_SIZE;
    }
    for (MappingRecordItem eidToLocatorRecord : mapRegister.getMappingRecordItem()) {
        size += MappingRecordSerializer.getInstance()
                .getSerializationSize(eidToLocatorRecord.getMappingRecord());
    }

    ByteBuffer registerBuffer = ByteBuffer.allocate(size);
    registerBuffer.put((byte) ((byte) (MessageType.MapRegister.getIntValue() << 4)
            | ByteUtil.boolToBit(BooleanUtils.isTrue(mapRegister.isProxyMapReply()), Flags.PROXY)
            | ByteUtil.boolToBit(BooleanUtils.isTrue(mapRegister.isXtrSiteIdPresent()), Flags.XTRSITEID)));
    registerBuffer.position(registerBuffer.position() + Length.RES);
    registerBuffer.put((byte) (ByteUtil.boolToBit(BooleanUtils.isTrue(mapRegister.isMergeEnabled()),
            Flags.MERGE_ENABLED)
            | ByteUtil.boolToBit(BooleanUtils.isTrue(mapRegister.isWantMapNotify()), Flags.WANT_MAP_NOTIFY)));
    registerBuffer.put((byte) mapRegister.getMappingRecordItem().size());
    registerBuffer.putLong(NumberUtil.asLong(mapRegister.getNonce()));
    registerBuffer.putShort(NumberUtil.asShort(mapRegister.getKeyId()));

    if (mapRegister.getAuthenticationData() != null) {
        registerBuffer.putShort((short) mapRegister.getAuthenticationData().length);
        registerBuffer.put(mapRegister.getAuthenticationData());
    } else {
        registerBuffer.putShort((short) 0);
    }
    for (MappingRecordItem eidToLocatorRecord : mapRegister.getMappingRecordItem()) {
        MappingRecordSerializer.getInstance().serialize(registerBuffer, eidToLocatorRecord.getMappingRecord());
    }

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