public void addOperation(CASOperation op) {
    ops.add(op);

    // Count the bytes required by this operation.
    Iterator<String> is = op.getKeys().iterator();
    String k = is.next();
    int keylen = KeyUtil.getKeyBytes(k).length;

    byteCount += MIN_RECV_PACKET + StoreOperationImpl.EXTRA_LEN + keylen + op.getData().length;
  }
  public void testCASOperationCloning() {
    CASOperation op =
        ofact.cas(StoreType.set, "someKey", 727582, 8174, 7175, testData, genericCallback);

    CASOperation op2 = cloneOne(CASOperation.class, op);
    assertKey(op2);
    assertEquals(727582, op2.getCasValue());
    assertEquals(8174, op2.getFlags());
    assertEquals(7175, op2.getExpiration());
    assertBytes(op2.getBytes());
    assertCallback(op2);
  }
  private Operation optimizeSets() {
    // make sure there are at least two get operations in a row before
    // attempting to optimize them.
    Operation optimizedOp = writeQ.remove();
    if (writeQ.peek() instanceof CASOperation) {
      OptimizedSetImpl og = new OptimizedSetImpl((CASOperation) optimizedOp);
      optimizedOp = og;

      while (writeQ.peek() instanceof StoreOperation
          && og.size() < MAX_SET_OPTIMIZATION_COUNT
          && og.bytes() < MAX_SET_OPTIMIZATION_BYTES) {
        CASOperation o = (CASOperation) writeQ.remove();
        if (!o.isCancelled()) {
          og.addOperation(o);
        }
      }

      // Initialize the new mega set
      optimizedOp.initialize();
      assert optimizedOp.getState() == OperationState.WRITING;
    }

    return optimizedOp;
  }
  @Override
  public void initialize() {
    // Now create a buffer.
    ByteBuffer bb = ByteBuffer.allocate(byteCount);
    for (CASOperation so : ops) {
      Iterator<String> is = so.getKeys().iterator();
      String k = is.next();
      byte[] keyBytes = KeyUtil.getKeyBytes(k);
      assert !is.hasNext();

      int myOpaque = generateOpaque();
      callbacks.put(myOpaque, so.getCallback());
      byte[] data = so.getData();

      // Custom header
      bb.put(REQ_MAGIC);
      bb.put((byte) cmdMap(so.getStoreType()));
      bb.putShort((short) keyBytes.length);
      bb.put((byte) StoreOperationImpl.EXTRA_LEN); // extralen
      bb.put((byte) 0); // data type
      bb.putShort(((VBucketAware) so).getVBucket(k)); // vbucket
      bb.putInt(keyBytes.length + data.length + StoreOperationImpl.EXTRA_LEN);
      bb.putInt(myOpaque);
      bb.putLong(so.getCasValue()); // cas
      // Extras
      bb.putInt(so.getFlags());
      bb.putInt(so.getExpiration());
      // the actual key
      bb.put(keyBytes);
      // And the value
      bb.put(data);
    }
    // Add the noop
    bb.put(REQ_MAGIC);
    bb.put((byte) NoopOperationImpl.CMD);
    bb.putShort((short) 0);
    bb.put((byte) 0); // extralen
    bb.put((byte) 0); // data type
    bb.putShort((short) 0); // reserved
    bb.putInt(0);
    bb.putInt(terminalOpaque);
    bb.putLong(0); // cas

    bb.flip();
    setBuffer(bb);
  }