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

The following examples show how to use com.gemstone.gemfire.cache.Region#get() . 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: RegionUtil.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public static void checkRegionKeyExistsValueExists(Region r, Object key, Object value) {
  if (HydraUtil.isSerialTest()) {
    if (value == null)
      throw new TestException("Expected value can not be null ");

    checkRegionKeyExists(r, key);
    Object regionValue = r.get(key);
    if (regionValue == null) {
      throw new TestException("Region " + r.getName() + " value for  " + key + " is " + regionValue
          + " but expected " + value);
    }

    if (regionValue != null && !regionValue.equals(value)) {
      throw new TestException("Region " + r.getName() + " value for  " + key + " is " + regionValue
          + " but expected " + value);
    }
  }
}
 
Example 2
Source File: PeerTypeRegistration.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
private EnumId allocateEnumId() {
  TXStateInterface currentState = suspendTX();
  Region<Object, Object> r = getIdToType();
  try {
    //Find the next available type id.
    do {
      this.nextEnumId++;
      if(this.nextEnumId == maxEnumId) {
        throw new InternalGemFireError("Used up all of the PDX enum ids for this distributed system. The maximum number of PDX types is " + maxEnumId);
      }
    } while(r.get(new EnumId(nextEnumId)) != null);

    this.lastAllocatedEnumId = this.nextEnumId;
    return new EnumId(this.nextEnumId);
  } finally {
    resumeTX(currentState);
  }
}
 
Example 3
Source File: RollingUpgradeTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Write snapshot of all the regions into BB
 *
 */
Map writeSnapshot() {
  Map allRegionsSnapshot = new HashMap();
  Set<Region<?,?>>  regions = CacheHelper.getCache().rootRegions();
  Log.getLogWriter().info("Preparing to write snapshot for " + regions.size() + " regions");
  for (Region aRegion: regions) {
    Map regionSnapshot = new HashMap();
    for (Object key: aRegion.keySet()) {
      Object value = null;
      if (aRegion.containsValueForKey(key)) { // won't invoke a loader (if any)
        value = aRegion.get(key);
      }
      if (value instanceof BaseValueHolder) {
        regionSnapshot.put(key, ((BaseValueHolder)value).myValue);
      } else {
        regionSnapshot.put(key, value);
      }
    }
    allRegionsSnapshot.put(aRegion.getFullPath(), regionSnapshot);
    Log.getLogWriter().info("Region snapshot for " + aRegion.getFullPath() + " is size " + regionSnapshot.size() + " and contains keys " + regionSnapshot.keySet());
  }
  RollingUpgradeBB.getBB().getSharedMap().put(allRegionsSnapshotKey, allRegionsSnapshot);
  Log.getLogWriter().info("Put snapshot for " + regions.size() + " regions into blackboard at key " + allRegionsSnapshotKey);
  
  return allRegionsSnapshot;
}
 
Example 4
Source File: PrependCommand.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
@Override
public ByteBuffer processStorageCommand(String key, byte[] value, int flags, Cache cache) {
  Region<Object, ValueWrapper> r = getMemcachedRegion(cache);
  ValueWrapper oldValWrapper = r.get(key);
  String retVal = Reply.NOT_FOUND.toString();
  if (oldValWrapper != null) {
    byte[] oldVal = oldValWrapper.getValue();
    byte[] prependVal = (byte[]) value;
    byte[] newVal = new byte[oldVal.length + prependVal.length];
    System.arraycopy(prependVal, 0, newVal, 0, prependVal.length);
    System.arraycopy(oldVal, 0, newVal, prependVal.length, oldVal.length);
    r.put(key, ValueWrapper.getWrappedValue(newVal, flags));
    retVal = Reply.STORED.toString();
  }
  return asciiCharset.encode(retVal);
}
 
Example 5
Source File: QueryFunctionExecTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Read object
 */
@Override
protected void readObject(Region aRegion) {
  Set aSet = aRegion.keySet();
  if (aSet.size() == 0) {
     Log.getLogWriter().info("readObject: No names in region");
     return;
  }
  Iterator it = aSet.iterator();
  Object key = null;
  if (it.hasNext()) {
    key = it.next();
  } else {
     Log.getLogWriter().info("readObject: Unable to get key from region");
     return; 
  }
  aRegion.get(key);
}
 
Example 6
Source File: ConflationDUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * do a get on region1
 *
 */
public static void get()
{
  try {
    Region r = cache.getRegion(Region.SEPARATOR +REGION_NAME1);
    r.get("key-1");
  }
  catch (Exception ex) {
    ex.printStackTrace();
    fail("failed while region.get()", ex);
  }
}
 
Example 7
Source File: WANClient.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/** Prints the contents of the local cache. */
protected void print(String regionName) {
  // get the number of cache entries (one for each thread in the group)
  long size = WANBlackboard.getInstance().getSharedCounters()
                           .read(WANBlackboard.MaxKeys);

  // print the value of each entry in the local cache
  StringBuffer buffer = new StringBuffer();
  Region region = RegionHelper.getRegion(regionName);
  buffer.append("Contents of region");
  buffer.append(region.getFullPath());
  buffer.append(":");
  for (int i = 0; i < size; i++) {
    Integer key = new Integer(i);
    // use hook to do local get (in clients)
    Object val = DiskRegUtil.getValueInVM(region, key);
    // special case w/partitionedRegions (servers)
    if (region.getAttributes().getPartitionAttributes() != null) {
      val = region.get(key);
    }
    if (val != null) {
      buffer.append("\n\tENTRY ");
      buffer.append(key);
      buffer.append(":");
      buffer.append(val);
    }
  }
  Log.getLogWriter().info(buffer.toString());
}
 
Example 8
Source File: SnapshotTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/** Does a get operation on an existing key.
 *
 *  @param aRegion The region to perform the get on.
 *
 */
protected void getExistingKey(Region aRegion) {
  Object key = obtainExistingKey(aRegion);
  if (key == null) {
    Log.getLogWriter().info("No keys available in " + aRegion.getFullPath() + ", cannot do get on existing key");
    return;
  }
  Log.getLogWriter().info("Getting existing key " + key + " from region " + aRegion.getFullPath());
  Object result = aRegion.get(key);
  Log.getLogWriter().info("Done getting existing key " + key + ", returned value " + result);
}
 
Example 9
Source File: MemoryThresholdsDUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(FunctionContext context) {
  if (context instanceof RegionFunctionContext) {
    RegionFunctionContext regionContext = (RegionFunctionContext)context;
    Region dataSet = regionContext.getDataSet();
    dataSet.get(1);
    regionContext.getResultSender().lastResult("executed");
  } else {
    context.getResultSender().lastResult("executed");
  }
}
 
Example 10
Source File: SimplePrintUtil.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public static int printEntries(Region region, Set keySet, List keyList) throws Exception
{
	if (region == null) {
		System.out.println("Error: Region is null");
		return 0;
	}

	if (keySet.size() == 0) {
		return 0;
	}

	// Print keys and values
	HashSet keyNameSet = new HashSet();
	HashSet valueNameSet = new HashSet();
	int row = 1;
	Object key = null;
	Object value = null;
	for (Iterator iterator = keySet.iterator(); iterator.hasNext();) {
		key = iterator.next();
		value = region.get(key);
		if (keyList != null) {
			keyList.add(key);
		}
		keyNameSet.add(key.getClass().getName());
		if (value != null) {
			valueNameSet.add(value.getClass().getName());
		}
		printObject(row, "Key", key, true);
		printObject(row, "Value", value, false);
		row++;
	}
	System.out.println();
	for (Object keyName : keyNameSet) {
		System.out.println("  Key Class: " + keyName);
	}
	for (Object valueName : valueNameSet) {
		System.out.println("Value Class: " + valueName);
	}
	return row - 1;
}
 
Example 11
Source File: RecycleSystem.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public static void invokeCacheMiss() {
  Cache cache = CacheFactory.getInstance(DistributedSystemHelper.getDistributedSystem());
  Object[] regionList = cache.rootRegions().toArray();
  int numRegs = regionList.length;

  for (int i = 0; i < numRegs; i++) {
    Region reg = (Region)regionList[i];
    if (!(reg instanceof HARegion)) {
      int keysize = reg.keySet().size();
      for (int j = 0; j < keysize; j++)
        reg.get("notexist" + j);
    }
  }
}
 
Example 12
Source File: HARegionQueueDUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public static void verifyDispatchedMessagesRemoved()
{
  try {
    final Region region = hrq.getRegion();
    // wait until we have a dead
    // server
    WaitCriterion ev = new WaitCriterion() {
      public boolean done() {
        Thread.yield(); // TODO is this necessary?
        return region.get(new Long(0)) == null;
      }
      public String description() {
        return null;
      }
    };
    DistributedTestCase.waitForCriterion(ev, 60 * 1000, 200, true);

    /*
     * if (region.get(new Long(0)) != null) { fail("Expected message to have
     * been deleted but it is not deleted"); }
     */

    if (region.get(new Long(1)) == null) {
      fail("Expected message not to have been deleted but it is deleted");
    }

  }
  catch (Exception e) {
    fail("test failed due to an exception :  " + e);
  }
}
 
Example 13
Source File: PdxInstanceFactoryJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public void testPdxInstancePut() throws IOException {
  Region r = cache.createRegionFactory(RegionShortcut.LOCAL).create("testPdxInstancePut");
  PdxInstanceFactory c = PdxInstanceFactoryImpl.newCreator("testPdxInstancePut", false);
  c.writeField("f", 37, int.class);
  PdxInstance pi = c.create();
  r.put("key", pi);
  PdxInstance pi2 = (PdxInstance)r.get("key");
  assertEquals(pi, pi2);
}
 
Example 14
Source File: ConcCQMultRegionsClient.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
protected void removeObject(String regionName) {
  String key = null;
  long counter = CQUtilBB.getBB().getSharedCounters().incrementAndRead(CQUtilBB.NumCounterToDestroy);

  Region region = RegionHelper.getRegion(regionName);
  if (region != null) {        
    int temp = rnd.nextInt(2);
    key = (temp>0) ? thePrimarySecId : NameFactory.getObjectNameForCounter(counter);
    //key = NameFactory.getObjectNameForCounter(counter);
    if (counter <= 100) {
      MasterController.sleepForMs(1000);
    } //to avoid bug 35662 -- allow the put key event propogated to the p2p bridges first before destory 
    if (counter <= 100) {
      MasterController.sleepForMs(1000);
    } //to avoid bug 35662 -- allow the put key event propogated to the p2p bridges first before destory 
    if (counter <= 100) {
      MasterController.sleepForMs(1000);
    } //to avoid bug 35662 -- allow the put key event propogated to the p2p bridges first before destory 
    Object got = region.get(key); 
    if (got != null) {
      region.remove(key);
      Log.getLogWriter().info("successfully removed this key: " + key + " and value " + got.toString());
      if (createIndex) {
        if (testPrimaryIndex  && ((Position)got).getSecId().equals(thePrimarySecId)) {
          updateBBForRemoves(regionName, key);
        }
      }
      else {
        updateBBForRemoves(regionName, key);
      }
   }
  }    
}
 
Example 15
Source File: MemoryThresholdsDUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(FunctionContext context) {
  if (context instanceof RegionFunctionContext) {
    RegionFunctionContext regionContext = (RegionFunctionContext)context;
    Region dataSet = regionContext.getDataSet();
    dataSet.get(1);
    regionContext.getResultSender().lastResult("executed");
  } else {
    context.getResultSender().lastResult("executed");
  }
}
 
Example 16
Source File: ConflationDUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * do a get on region1
 *
 */
public static void get()
{
  try {
    Region r = cache.getRegion(Region.SEPARATOR +REGION_NAME1);
    r.get("key-1");
  }
  catch (Exception ex) {
    ex.printStackTrace();
    fail("failed while region.get()", ex);
  }
}
 
Example 17
Source File: SnapshotTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/** Return an object to be used to update the given key. If the
 *  value for the key is a ValueHolder, then get an alternate
 *  value which is similar to it's previous value (see
 *  ValueHolder.getAlternateValueHolder()).
 *
 *  @param aRegion The region which possible contains key.
 *  @param key The key to get a new value for.
 *  
 *  @returns An update to be used to update key in aRegion.
 */
protected Object getUpdateObject(Region r, String key) {
  Object anObj = r.get(key);
  Object newObj = null;
  if ((anObj == null) || (!(anObj instanceof BaseValueHolder))) {
    newObj = getValueForKey(key);
  } else {
    newObj = ((BaseValueHolder)anObj).getAlternateValueHolder(randomValues);
  }
  if ((newObj instanceof BaseValueHolder) && TestConfig.tab().getRandGen().nextBoolean()) {
    return ((BaseValueHolder)newObj).extraObject;
  } else {
    return newObj;
  }
}
 
Example 18
Source File: DiskRegionJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * DiskRegionStatsJUnitTest :
 *  
 */
public void testStats()
{
  final int overflowCapacity = 100;
  int counter = 0;
  DiskRegionProperties diskRegionProperties = new DiskRegionProperties();
  diskRegionProperties.setDiskDirs(null);
  diskRegionProperties.setOverFlowCapacity(overflowCapacity);
  diskRegionProperties.setMaxOplogSize(2097152);
  diskRegionProperties.setRolling(true);

  Region region = DiskRegionHelperFactory.getSyncOverFlowOnlyRegion(cache,
      diskRegionProperties);

  DiskRegionStats stats = ((LocalRegion)region).getDiskRegion().getStats();

  for (int i = 0; i < 5000; i++) {
    region.put(new Integer(i), new Integer(i));
    region.put(new Integer(i), new Integer(i));
    region.put(new Integer(i), new Integer(i));
    if (i > overflowCapacity + 5) {
      region.get(new Integer(++counter));
      region.get(new Integer(counter));
    }

    if (i > overflowCapacity) {
      if (!(stats.getNumEntriesInVM() == overflowCapacity)) {
        fail(" number of entries is VM should be equal to overflow capacity");
      }
      if (!(stats.getNumOverflowOnDisk() - 1 == i - overflowCapacity)) {
        fail(" number of entries on disk not corrected expected "
            + (i - overflowCapacity) + " but is "
            + stats.getNumOverflowOnDisk());
      }
    }
  }
}
 
Example 19
Source File: UniqueKeyIndexTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Test Mics methods added to get GemFireKey,
 */
public void testMiscGetGemFireKey() throws SQLException, StandardException {

  Connection conn = getConnection();
  Statement s = conn.createStatement();

  s.execute("create table TestTable (c1 int primary key, c2 int NOT NULL, " +
      "c3 char(20) NOT NULL, c4 int , UNIQUE (c2,c3))"+ getOverflowSuffix());

  s.execute("insert into TestTable (c1, c2, c3, c4) values (10, 10, 'XXXX', 10)");
  s.execute("insert into TestTable (c1, c2, c3, c4) values (20, 20, 'YYYY', 20)");
  s.execute("insert into TestTable (c1, c2, c3, c4) values (30, 30, 'ZZZZ', 30)");
  s.execute("insert into TestTable (c1, c2, c3, c4) values (40, 30, 'XXXX', 40)");

  //Remember to captilize the name.
  final Region<?, ?> tableRegion = Misc
      .getRegionForTable(getCurrentDefaultSchemaName() + ".TESTTABLE", true);

  RegionKey key = getGemFireKey(10, tableRegion);
  Object value = tableRegion.get(key);
  assertNotNull("Value cannot be null", value);

  int i = 20;
  key = getGemFireKey(i, tableRegion);
  value = tableRegion.get(key);
  assertNotNull("Value cannot be null", value);
}
 
Example 20
Source File: ClientWorker.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

    System.out.println("Connecting to the distributed system and creating the cache.");
    // Create the cache which causes the cache-xml-file to be parsed
    ClientCache cache = new ClientCacheFactory()
        .set("name", "ClientWorker")
        .set("cache-xml-file", "xml/Client.xml")
        .create();

    // Get the exampleRegion
    Region<String, String> exampleRegion = cache.getRegion(EXAMPLE_REGION_NAME);
    System.out.println("Example region \"" + exampleRegion.getFullPath() + "\" created in cache.");
    System.out.println();
    System.out.println("Getting three values from the cache server.");
    System.out.println("This will cause the server's loader to run, which will add the values");
    System.out.println("to the server cache and return them to me. The values will also be");
    System.out.println("forwarded to any other client that has subscribed to the region.");

    // Get three values from the cache
    for (int count = 0; count < 3; count++) {
      String key = "key" + count;
      System.out.println("Getting key " + key);
      exampleRegion.get(key);
    }

    System.out.println("Note the other client's region listener in response to these gets.");
    System.out.println("Press Enter to continue.");
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
    bufferedReader.readLine();

    System.out.println("Changing the data in my cache - all destroys and updates are forwarded");
    System.out.println("through the server to other clients. Invalidations are not forwarded.");

    // Update one value in the cache
    System.out.println("Putting new value for key0");
    exampleRegion.put("key0", "ClientValue0");

    // Invalidate one entry in the cache
    System.out.println("Invalidating key1");
    exampleRegion.invalidate("key1");

    // Destroy one entry in the cache
    System.out.println("Destroying key2");
    exampleRegion.destroy("key2");

    // Close the cache and disconnect from GemFire distributed system
    System.out.println("Closing the cache and disconnecting.");
    cache.close();

    System.out.println("In the other session, please hit Enter in the Consumer client");
    System.out.println("and then stop the cacheserver with 'gfsh stop server --dir=<serverDirectory>'.");
  }