Java Code Examples for java.nio.ByteBuffer#putShort()

The following examples show how to use java.nio.ByteBuffer#putShort() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestFuzzyRowAndColumnRangeFilter.java    From hbase with Apache License 2.0 6 votes vote down vote up
private void runTest(Table hTable, int cqStart, int expectedSize) throws IOException {
  // [0, 2, ?, ?, ?, ?, 0, 0, 0, 1]
  byte[] fuzzyKey = new byte[10];
  ByteBuffer buf = ByteBuffer.wrap(fuzzyKey);
  buf.clear();
  buf.putShort((short) 2);
  for (int i = 0; i < 4; i++)
    buf.put((byte)63);
  buf.putInt((short)1);

  byte[] mask = new byte[] {0 , 0, 1, 1, 1, 1, 0, 0, 0, 0};

  Pair<byte[], byte[]> pair = new Pair<>(fuzzyKey, mask);
  FuzzyRowFilter fuzzyRowFilter = new FuzzyRowFilter(Lists.newArrayList(pair));
  ColumnRangeFilter columnRangeFilter = new ColumnRangeFilter(Bytes.toBytes(cqStart), true
          , Bytes.toBytes(4), true);
  //regular test
  runScanner(hTable, expectedSize, fuzzyRowFilter, columnRangeFilter);
  //reverse filter order test
  runScanner(hTable, expectedSize, columnRangeFilter, fuzzyRowFilter);
}
 
Example 2
Source File: ConsumeQueueExt.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 6 votes vote down vote up
/**
 * Transform unit data to byte array.
 * <p/>
 * <li>1. @{code container} can be null, it will be created if null.</li>
 * <li>2. if capacity of @{code container} is less than unit size, it will be created also.</li>
 * <li>3. Pls be sure that size of unit is not greater than {@link #MAX_EXT_UNIT_SIZE}</li>
 *
 * @param container
 * @return
 */
private byte[] write(final ByteBuffer container) {
    this.bitMapSize = (short) (filterBitMap == null ? 0 : filterBitMap.length);
    this.size = (short) (MIN_EXT_UNIT_SIZE + this.bitMapSize);

    ByteBuffer temp = container;

    if (temp == null || temp.capacity() < this.size) {
        temp = ByteBuffer.allocate(this.size);
    }

    temp.flip();
    temp.limit(this.size);

    temp.putShort(this.size);
    temp.putLong(this.tagsCode);
    temp.putLong(this.msgStoreTime);
    temp.putShort(this.bitMapSize);
    if (this.bitMapSize > 0) {
        temp.put(this.filterBitMap);
    }

    return temp.array();
}
 
Example 3
Source File: ConfigModelAppBind.java    From Android-nRF-Mesh-Library with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
void assembleMessageParameters() {
    final ByteBuffer paramsBuffer;
    final byte[] applicationKeyIndex = MeshParserUtils.addKeyIndexPadding(mAppKeyIndex);
    //We check if the model identifier value is within the range of a 16-bit value here. If it is then it is a sigmodel
    if (mModelIdentifier >= Short.MIN_VALUE && mModelIdentifier <= Short.MAX_VALUE) {
        paramsBuffer = ByteBuffer.allocate(SIG_MODEL_APP_KEY_BIND_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);
        paramsBuffer.putShort((short) mElementAddress);
        paramsBuffer.put(applicationKeyIndex[1]);
        paramsBuffer.put(applicationKeyIndex[0]);
        paramsBuffer.putShort((short) mModelIdentifier);
        mParameters = paramsBuffer.array();
    } else {
        paramsBuffer = ByteBuffer.allocate(VENDOR_MODEL_APP_KEY_BIND_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);
        paramsBuffer.putShort((short) mElementAddress);
        paramsBuffer.put(applicationKeyIndex[1]);
        paramsBuffer.put(applicationKeyIndex[0]);
        final byte[] modelIdentifier = new byte[]{(byte) ((mModelIdentifier >> 24) & 0xFF),
                (byte) ((mModelIdentifier >> 16) & 0xFF), (byte) ((mModelIdentifier >> 8) & 0xFF), (byte) (mModelIdentifier & 0xFF)};
        paramsBuffer.put(modelIdentifier[1]);
        paramsBuffer.put(modelIdentifier[0]);
        paramsBuffer.put(modelIdentifier[3]);
        paramsBuffer.put(modelIdentifier[2]);
        mParameters = paramsBuffer.array();
    }
}
 
Example 4
Source File: BootstrapResponseV2.java    From nyzoVerifier with The Unlicense 6 votes vote down vote up
@Override
public byte[] getBytes() {

    int size = getByteSize();
    byte[] result = new byte[size];
    ByteBuffer buffer = ByteBuffer.wrap(result);

    // frozen-edge height and hash
    buffer.putLong(frozenEdgeHeight);
    buffer.put(frozenEdgeHash);

    // verifiers
    buffer.putShort((short) cycleVerifiers.size());
    for (ByteBuffer identifier : cycleVerifiers) {
        buffer.put(identifier.array());
    }

    return result;
}
 
Example 5
Source File: SceneDelete.java    From Android-nRF-Mesh-Library with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
void assembleMessageParameters() {
    mAid = SecureUtils.calculateK4(mAppKey.getKey());
    final ByteBuffer paramsBuffer;
    Log.v(TAG, "Scene Number: " + mSceneNumber);
    paramsBuffer = ByteBuffer.allocate(SCENE_DELETE_PARAMS_LENGTH).order(ByteOrder.LITTLE_ENDIAN);
    paramsBuffer.putShort((short) mSceneNumber);
    mParameters = paramsBuffer.array();
}
 
Example 6
Source File: Fragment.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] serialize() {
    byte[] payloadData = null;
    if (this.payload != null) {
        this.payload.setParent(this);
        payloadData = this.payload.serialize();
    }

    int payloadLength = 0;
    if (payloadData != null) {
        payloadLength = payloadData.length;
    }

    final byte[] data = new byte[HEADER_LENGTH + payloadLength];
    final ByteBuffer bb = ByteBuffer.wrap(data);

    bb.put(this.nextHeader);
    bb.put((byte) 0);
    bb.putShort((short) (
            (this.fragmentOffset & 0x1fff) << 3 |
            this.moreFragment & 0x1
    ));
    bb.putInt(this.identification);

    if (payloadData != null) {
        bb.put(payloadData);
    }

    if (this.parent != null && this.parent instanceof IExtensionHeader) {
        ((IExtensionHeader) this.parent).setNextHeader(IPv6.PROTOCOL_FRAG);
    }
    return data;
}
 
Example 7
Source File: EddystoneTLM.java    From beacons-android with Apache License 2.0 5 votes vote down vote up
@Override
public Advertiser createAdvertiser(BleService service) {
    byte[] data = new byte[12];

    if (null != service) {
        ByteBuffer buffer = ByteBuffer.wrap(data);
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent stickyIntent = service.registerReceiver(null, intentFilter);
        if (null != stickyIntent) {
            mBatteryVoltage = (short) stickyIntent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
            buffer.putShort(mBatteryVoltage);

            mBatteryTemperature = stickyIntent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);

            // (int * 10) to fixed point 8.8
            buffer.putShort((short) (mBatteryTemperature / 10 << 8 | mBatteryTemperature % 10 * 256 / 10));

            mEstimatedPDUCount = (int) service.updateEstimatedPDUCount();
            buffer.putInt(mEstimatedPDUCount);

            mPowerOnTime = (int) service.getPowerOnTime();
            buffer.putInt(mPowerOnTime / 100);
        }
    }

    return new EddystoneAdvertiser(this, EddystoneAdvertiser.FRAME_TLM, data, 0, data.length);
}
 
Example 8
Source File: MuxerMP4.java    From Android-Audio-Recorder with Apache License 2.0 5 votes vote down vote up
public void encode(short[] buf) {
    for (int offset = 0; offset < buf.length; ) {
        int len = buf.length - offset;

        int inputIndex = encoder.dequeueInputBuffer(-1);
        if (inputIndex < 0)
            throw new RuntimeException("unable to open encoder input buffer");

        ByteBuffer input = encoder.getInputBuffer(inputIndex);
        input.clear();

        len = Math.min(len, input.limit() / 2);

        for (int i = 0; i < len; i++)
            input.putShort(buf[i]);

        int bytes = len * 2;

        long ts = getCurrentTimeStamp();
        encoder.queueInputBuffer(inputIndex, 0, bytes, ts, 0);
        NumSamples += len / info.channels;
        offset += len;

        while (encode())
            ;// do encode()
    }
}
 
Example 9
Source File: GroupMetadataConstants.java    From kop with Apache License 2.0 5 votes vote down vote up
/**
 * Generates the payload for offset commit message from given offset and metadata.
 *
 * @param offsetAndMetadata consumer's current offset and metadata
 * @return payload for offset commit message
 */
static byte[] offsetCommitValue(OffsetAndMetadata offsetAndMetadata) {
    Struct value = new Struct(CURRENT_OFFSET_VALUE_SCHEMA);
    value.set(OFFSET_VALUE_OFFSET_FIELD_V1, offsetAndMetadata.offset());
    value.set(OFFSET_VALUE_METADATA_FIELD_V1, offsetAndMetadata.metadata());
    value.set(OFFSET_VALUE_COMMIT_TIMESTAMP_FIELD_V1, offsetAndMetadata.commitTimestamp());
    value.set(OFFSET_VALUE_EXPIRE_TIMESTAMP_FIELD_V1, offsetAndMetadata.expireTimestamp());
    ByteBuffer byteBuffer = ByteBuffer.allocate(2 /* version */ + value.sizeOf());
    byteBuffer.putShort(CURRENT_GROUP_VALUE_SCHEMA_VERSION);
    value.writeTo(byteBuffer);
    return byteBuffer.array();
}
 
Example 10
Source File: PVAStructure.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void encodeType(final ByteBuffer buffer, final BitSet described) throws Exception
{
    final short type_id = getTypeID();
    if (type_id != 0)
    {
        final int u_type_id = Short.toUnsignedInt(type_id);
        if (described.get(u_type_id))
        {   // Refer to existing definition
            buffer.put(PVAFieldDesc.ONLY_ID_TYPE_CODE);
            buffer.putShort(type_id);
            // Done!
            return;
        }
        else
        {   // (Re-)define this type
            buffer.put(PVAFieldDesc.FULL_WITH_ID_TYPE_CODE);
            buffer.putShort(type_id);
            described.set(u_type_id);
        }
    }

    // Encode 'structure' type, name
    buffer.put((byte) (PVAComplex.FIELD_DESC_TYPE | PVAComplex.STRUCTURE));
    PVAString.encodeString(struct_name, buffer);

    // Encode elements
    PVASize.encodeSize(elements.size(), buffer);
    for (PVAData element : elements)
    {
        PVAString.encodeString(element.getName(), buffer);
        element.encodeType(buffer, described);
    }
}
 
Example 11
Source File: PacketTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testReplyPacket() {
    Values ret = new Values();
    ret.add(new Int32Value(123));

    Packet packet = new ReplyPacket(0, 42, ret);
    PacketInfo info = packet.getPacketInfo();

    ByteBuffer buf = ByteBuffer.allocate(info.packetLength());
    info.encodePacket(packet, buf);
    buf.flip();

    int bytes = 12 + ret.bytes();
    ByteBuffer ref = ByteBuffer.allocate(bytes);
    ref.putInt(bytes - 4);    // plen
    ref.putShort((short)0);   // flags
    ref.putShort((short)101); // pcode (reply)
    ref.putInt(42);           // reqId
    ret.encode(ref);
    assertEquals(0, ref.remaining());
    ref.flip();
    assertTrue(buf.equals(ref));

    PacketInfo info2 = PacketInfo.getPacketInfo(buf);
    assertTrue(info2 != null);
    assertEquals(info2.packetLength(), buf.remaining());
    Packet packet2 = info2.decodePacket(buf);
    assertEquals(0, buf.remaining());

    assertEquals(packet2.requestId(), 42);
    Values ret2 = ((ReplyPacket)packet2).returnValues();
    assertEquals(ret2.size(), 1);
    assertEquals(ret2.get(0).type(), Value.INT32);
    assertEquals(ret2.get(0).asInt32(), 123);
}
 
Example 12
Source File: Ethernet.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] serialize() {
    byte[] payloadData = null;
    if (this.payload != null) {
        this.payload.setParent(this);
        payloadData = this.payload.serialize();
    }
    int length = 14 + (this.vlanID == Ethernet.VLAN_UNTAGGED ? 0 : 4)
            + (this.qinqVID == Ethernet.VLAN_UNTAGGED ? 0 : 4)
            + (payloadData == null ? 0 : payloadData.length);
    if (this.pad && length < 60) {
        length = 60;
    }
    final byte[] data = new byte[length];
    final ByteBuffer bb = ByteBuffer.wrap(data);
    bb.put(this.destinationMACAddress.toBytes());
    bb.put(this.sourceMACAddress.toBytes());
    if (this.qinqVID != Ethernet.VLAN_UNTAGGED) {
        bb.putShort(this.qinqTPID);
        bb.putShort((short) (this.qInQPriorityCode << 13 | this.qinqVID & 0x0fff));
    }
    if (this.vlanID != Ethernet.VLAN_UNTAGGED) {
        bb.putShort(TYPE_VLAN);
        bb.putShort((short) (this.priorityCode << 13 | this.vlanID & 0x0fff));
    }
    bb.putShort(this.etherType);
    if (payloadData != null) {
        bb.put(payloadData);
    }
    if (this.pad) {
        Arrays.fill(data, bb.position(), data.length, (byte) 0x0);
    }
    return data;
}
 
Example 13
Source File: libpcapTest.java    From JavaLinuxNet with Apache License 2.0 5 votes vote down vote up
public static ByteBuffer getIPPacket(int len, byte protocol, int srcIp, int dstIp) {
    //create UDP packet
    ByteBuffer ipPacket = ByteBuffer.allocateDirect(len);
    ipPacket.put((byte) 0x45);  //ipv4 , size header
    ipPacket.put((byte) 0x00);  //tos
    ipPacket.putShort((short) (len & 0xffff));  //len=64
    ipPacket.putShort((short) 0x00);  //identification=0
    ipPacket.putShort((short) 0x00);  //flags/fragment
    ipPacket.put((byte) 0x40);  //TTL=64
    ipPacket.put(protocol);  //protocol
    ipPacket.putShort((short) 0x00);  //checksum
    return ipPacket;
}
 
Example 14
Source File: IndexData.java    From jackcess with Apache License 2.0 4 votes vote down vote up
/**
 * Writes the index definitions into a table definition buffer.
 * @param creator description of the indexes to write
 * @param buffer Buffer to write to
 */
protected static void writeDefinition(
    TableMutator creator, ByteBuffer buffer,
    TableMutator.IndexDataState idxDataState, ByteBuffer rootPageBuffer)
  throws IOException
{
  if(rootPageBuffer == null) {
    rootPageBuffer = createRootPageBuffer(creator);
  }

  buffer.putInt(MAGIC_INDEX_NUMBER); // seemingly constant magic value

  // write column information (always MAX_COLUMNS entries)
  IndexBuilder idx = idxDataState.getFirstIndex();
  List<IndexBuilder.Column> idxColumns = idx.getColumns();
  for(int i = 0; i < MAX_COLUMNS; ++i) {

    short columnNumber = COLUMN_UNUSED;
    byte flags = 0;

    if(i < idxColumns.size()) {

      // determine column info
      IndexBuilder.Column idxCol = idxColumns.get(i);
      flags = idxCol.getFlags();

      // find actual table column number
      columnNumber = creator.getColumnNumber(idxCol.getName());
      if(columnNumber == COLUMN_UNUSED) {
        // should never happen as this is validated before
        throw new IllegalArgumentException(
            withErrorContext(
                "Column with name " + idxCol.getName() + " not found",
                creator.getDatabase(), creator.getTableName(), idx.getName()));
      }
    }

    buffer.putShort(columnNumber); // table column number
    buffer.put(flags); // column flags (e.g. ordering)
  }

  buffer.put(idxDataState.getUmapRowNumber()); // umap row
  ByteUtil.put3ByteInt(buffer, idxDataState.getUmapPageNumber()); // umap page

  // write empty root index page
  creator.getPageChannel().writePage(rootPageBuffer,
                                     idxDataState.getRootPageNumber());

  buffer.putInt(idxDataState.getRootPageNumber());
  buffer.putInt(0); // unknown
  buffer.put(idx.getFlags()); // index flags (unique, etc.)
  ByteUtil.forward(buffer, 5); // unknown
}
 
Example 15
Source File: DynamicCompositeTypeTest.java    From stratio-cassandra with Apache License 2.0 4 votes vote down vote up
private ByteBuffer createDynamicCompositeKey(String s, UUID uuid, int i, boolean lastIsOne,
        final boolean reversed)
{
    String intType = (reversed ? "ReversedType(IntegerType)" : "IntegerType");
    ByteBuffer bytes = ByteBufferUtil.bytes(s);
    int totalSize = 0;
    if (s != null)
    {
        totalSize += 2 + 2 + bytes.remaining() + 1;
        if (uuid != null)
        {
            totalSize += 2 + 2 + 16 + 1;
            if (i != -1)
            {
                totalSize += 2 + intType.length() + 2 + 1 + 1;
            }
        }
    }

    ByteBuffer bb = ByteBuffer.allocate(totalSize);

    if (s != null)
    {
        bb.putShort((short)(0x8000 | (reversed ? 'B' : 'b')));
        bb.putShort((short) bytes.remaining());
        bb.put(bytes);
        bb.put(uuid == null && lastIsOne ? (byte)1 : (byte)0);
        if (uuid != null)
        {
            bb.putShort((short)(0x8000 | (reversed ? 'T' : 't')));
            bb.putShort((short) 16);
            bb.put(UUIDGen.decompose(uuid));
            bb.put(i == -1 && lastIsOne ? (byte)1 : (byte)0);
            if (i != -1)
            {
                bb.putShort((short) intType.length());
                bb.put(ByteBufferUtil.bytes(intType));
                // We are putting a byte only because our test use ints that fit in a byte *and* IntegerType.fromString() will
                // return something compatible (i.e, putting a full int here would break 'fromStringTest')
                bb.putShort((short) 1);
                bb.put((byte)i);
                bb.put(lastIsOne ? (byte)1 : (byte)0);
            }
        }
    }
    bb.rewind();
    return bb;
}
 
Example 16
Source File: NmcObsLegacy.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
void loadStructureData(ByteBuffer bb) {
  bb.putInt(data);
  bb.putShort(table101code);
  bb.put(quality);
}
 
Example 17
Source File: Serializer.java    From joyqueue with Apache License 2.0 4 votes vote down vote up
/**
     * 写入存储消息
     *
     * @param message 存储消息
     * @param out     输出缓冲区
     * @throws Exception 序列化异常
     */
    public static void write(final BrokerMessage message, final ByteBuffer out, int size) throws Exception {
        // FIXME: size没用,是否可以去掉?
//        int size;
        if (out == null || message == null) {
            return;
        }
        // 记录写入的起始位置
        int begin = out.position();
        // 4个字节的消息长度需要计算出来
        out.putInt(size);
        // 分区
        out.putShort(message.getPartition());
        //消息序号
        out.putLong(message.getMsgIndexNo());
        // 任期
        out.putInt(message.getTerm());
        // 2个字节的魔法标识
        out.putShort(BrokerMessage.MAGIC_CODE);

        //   | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 |
        //TODO   1个字节的系统字段 1-1:压缩标识 2-2:顺序消息 3-4: 消息来源,包括Jmq,kafka,mqtt 5-5:压缩算法 6-8:其他,预留未用
        byte sysCode = (byte) (message.isCompressed() ? 1 : 0);
        sysCode |= ((message.isOrdered() ? 1 : 0) << 1) & 0x3;

        sysCode |= (message.getSource() << 2) & 12;
        // compressor
        if (message.isCompressed()) {
            sysCode |= (message.getCompressionType().getType() << 4) & 48;
        }
        if (message.getClientIp().length < 7) {
            sysCode |= (1 << 5);
        }
        //T 2字节系统字段
        byte [] sysCodes = new byte[2];
        sysCodes[1] = sysCode;
        out.put(sysCodes);
        // 1字节优先级
        out.put(message.getPriority());
        // 16字节的客户端地址
        byte [] clientIp = new byte[16];
        if(message.getClientIp() != null) {
            System.arraycopy(message.getClientIp(), 0, clientIp,0, Math.min(message.getClientIp().length, clientIp.length));
        }
        out.put(clientIp);
//        out.put(message.getClientIp() == null ? new byte[16] : message.getClientIp());
//        if (message.getClientIp().length < 7){
//            out.put(new byte[10]);
//        }
        // 8字节发送时间
        out.putLong(message.getStartTime());
        // 4字节存储时间(相对发送时间的偏移)
        out.putInt(0);
        // 8字节消息体CRC
        out.putLong(message.getBodyCRC());

        // 4字节消息体大小
        // 消息体(字节数组)
        if (message.getByteBody() != null) {
            write(message.getBody(), out, true);
        } else {
            out.putInt(0);
        }

        // 1字节应用长度
        // 应用(字节数组)
        write(message.getApp(), out);
        // 1字节业务ID长度
        // 业务ID(字节数组)
        write(message.getBusinessId(), out);
        // 2字节属性长度
        // 属性(字节数组)
        write(toProperties(message.getAttributes()), out, 2);
        // 4字节扩展字段大小
        // 扩展字段(字节数组)
        write(message.getExtension(), out, true);

        // 重写总长度
//        int end = out.position();
//        size = end - begin;
        message.setSize(size);
//        out.position(begin);
//        out.putInt(size);
        out.flip();
//        out.position(end);
    }
 
Example 18
Source File: DecrementCommand.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
private ByteBuffer processBinaryProtocol(RequestReader request, Cache cache) {
  ByteBuffer buffer = request.getRequest();
  int extrasLength = buffer.get(EXTRAS_LENGTH_INDEX);
  final KeyWrapper key = getKey(buffer, HEADER_LENGTH + extrasLength);
  
  long decrBy = buffer.getLong(HEADER_LENGTH);
  long initialVal = buffer.getLong(HEADER_LENGTH + LONG_LENGTH);
  int expiration = buffer.getInt(HEADER_LENGTH + LONG_LENGTH + LONG_LENGTH);
  
  final Region<Object, ValueWrapper> r = getMemcachedRegion(cache);
  ByteBuffer newVal = ByteBuffer.allocate(8);
  boolean notFound = false;
  ValueWrapper newValWrapper = null;
  
  while (true) {
    ValueWrapper oldValWrapper = r.get(key);
    if (oldValWrapper == null) {
      if (expiration == -1) {
        notFound = true;
      } else {
        newVal.putLong(0, initialVal);
        newValWrapper = ValueWrapper.getWrappedValue(newVal.array(), 0/*flags*/);
        r.put(key, newValWrapper);
      }
      break;
    }
    byte[] oldVal = oldValWrapper.getValue();
    long oldLong = getLongFromByteArray(oldVal);
    long newLong = oldLong - decrBy;
    if (newLong < 0) {
      newLong = 0;
    }
    newVal.putLong(0, newLong);
    newValWrapper = ValueWrapper.getWrappedValue(newVal.array(), 0/*flags*/);
    if (r.replace(key, oldValWrapper, newValWrapper)) {
      break;
    }
  }
  
  if (expiration > 0) {
    StorageCommand.getExpiryExecutor().schedule(new Runnable() {
      @Override
      public void run() {
        r.destroy(key);
      }
    }, expiration, TimeUnit.SECONDS);
  }
  
  if (getLogger().fineEnabled()) {
    getLogger().fine("decr:key:"+key+" decrBy:"+decrBy+" initVal:"+initialVal+" exp:"+expiration+" notFound:"+notFound);
  }
  
  ByteBuffer response = null;
  if (notFound) {
    response = request.getResponse();
    response.putShort(POSITION_RESPONSE_STATUS, ResponseStatus.KEY_NOT_FOUND.asShort());
  } else {
    if (isQuiet()) {
      return null;
    }
    response = request.getResponse(HEADER_LENGTH + LONG_LENGTH);
    response.putInt(TOTAL_BODY_LENGTH_INDEX, LONG_LENGTH);
    response.putLong(HEADER_LENGTH, newVal.getLong(0));
    response.putLong(POSITION_CAS, newValWrapper.getVersion());
  }
  return response;
}
 
Example 19
Source File: RocketMQSerializable.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
public static byte[] rocketMQProtocolEncode(RemotingCommand cmd) {
    // String remark
    byte[] remarkBytes = null;
    int remarkLen = 0;
    if (cmd.getRemark() != null && cmd.getRemark().length() > 0) {
        remarkBytes = cmd.getRemark().getBytes(CHARSET_UTF8);
        remarkLen = remarkBytes.length;
    }

    // HashMap<String, String> extFields
    byte[] extFieldsBytes = null;
    int extLen = 0;
    if (cmd.getExtFields() != null && !cmd.getExtFields().isEmpty()) {
        extFieldsBytes = mapSerialize(cmd.getExtFields());
        extLen = extFieldsBytes.length;
    }

    int totalLen = calTotalLen(remarkLen, extLen);

    ByteBuffer headerBuffer = ByteBuffer.allocate(totalLen);
    // int code(~32767)
    headerBuffer.putShort((short) cmd.getCode());
    // LanguageCode language
    headerBuffer.put(cmd.getLanguage().getCode());
    // int version(~32767)
    headerBuffer.putShort((short) cmd.getVersion());
    // int opaque
    headerBuffer.putInt(cmd.getOpaque());
    // int flag
    headerBuffer.putInt(cmd.getFlag());
    // String remark
    if (remarkBytes != null) {
        headerBuffer.putInt(remarkBytes.length);
        headerBuffer.put(remarkBytes);
    } else {
        headerBuffer.putInt(0);
    }
    // HashMap<String, String> extFields;
    if (extFieldsBytes != null) {
        headerBuffer.putInt(extFieldsBytes.length);
        headerBuffer.put(extFieldsBytes);
    } else {
        headerBuffer.putInt(0);
    }

    return headerBuffer.array();
}
 
Example 20
Source File: PacketWriteHelper.java    From aion-germany with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Write short to buffer.
 *
 * @param buf
 * @param value
 */
protected final void writeH(ByteBuffer buf, int value) {
	buf.putShort((short) value);
}