Java Code Examples for com.gemstone.gemfire.cache.Region#replace()

The following examples show how to use com.gemstone.gemfire.cache.Region#replace() . 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: WanSecurity.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Same as the putSequentialKeysTask() but with the keys prefixed with
 * "writer" Adds the key to the ArrayList
 */
public static void putSequentialKeysTaskForWriter() throws Exception {   
  Region region = RegionHelper.getRegion(regionNames.get(0));
  String key = "writer_"
      + WANBlackboard.getInstance().getSharedCounters().incrementAndRead(
          WANBlackboard.currentEntry_writer);
  Log.getLogWriter().info("The vm will be operating on the key : " + key);
  keyList.add(key);

  int sleepMs = CacheClientPrms.getSleepSec() * 1000;
  for (int i = 1; i <= ITERATIONS; i++) {
    if (TestConfig.tab().getRandGen().nextBoolean()) {
      region.put(key, new Integer(i));
    }
    else {
      Object v = region.replace(key, new Integer(i));
      if (v == null) { // force update
        region.put(key, new Integer(i));
      }
    }
  }    
}
 
Example 2
Source File: EntryOperations.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public synchronized static void putAllKeysInRange() {
  Region region = RegionHelper.getRegion(regionName);
  for (int keyRng = 0; keyRng < PUT_KEY_RANGE; keyRng++) {
    String Key = "KEY-" + keyRng;
    String Value = Key + "_VALUE";
    Log.getLogWriter().info("key is: " + Key);
    if (TestConfig.tab().getRandGen().nextBoolean()) {
    region.put(Key, Value);
    } else {
      Object v = region.putIfAbsent(Key, Value);
      if (v != null) {
        region.replace(Key, Value);
  }
}
  }
}
 
Example 3
Source File: WanSecurity.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Same as the putSequentialKeysTask() but with the keys prefixed with
 * "reader" Adds the key to the ArrayList
 */
public static void putSequentialKeysTaskForReader() throws Exception {
  Region region = RegionHelper.getRegion(regionNames.get(0));
  String key = "reader_"
      + WANBlackboard.getInstance().getSharedCounters().incrementAndRead(
          WANBlackboard.currentEntry_reader);
  Log.getLogWriter().info("The vm will be operating on the key : " + key);
  keyList.add(key);

  int sleepMs = CacheClientPrms.getSleepSec() * 1000;
  for (int i = 1; i <= ITERATIONS; i++) {
    if (TestConfig.tab().getRandGen().nextBoolean()) {
      region.put(key, new Integer(i));
    }
    else {
      Object v = region.replace(key, new Integer(i));
      if (v == null) { // force update
        region.put(key, new Integer(i));
      }
    }
  }
}
 
Example 4
Source File: WanSecurity.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Same as the putSequentialKeysTask() but with the keys prefixed with
 * "writer" Adds the key to the ArrayList
 */
public static void putSequentialKeysTaskForWriter() throws Exception {   
  Region region = RegionHelper.getRegion(regionNames.get(0));
  String key = "writer_"
      + WANBlackboard.getInstance().getSharedCounters().incrementAndRead(
          WANBlackboard.currentEntry_writer);
  Log.getLogWriter().info("The vm will be operating on the key : " + key);
  keyList.add(key);

  int sleepMs = CacheClientPrms.getSleepSec() * 1000;
  for (int i = 1; i <= ITERATIONS; i++) {
    if (TestConfig.tab().getRandGen().nextBoolean()) {
      region.put(key, new Integer(i));
    }
    else {
      Object v = region.replace(key, new Integer(i));
      if (v == null) { // force update
        region.put(key, new Integer(i));
      }
    }
  }    
}
 
Example 5
Source File: EntryOperations.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public static void updateKeysInRegion(Region aRegion) {
  long thrdNum = SecurityClientBB.getBB().getSharedCounters()
      .incrementAndRead(SecurityClientBB.threadCount);
  for (int keyRng = 0; keyRng < PUT_KEY_RANGE; keyRng++) {
    String Key = getKeyForOperation();
    String Value = Key + "_VALUE";
    Log.getLogWriter().info("key is: " + Key);
    if (TestConfig.tab().getRandGen().nextBoolean()) {
    aRegion.put(Key, Value);
    } else {
      Object v = aRegion.putIfAbsent(Key, Value);
      if (v != null) {
        aRegion.replace(Key, v, Value);
  }
}
  }
}
 
Example 6
Source File: EntryOperations.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public synchronized static void populateNonSecureRegion() {
  Region nonSecureRegion = RegionHelper.getRegion(NON_SECURE_REGION_NAME);
  if (nonSecureRegion == null)
    return;
  for (int keyRng = 0; keyRng < PUT_KEY_RANGE; keyRng++) {
    String Key = "KEY-" + keyRng;
    String Value = Key + "_VALUE";
    Log.getLogWriter().info("key is: " + Key);
    if (TestConfig.tab().getRandGen().nextBoolean()) {
    nonSecureRegion.put(Key, Value);
    } else {
      Object v = nonSecureRegion.putIfAbsent(Key, Value);
      if (v != null) {
        nonSecureRegion.replace(Key, Value);
  }
}
  }
}
 
Example 7
Source File: EntryOperations.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public synchronized static void populateNonSecureRegion() {
  Region nonSecureRegion = RegionHelper.getRegion(NON_SECURE_REGION_NAME);
  if (nonSecureRegion == null)
    return;
  for (int keyRng = 0; keyRng < PUT_KEY_RANGE; keyRng++) {
    String Key = "KEY-" + keyRng;
    String Value = Key + "_VALUE";
    Log.getLogWriter().info("key is: " + Key);
    if (TestConfig.tab().getRandGen().nextBoolean()) {
    nonSecureRegion.put(Key, Value);
    } else {
      Object v = nonSecureRegion.putIfAbsent(Key, Value);
      if (v != null) {
        nonSecureRegion.replace(Key, Value);
  }
}
  }
}
 
Example 8
Source File: ReplaceCommand.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@Override
public ByteBuffer processBinaryStorageCommand(Object key, byte[] value, long cas,
    int flags, Cache cache, ByteBuffer response) {
  Region<Object, ValueWrapper> r = getMemcachedRegion(cache);
  ValueWrapper val = ValueWrapper.getWrappedValue(value, flags);
  boolean success = false;
  
  if (cas != 0L) {
    ValueWrapper expected = ValueWrapper.getDummyValue(cas);
    success = r.replace(key, expected, val);
  } else {
    success = r.replace(key, val) == null;
  }
  
  if (getLogger().fineEnabled()) {
    getLogger().fine("replace:key:"+key+" cas:"+cas+" success:"+success);
  }
  
  // set status
  if (success) {
    if (isQuiet()) {
      return null;
    }
    response.putShort(POSITION_RESPONSE_STATUS, ResponseStatus.KEY_EXISTS.asShort());
    response.putLong(POSITION_CAS, cas);
  } else {
    response.putShort(POSITION_RESPONSE_STATUS, ResponseStatus.NO_ERROR.asShort());
    // set CAS
    response.putLong(POSITION_CAS, val.getVersion());
  }
  return response;
}
 
Example 9
Source File: SetCommand.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@Override
public ByteBuffer processBinaryStorageCommand(Object key, byte[] value, long cas,
    int flags, Cache cache, ByteBuffer response) {
  Region<Object, ValueWrapper> r = getMemcachedRegion(cache);
  ValueWrapper val = ValueWrapper.getWrappedValue(value, flags);
  boolean success = true;

  if (cas != 0L) {
    ValueWrapper expected = ValueWrapper.getDummyValue(cas);
    success = r.replace(key, expected, val);
  } else {
    r.put(key, val);
  }
  
  if (getLogger().fineEnabled()) {
    getLogger().fine("set key:"+key+" succedded:"+success);
  }
  
  if (success) {
    if (isQuiet()) {
      return null;
    }
    response.putShort(POSITION_RESPONSE_STATUS, ResponseStatus.NO_ERROR.asShort());
    response.putLong(POSITION_CAS, val.getVersion());
  } else {
    response.putShort(POSITION_RESPONSE_STATUS, ResponseStatus.KEY_EXISTS.asShort());
  }
  
  return response;
}
 
Example 10
Source File: WanSecurity.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Same as the putSequentialKeysTask() but with the keys prefixed with
 * "invalid"
 */
public static void putSequentialKeysTaskForInValid() throws Exception {
  Set regionVisited = new HashSet();
  for (String regionName : regionNames) {
    if (!regionVisited.contains(regionName)) {
      regionVisited.add(regionName);
      Region region = RegionHelper.getRegion(regionName);
      Log.getLogWriter()
          .info(
              "putSequentialKeysTaskForInValid : working on region "
                  + regionName);

      String key = INVALID_PRIFIX
          + +WANBlackboard.getInstance().getSharedCounters()
              .incrementAndRead(WANBlackboard.currentEntry_invalid);
      Log.getLogWriter().info("The vm will be operating on the key : " + key);

      for (int i = 1; i <= ITERATIONS; i++) {
        if (TestConfig.tab().getRandGen().nextBoolean()) {
          region.put(key, new Integer(i));
        }
        else {
          Object v = region.replace(key, new Integer(i));
          if (v == null) { // force update
            region.put(key, new Integer(i));
          }
        }
      }
    }
  }
}
 
Example 11
Source File: WanSecurity.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Same as the putSequentialKeysTask() but with the keys prefixed with "valid"
 */
public static void putSequentialKeysTaskForValid() throws Exception {
  Set regionVisited = new HashSet();
  for (String regionName : regionNames) {
    if (!regionVisited.contains(regionName)) {
      regionVisited.add(regionName);
      Region region = RegionHelper.getRegion(regionName);
      Log.getLogWriter().info(
          "putSequentialKeysTaskForValid : working on region " + regionName);

      String key = VALID_PRIFIX
          + +WANBlackboard.getInstance().getSharedCounters()
              .incrementAndRead(WANBlackboard.currentEntry_valid);
      Log.getLogWriter().info("The vm will be operating on the key : " + key);

      for (int i = 1; i <= ITERATIONS; i++) {
        if (TestConfig.tab().getRandGen().nextBoolean()) {
          region.put(key, new Integer(i));
        }
        else {
          Object v = region.replace(key, new Integer(i));
          if (v == null) { // force update
            region.put(key, new Integer(i));
          }
        }

      }
    }
  }
}
 
Example 12
Source File: WanSecurity.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Same as the putSequentialKeysTask() but with the keys prefixed with
 * "invalid"
 */
public static void putSequentialKeysTaskForInValid() throws Exception {
  Set regionVisited = new HashSet();
  for (String regionName : regionNames) {
    if (!regionVisited.contains(regionName)) {
      regionVisited.add(regionName);
      Region region = RegionHelper.getRegion(regionName);
      Log.getLogWriter()
          .info(
              "putSequentialKeysTaskForInValid : working on region "
                  + regionName);

      String key = INVALID_PRIFIX
          + +WANBlackboard.getInstance().getSharedCounters()
              .incrementAndRead(WANBlackboard.currentEntry_invalid);
      Log.getLogWriter().info("The vm will be operating on the key : " + key);

      for (int i = 1; i <= ITERATIONS; i++) {
        if (TestConfig.tab().getRandGen().nextBoolean()) {
          region.put(key, new Integer(i));
        }
        else {
          Object v = region.replace(key, new Integer(i));
          if (v == null) { // force update
            region.put(key, new Integer(i));
          }
        }
      }
    }
  }
}
 
Example 13
Source File: MyTransactionFunction.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
private void verifyTransactionRollback(RegionFunctionContext ctx) {
  Region custPR = ctx.getDataSet();
  Region orderPR = custPR.getCache().getRegion(PRTransactionDUnitTest.OrderPartitionedRegionName);
  CacheTransactionManager mgr = custPR.getCache()
      .getCacheTransactionManager();
  ArrayList args = (ArrayList)ctx.getArguments();
  CustId custId = (CustId)args.get(1);
  Customer newCus = (Customer)args.get(2);
  OrderId orderId = (OrderId)args.get(3);
  Order order = (Order)args.get(4);
  Customer oldCustomer = (Customer)custPR.get(custId);
  Order oldOrder = (Order)orderPR.get(orderId);
  mgr.begin();
  custPR.put(custId, newCus);
  Customer txCust = (Customer)custPR.get(custId);
  orderPR.put(orderId, order);
  Order txOrder = (Order)orderPR.get(orderId);
  Assert.assertTrue(newCus.equals(txCust), "Expected Customer to be:"
      + newCus + " but was:" + txCust);
  Assert.assertTrue(txOrder.equals(order), "Expected Order to be:" + order
      + " but was:" + txOrder);
  mgr.rollback();
  Customer commitedCust = (Customer)custPR.get(custId);
  Assert.assertTrue(oldCustomer.equals(commitedCust),
      "Expected Customer to be:" + oldCustomer + " but was:" + commitedCust);
  Order commitedOrder = (Order)orderPR.get(orderId);
  Assert.assertTrue(oldOrder.equals(commitedOrder), "Expected Order to be:"
      + oldOrder + " but was:" + commitedOrder);
  
  mgr.begin();
  Assert.assertTrue(custPR.remove(custId, oldCustomer));
  orderPR.replace(orderId, order);
  mgr.rollback();
  
  Assert.assertTrue(oldCustomer.equals(custPR.get(custId)));
  Assert.assertTrue(oldOrder.equals(orderPR.get(orderId)));
  
  mgr.begin();
  Assert.assertTrue(custPR.replace(custId, oldCustomer, newCus));
  orderPR.remove(orderId, oldOrder);
  Assert.assertTrue(null == orderPR.putIfAbsent(orderId, order));
  mgr.rollback();
  Assert.assertTrue(oldCustomer.equals(custPR.get(custId)));
  Assert.assertTrue(oldOrder.equals(orderPR.get(orderId)));
  
}
 
Example 14
Source File: MyTransactionFunction.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
private void verifyTransactionRollback(RegionFunctionContext ctx) {
  Region custPR = ctx.getDataSet();
  Region orderPR = custPR.getCache().getRegion(PRTransactionDUnitTest.OrderPartitionedRegionName);
  CacheTransactionManager mgr = custPR.getCache()
      .getCacheTransactionManager();
  ArrayList args = (ArrayList)ctx.getArguments();
  CustId custId = (CustId)args.get(1);
  Customer newCus = (Customer)args.get(2);
  OrderId orderId = (OrderId)args.get(3);
  Order order = (Order)args.get(4);
  Customer oldCustomer = (Customer)custPR.get(custId);
  Order oldOrder = (Order)orderPR.get(orderId);
  mgr.begin();
  custPR.put(custId, newCus);
  Customer txCust = (Customer)custPR.get(custId);
  orderPR.put(orderId, order);
  Order txOrder = (Order)orderPR.get(orderId);
  Assert.assertTrue(newCus.equals(txCust), "Expected Customer to be:"
      + newCus + " but was:" + txCust);
  Assert.assertTrue(txOrder.equals(order), "Expected Order to be:" + order
      + " but was:" + txOrder);
  mgr.rollback();
  Customer commitedCust = (Customer)custPR.get(custId);
  Assert.assertTrue(oldCustomer.equals(commitedCust),
      "Expected Customer to be:" + oldCustomer + " but was:" + commitedCust);
  Order commitedOrder = (Order)orderPR.get(orderId);
  Assert.assertTrue(oldOrder.equals(commitedOrder), "Expected Order to be:"
      + oldOrder + " but was:" + commitedOrder);
  
  mgr.begin();
  Assert.assertTrue(custPR.remove(custId, oldCustomer));
  orderPR.replace(orderId, order);
  mgr.rollback();
  
  Assert.assertTrue(oldCustomer.equals(custPR.get(custId)));
  Assert.assertTrue(oldOrder.equals(orderPR.get(orderId)));
  
  mgr.begin();
  Assert.assertTrue(custPR.replace(custId, oldCustomer, newCus));
  orderPR.remove(orderId, oldOrder);
  Assert.assertTrue(null == orderPR.putIfAbsent(orderId, order));
  mgr.rollback();
  Assert.assertTrue(oldCustomer.equals(custPR.get(custId)));
  Assert.assertTrue(oldOrder.equals(orderPR.get(orderId)));
  
}
 
Example 15
Source File: EntryOperations.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public synchronized static void doInitialFeed() {
  Boolean putOpFoundInOpList = false;
  Region region = null;
  String userName = null;
  if (PoolHelper.getPool("brloader").getMultiuserAuthentication()) {
    Iterator iter = PerUserRequestSecurityTest.proxyRegionMap.keySet()
        .iterator();
    while (iter.hasNext()) {
      putOpFoundInOpList = false;
      userName = (String)iter.next();
      Map<String, ArrayList<String>> userRoleOpMap = PerUserRequestSecurityTest.userToRolesMap
          .get(userName);
      Iterator userRoleOpIter = userRoleOpMap.keySet().iterator();
      while (userRoleOpIter.hasNext()) {
        String roleName = (String)userRoleOpIter.next();
        ArrayList<String> roleOpNames = userRoleOpMap.get(roleName);
        for (int i = 0; i < roleOpNames.size(); i++) {
          if (roleOpNames.get(i).equalsIgnoreCase("PUT")) {
            putOpFoundInOpList = true;

          }
        }
        if (putOpFoundInOpList)
          break;
      }
      if (putOpFoundInOpList) {
        break;
      }
    }
    if(putOpFoundInOpList){
    region = PerUserRequestSecurityTest.proxyRegionMap.get(userName);
    Log.getLogWriter().info("Got the proxyRegion for user :: " + userName);
    }
    else {
      Log.getLogWriter().info("No user found with PUT permission.");
    }
  }

  else {
    region = RegionHelper.getRegion(regionName);
  }
  for (int keyRng = 0; keyRng < PUT_KEY_RANGE; keyRng++) {
    String Key = getKeyForOperation();
    Long Value = new Long(1);
    if (TestConfig.tab().getRandGen().nextBoolean()) {
    region.put(Key, Value);
    } else {
      Object v = region.putIfAbsent(Key, Value);
      if (v != null) {
         region.replace(Key, Value);
  }
}
  }
}
 
Example 16
Source File: EntryOperations.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public synchronized static void doInitialFeed() {
  Boolean putOpFoundInOpList = false;
  Region region = null;
  String userName = null;
  if (PoolHelper.getPool("brloader").getMultiuserAuthentication()) {
    Iterator iter = PerUserRequestSecurityTest.proxyRegionMap.keySet()
        .iterator();
    while (iter.hasNext()) {
      putOpFoundInOpList = false;
      userName = (String)iter.next();
      Map<String, ArrayList<String>> userRoleOpMap = PerUserRequestSecurityTest.userToRolesMap
          .get(userName);
      Iterator userRoleOpIter = userRoleOpMap.keySet().iterator();
      while (userRoleOpIter.hasNext()) {
        String roleName = (String)userRoleOpIter.next();
        ArrayList<String> roleOpNames = userRoleOpMap.get(roleName);
        for (int i = 0; i < roleOpNames.size(); i++) {
          if (roleOpNames.get(i).equalsIgnoreCase("PUT")) {
            putOpFoundInOpList = true;

          }
        }
        if (putOpFoundInOpList)
          break;
      }
      if (putOpFoundInOpList) {
        break;
      }
    }
    if(putOpFoundInOpList){
    region = PerUserRequestSecurityTest.proxyRegionMap.get(userName);
    Log.getLogWriter().info("Got the proxyRegion for user :: " + userName);
    }
    else {
      Log.getLogWriter().info("No user found with PUT permission.");
    }
  }

  else {
    region = RegionHelper.getRegion(regionName);
  }
  for (int keyRng = 0; keyRng < PUT_KEY_RANGE; keyRng++) {
    String Key = getKeyForOperation();
    Long Value = new Long(1);
    if (TestConfig.tab().getRandGen().nextBoolean()) {
    region.put(Key, Value);
    } else {
      Object v = region.putIfAbsent(Key, Value);
      if (v != null) {
         region.replace(Key, Value);
  }
}
  }
}
 
Example 17
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 18
Source File: WANTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public void putSequentialKeys(Region region) throws Exception {
  if (region == null) {
    throw new TestException("Region in putSequentialKeys is " + region);
  }

  // init class loader if pdx is enabled
  PdxTest.initClassLoader();

  int putAllOps = 5; // 1 out of 5 chances to perform putAll operation

  // add putAll task
  int sleepMs = WANTestPrms.getSleepSec() * 1000;

  for (int j = 0; j < WANTestPrms.getBatchSize(); j++) {
    int doPutAll = rand.nextInt(putAllOps);
    if (doPutAll == 1) {
      putSequentialKeyUsingPutAll(region, sleepMs);
    } else {
      long opsCounter = bb.getSharedCounters().read(
          WANBlackboard.operation_counter);
      if ((opsCounter + ITERATIONS) > maxOperations) {
        // stop scheduling task
        throw new StopSchedulingOrder(
            "Time to stop as max number of operations reached. Operations="
                + opsCounter);
      }

      opsCounter = bb.getSharedCounters().add(
          WANBlackboard.operation_counter, ITERATIONS);
      Long keyCounter = bb.increamentAndReadKeyCounter(region.getName(), 1);
      Object key = getKeyForCounter(keyCounter.longValue());

      logger.info("Working on key :" + key + " for region "
          + region.getFullPath() + " opsCounter=" + opsCounter);
      for (long i = 1; i <= ITERATIONS; i++) {
        MasterController.sleepForMs(sleepMs);

        BaseValueHolder val = getValueForCounter(i);
        Object v = region.replace(key, val);
        if (v == null) { // force replacement
          region.put(key, val);
        }
      }
    }
  }
}
 
Example 19
Source File: IncrementCommand.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 incrBy = 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 + incrBy;
    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("incr:key:"+key+" incrBy:"+incrBy+" 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 20
Source File: IncrementCommand.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 incrBy = 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 + incrBy;
    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("incr:key:"+key+" incrBy:"+incrBy+" 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;
}