コード例 #1
0
ファイル: SimplePrintUtil.java プロジェクト: netcrest/pado
  /**
   * Prints the region entries. It prints both keys and values formatted.
   *
   * @param region
   * @param startIndex
   * @param startRowNum
   * @param rowCount
   * @param keyList
   * @return Returns the number of rows printed.
   * @throws Exception
   */
  public static int printEntries(
      Region region,
      Iterator regionIterator,
      int startIndex,
      int startRowNum,
      int rowCount,
      List keyList)
      throws Exception {

    if (region == null || regionIterator == null) {
      PadoShell.printlnError("Path is null");
      return 0;
    }

    int endIndex = startIndex + rowCount; // exclusive
    if (endIndex >= region.size()) {
      endIndex = region.size();
    }

    if (startIndex == endIndex) {
      return 0;
    }

    HashSet keyNameSet = new HashSet();
    HashSet valueNameSet = new HashSet();
    Object key = null;
    Object value = null;
    int index = startIndex;

    // Print keys and values
    int row = startRowNum;
    index = startIndex;
    for (Iterator itr = regionIterator; index < endIndex && itr.hasNext(); index++) {
      Region.Entry entry = (Region.Entry) itr.next();
      key = entry.getKey();
      value = entry.getValue();
      keyNameSet.add(key.getClass().getName());
      if (value != null) {
        valueNameSet.add(value.getClass().getName());
      }
      printObject(row, "Key", key, true);
      printObject(row, "Value", value, false);
      PadoShell.println("");
      row++;
    }

    PadoShell.println("");
    PadoShell.println(" Fetch size: " + rowCount);
    PadoShell.println("   Returned: " + (row - 1) + "/" + region.size());
    for (Object keyName : keyNameSet) {
      PadoShell.println("  Key Class: " + keyName);
    }
    for (Object valueName : valueNameSet) {
      PadoShell.println("Value Class: " + valueName);
    }
    return endIndex - startIndex;
  }
  protected void assertRegionContents(Region<?, ?> region, Object... values) {
    assertThat(region.size(), is(equalTo(values.length)));

    for (Object value : values) {
      assertThat(region.containsValue(value), is(true));
    }
  }
コード例 #3
0
 /**
  * Register interest with ALL_KEYS, and InterestPolicyResult = KEYS_VALUES which is equivalent to
  * a full GII.
  *
  * @param aRegion The region to register interest on.
  */
 protected static void registerInterest(Region aRegion) {
   Log.getLogWriter()
       .info("Calling registerInterest for all keys, result interest policy KEYS_VALUES");
   aRegion.registerInterest("ALL_KEYS", InterestResultPolicy.KEYS_VALUES);
   Log.getLogWriter()
       .info(
           "Done calling registerInterest for all keys, "
               + "result interest policy KEYS_VALUES, "
               + aRegion.getFullPath()
               + " size is "
               + aRegion.size());
 }
  @Before
  public void setup() {
    assertThat(users).isNotNull();

    if (users.isEmpty()) {
      for (User user : TEST_USERS) {
        users.put(getKey(user), user);
      }

      assertThat(users.isEmpty()).isFalse();
      assertThat(users.size()).isEqualTo(TEST_USERS.size());
    }
  }
コード例 #5
0
 /**
  * Load a region with keys and values. The number of keys and values is specified by the total
  * number of keys in keyIntervals. This can be invoked by several threads to accomplish the work.
  */
 public void loadRegion() {
   final long LOG_INTERVAL_MILLIS = 10000;
   int numKeysToCreate = keyIntervals.getNumKeys();
   long lastLogTime = System.currentTimeMillis();
   long startTime = System.currentTimeMillis();
   SharedCounters sc = CQUtilBB.getBB().getSharedCounters();
   do {
     long shouldAddCount =
         CQUtilBB.getBB().getSharedCounters().incrementAndRead(CQUtilBB.SHOULD_ADD_COUNT);
     if (shouldAddCount > numKeysToCreate) {
       String aStr =
           "In loadRegion, shouldAddCount is "
               + shouldAddCount
               + ", numOriginalKeysCreated is "
               + sc.read(CQUtilBB.NUM_ORIGINAL_KEYS_CREATED)
               + ", numKeysToCreate is "
               + numKeysToCreate
               + ", region size is "
               + aRegion.size();
       Log.getLogWriter().info(aStr);
       NameBB.getBB().printSharedCounters();
       throw new StopSchedulingTaskOnClientOrder(aStr);
     }
     Object key = NameFactory.getNextPositiveObjectName();
     QueryObject value = getValueToAdd(key);
     value.extra = key;
     Log.getLogWriter().info("Creating with put, key " + key + ", value " + value.toStringFull());
     aRegion.put(key, value);
     sc.increment(CQUtilBB.NUM_ORIGINAL_KEYS_CREATED);
     if (System.currentTimeMillis() - lastLogTime > LOG_INTERVAL_MILLIS) {
       Log.getLogWriter()
           .info(
               "Added "
                   + NameFactory.getPositiveNameCounter()
                   + " out of "
                   + numKeysToCreate
                   + " entries into "
                   + TestHelper.regionToString(aRegion, false));
       lastLogTime = System.currentTimeMillis();
     }
   } while ((minTaskGranularitySec == -1)
       || (System.currentTimeMillis() - startTime < minTaskGranularityMS));
 }
コード例 #6
0
ファイル: GemfireRegionInfo.java プロジェクト: netcrest/pado
  /**
   * Initializes without children.
   *
   * @param region The region from which RegionInfo is extracted.
   */
  @SuppressWarnings({"unchecked", "rawtypes"})
  private void init(Region region) {
    if (region == null) {
      return;
    }
    DistributedMember member =
        CacheFactory.getAnyInstance().getDistributedSystem().getDistributedMember();
    setName(region.getName());
    setFullPath(region.getFullPath());
    GemfireRegionAttributeInfo attrInfo = new GemfireRegionAttributeInfo();
    RegionAttributes<?, ?> attr = region.getAttributes();
    attrInfo.setAttribute(GemfireRegionAttributeInfo.DATA_POLICY, attr.getDataPolicy().toString());
    attrInfo.setAttribute(GemfireRegionAttributeInfo.SCOPE, attr.getScope().toString());
    if (region instanceof PartitionedRegion) {
      PartitionedRegion pr = (PartitionedRegion) region;
      PartitionAttributes pattr = pr.getPartitionAttributes();
      attrInfo.setAttribute(
          GemfireRegionAttributeInfo.LOCAL_MAX_MEMORY, pattr.getLocalMaxMemory() + "");
      attrInfo.setAttribute(
          GemfireRegionAttributeInfo.REDUNDANT_COPIES, pattr.getRedundantCopies() + "");
      attrInfo.setAttribute(
          GemfireRegionAttributeInfo.TOTAL_MAX_MEMORY, pattr.getTotalMaxMemory() + "");
      attrInfo.setAttribute(
          GemfireRegionAttributeInfo.TOTAL_NUM_BUCKETS, pattr.getTotalNumBuckets() + "");

      // data store is null if it's a proxy, i.e., LOCAL_MAX_MEMORY=0
      if (pr.getDataStore() != null) {
        Set<BucketRegion> localtBuketSet = pr.getDataStore().getAllLocalBucketRegions();
        List<BucketInfo> primaryList = new ArrayList<BucketInfo>();
        List<BucketInfo> redundantList = new ArrayList<BucketInfo>();
        this.size = 0;
        for (BucketRegion br : localtBuketSet) {
          BucketInfo bucketInfo =
              new GemfireBucketInfo(
                  br.getId(), br.getBucketAdvisor().isPrimary(), br.size(), br.getTotalBytes());
          //					InternalDistributedMember m = pr.getBucketPrimary(br.getId());
          //					if (m.getId().equals(member.getId())) {
          if (bucketInfo.isPrimary()) {
            primaryList.add(bucketInfo);
            this.size += bucketInfo.getSize();
          } else {
            redundantList.add(bucketInfo);
          }
        }
        Collections.sort(primaryList);
        Collections.sort(redundantList);
        setPrimaryBucketInfoList(primaryList);
        setRedundantBucketInfoList(redundantList);
      }
    } else {
      this.size = region.size();
    }
    setAttrInfo(attrInfo);
    temporalType = GemfireTemporalManager.getTemporalType(region);
    if (region.isDestroyed() == false && region.isEmpty() == false) {
      Set<Map.Entry> regionEntrySet = region.entrySet();
      for (Map.Entry entry : regionEntrySet) {
        Object key = entry.getKey();
        Object value = entry.getValue();
        keyTypeName = key.getClass().getName();
        valueTypeName = value.getClass().getName();
        break;
      }
    }
  }
コード例 #7
0
  /**
   * Verify the contents of the region, taking into account the keys that were destroyed,
   * invalidated, etc (as specified in keyIntervals) Throw an error of any problems are detected.
   * This must be called repeatedly by the same thread until StopSchedulingTaskOnClientOrder is
   * thrown.
   */
  public void verifyRegionContents() {
    final long LOG_INTERVAL_MILLIS = 10000;
    // we already completed this check once; we can't do it again without reinitializing the
    // verify state variables
    if (verifyRegionContentsCompleted) {
      throw new TestException(
          "Test configuration problem; already verified region contents, "
              + "cannot call this task again without resetting batch variables");
    }

    // iterate keys
    long lastLogTime = System.currentTimeMillis();
    long minTaskGranularitySec = TestConfig.tab().longAt(TestHelperPrms.minTaskGranularitySec);
    long minTaskGranularityMS = minTaskGranularitySec * TestHelper.SEC_MILLI_FACTOR;
    long startTime = System.currentTimeMillis();
    long size = aRegion.size();
    boolean first = true;
    int numKeysToCheck = keyIntervals.getNumKeys() + numNewKeys;
    while (verifyRegionContentsIndex < numKeysToCheck) {
      verifyRegionContentsIndex++;
      if (first) {
        Log.getLogWriter()
            .info(
                "In verifyRegionContents, region has "
                    + size
                    + " keys; starting verify at verifyRegionContentsIndex "
                    + verifyRegionContentsIndex
                    + "; verifying key names with indexes through (and including) "
                    + numKeysToCheck);
        first = false;
      }

      // check region size the first time through the loop to avoid it being called
      // multiple times when this is batched
      if (verifyRegionContentsIndex == 1) {
        if (totalNumKeys != size) {
          String tmpStr = "Expected region size to be " + totalNumKeys + ", but it is size " + size;
          Log.getLogWriter().info(tmpStr);
          verifyRegionContentsErrStr.append(tmpStr + "\n");
        }
      }

      Object key = NameFactory.getObjectNameForCounter(verifyRegionContentsIndex);
      try {
        if (((verifyRegionContentsIndex >= keyIntervals.getFirstKey(KeyIntervals.NONE))
                && (verifyRegionContentsIndex <= keyIntervals.getLastKey(KeyIntervals.NONE)))
            || ((verifyRegionContentsIndex >= keyIntervals.getFirstKey(KeyIntervals.GET))
                && (verifyRegionContentsIndex <= keyIntervals.getLastKey(KeyIntervals.GET)))) {
          // this key was untouched after its creation
          checkContainsKey(key, true, "key was untouched");
          checkContainsValueForKey(key, true, "key was untouched");
          Object value = aRegion.get(key);
          checkValue(key, value);
        } else if ((verifyRegionContentsIndex >= keyIntervals.getFirstKey(KeyIntervals.INVALIDATE))
            && (verifyRegionContentsIndex <= keyIntervals.getLastKey(KeyIntervals.INVALIDATE))) {
          checkContainsKey(key, true, "key was invalidated");
          checkContainsValueForKey(key, false, "key was invalidated");
        } else if ((verifyRegionContentsIndex
                >= keyIntervals.getFirstKey(KeyIntervals.LOCAL_INVALIDATE))
            && (verifyRegionContentsIndex
                <= keyIntervals.getLastKey(KeyIntervals.LOCAL_INVALIDATE))) {
          // this key was locally invalidated
          checkContainsKey(key, true, "key was locally invalidated");
          checkContainsValueForKey(key, true, "key was locally invalidated");
          Object value = aRegion.get(key);
          checkValue(key, value);
        } else if ((verifyRegionContentsIndex >= keyIntervals.getFirstKey(KeyIntervals.DESTROY))
            && (verifyRegionContentsIndex <= keyIntervals.getLastKey(KeyIntervals.DESTROY))) {
          // this key was destroyed
          checkContainsKey(key, false, "key was destroyed");
          checkContainsValueForKey(key, false, "key was destroyed");
        } else if ((verifyRegionContentsIndex
                >= keyIntervals.getFirstKey(KeyIntervals.LOCAL_DESTROY))
            && (verifyRegionContentsIndex <= keyIntervals.getLastKey(KeyIntervals.LOCAL_DESTROY))) {
          // this key was locally destroyed
          checkContainsKey(key, true, "key was locally destroyed");
          checkContainsValueForKey(key, true, "key was locally destroyed");
          Object value = aRegion.get(key);
          checkValue(key, value);
        } else if ((verifyRegionContentsIndex
                >= keyIntervals.getFirstKey(KeyIntervals.UPDATE_EXISTING_KEY))
            && (verifyRegionContentsIndex
                <= keyIntervals.getLastKey(KeyIntervals.UPDATE_EXISTING_KEY))) {
          // this key was updated
          checkContainsKey(key, true, "key was updated");
          checkContainsValueForKey(key, true, "key was updated");
          Object value = aRegion.get(key);
          checkUpdatedValue(key, value);
        } else if (verifyRegionContentsIndex > keyIntervals.getNumKeys()) {
          // key was newly added
          checkContainsKey(key, true, "key was new");
          checkContainsValueForKey(key, true, "key was new");
          Object value = aRegion.get(key);
          checkValue(key, value);
        }
      } catch (TestException e) {
        Log.getLogWriter().info(TestHelper.getStackTrace(e));
        verifyRegionContentsErrStr.append(e.getMessage() + "\n");
      }

      if (System.currentTimeMillis() - lastLogTime > LOG_INTERVAL_MILLIS) {
        Log.getLogWriter()
            .info("Verified key " + verifyRegionContentsIndex + " out of " + totalNumKeys);
        lastLogTime = System.currentTimeMillis();
      }

      if (System.currentTimeMillis() - startTime >= minTaskGranularityMS) {
        Log.getLogWriter()
            .info(
                "In HydraTask_verifyRegionContents, returning before completing verify "
                    + "because of task granularity (this task must be batched to complete); last key verified is "
                    + key);
        return; // task is batched; we are done with this batch
      }
    }
    verifyRegionContentsCompleted = true;
    if (verifyRegionContentsErrStr.length() > 0) {
      throw new TestException(verifyRegionContentsErrStr.toString());
    }
    String aStr =
        "In HydraTask_verifyRegionContents, verified " + verifyRegionContentsIndex + " keys/values";
    Log.getLogWriter().info(aStr);
    throw new StopSchedulingTaskOnClientOrder(aStr);
  }
コード例 #8
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  private void doRegionTest(final RegionShortcut rs, final String rName, boolean compressed) {
    boolean isPersistent =
        rs == RegionShortcut.LOCAL_PERSISTENT
            || rs == RegionShortcut.REPLICATE_PERSISTENT
            || rs == RegionShortcut.PARTITION_PERSISTENT;
    GemFireCacheImpl gfc = createCache(isPersistent);
    Region r = null;
    try {
      gfc.setCopyOnRead(true);
      final MemoryAllocator ma = gfc.getOffHeapStore();
      assertNotNull(ma);
      assertEquals(0, ma.getUsedMemory());
      Compressor compressor = null;
      if (compressed) {
        compressor = SnappyCompressor.getDefaultInstance();
      }
      r = gfc.createRegionFactory(rs).setOffHeap(true).setCompressor(compressor).create(rName);
      assertEquals(true, r.isEmpty());
      assertEquals(0, ma.getUsedMemory());
      Object data = new Integer(123456789);
      r.put("key1", data);
      // System.out.println("After put of Integer value off heap used memory=" +
      // ma.getUsedMemory());
      assertTrue(ma.getUsedMemory() == 0);
      assertEquals(data, r.get("key1"));
      r.invalidate("key1");
      assertEquals(0, ma.getUsedMemory());
      r.put("key1", data);
      assertTrue(ma.getUsedMemory() == 0);
      long usedBeforeUpdate = ma.getUsedMemory();
      r.put("key1", data);
      assertEquals(usedBeforeUpdate, ma.getUsedMemory());
      assertEquals(data, r.get("key1"));
      r.destroy("key1");
      assertEquals(0, ma.getUsedMemory());

      data = new Long(0x007FFFFFL);
      r.put("key1", data);
      if (!compressed) {
        assertTrue(ma.getUsedMemory() == 0);
      }
      assertEquals(data, r.get("key1"));
      data = new Long(0xFF8000000L);
      r.put("key1", data);
      if (!compressed) {
        assertTrue(ma.getUsedMemory() == 0);
      }
      assertEquals(data, r.get("key1"));

      // now lets set data to something that will be stored offheap
      data = new Long(Long.MAX_VALUE);
      r.put("key1", data);
      assertEquals(data, r.get("key1"));
      // System.out.println("After put of Integer value off heap used memory=" +
      // ma.getUsedMemory());
      assertTrue(ma.getUsedMemory() > 0);
      data = new Long(Long.MIN_VALUE);
      r.put("key1", data);
      assertEquals(data, r.get("key1"));
      // System.out.println("After put of Integer value off heap used memory=" +
      // ma.getUsedMemory());
      assertTrue(ma.getUsedMemory() > 0);
      r.invalidate("key1");
      assertEquals(0, ma.getUsedMemory());
      r.put("key1", data);
      assertTrue(ma.getUsedMemory() > 0);
      usedBeforeUpdate = ma.getUsedMemory();
      r.put("key1", data);
      assertEquals(usedBeforeUpdate, ma.getUsedMemory());
      assertEquals(data, r.get("key1"));
      r.destroy("key1");
      assertEquals(0, ma.getUsedMemory());

      // confirm that byte[] do use off heap
      {
        byte[] originalBytes = new byte[1024];
        Object oldV = r.put("byteArray", originalBytes);
        long startUsedMemory = ma.getUsedMemory();
        assertEquals(null, oldV);
        byte[] readBytes = (byte[]) r.get("byteArray");
        if (originalBytes == readBytes) {
          fail("Expected different byte[] identity");
        }
        if (!Arrays.equals(readBytes, originalBytes)) {
          fail("Expected byte array contents to be equal");
        }
        assertEquals(startUsedMemory, ma.getUsedMemory());
        oldV = r.put("byteArray", originalBytes);
        if (!compressed) {
          assertEquals(null, oldV); // we default to old value being null for offheap
        }
        assertEquals(startUsedMemory, ma.getUsedMemory());

        readBytes = (byte[]) r.putIfAbsent("byteArray", originalBytes);
        if (originalBytes == readBytes) {
          fail("Expected different byte[] identity");
        }
        if (!Arrays.equals(readBytes, originalBytes)) {
          fail("Expected byte array contents to be equal");
        }
        assertEquals(startUsedMemory, ma.getUsedMemory());
        if (!r.replace("byteArray", readBytes, originalBytes)) {
          fail("Expected replace to happen");
        }
        assertEquals(startUsedMemory, ma.getUsedMemory());
        byte[] otherBytes = new byte[1024];
        otherBytes[1023] = 1;
        if (r.replace("byteArray", otherBytes, originalBytes)) {
          fail("Expected replace to not happen");
        }
        if (r.replace("byteArray", "bogus string", originalBytes)) {
          fail("Expected replace to not happen");
        }
        if (r.remove("byteArray", "bogus string")) {
          fail("Expected remove to not happen");
        }
        assertEquals(startUsedMemory, ma.getUsedMemory());

        if (!r.remove("byteArray", originalBytes)) {
          fail("Expected remove to happen");
        }
        assertEquals(0, ma.getUsedMemory());
        oldV = r.putIfAbsent("byteArray", "string value");
        assertEquals(null, oldV);
        assertEquals("string value", r.get("byteArray"));
        if (r.replace("byteArray", "string valuE", originalBytes)) {
          fail("Expected replace to not happen");
        }
        if (!r.replace("byteArray", "string value", originalBytes)) {
          fail("Expected replace to happen");
        }
        oldV = r.destroy("byteArray"); // we default to old value being null for offheap
        if (!compressed) {
          assertEquals(null, oldV);
        }
        MyCacheListener listener = new MyCacheListener();
        r.getAttributesMutator().addCacheListener(listener);
        try {
          Object valueToReplace = "string value1";
          r.put("byteArray", valueToReplace);
          assertEquals(null, listener.ohOldValue);
          if (!compressed) {
            assertEquals("string value1", listener.ohNewValue.getDeserializedForReading());
            valueToReplace = listener.ohNewValue;
          }
          if (!r.replace("byteArray", valueToReplace, "string value2")) {
            fail("expected replace to happen");
          }
          if (!compressed) {
            assertEquals("string value2", listener.ohNewValue.getDeserializedForReading());
            assertEquals("string value1", listener.ohOldValue.getDeserializedForReading());
          }
          // make sure that a custom equals/hashCode are not used when comparing values.

        } finally {
          r.getAttributesMutator().removeCacheListener(listener);
        }
      }
      assertTrue(ma.getUsedMemory() > 0);
      {
        Object key = "MyValueWithPartialEquals";
        MyValueWithPartialEquals v1 = new MyValueWithPartialEquals("s1");
        MyValueWithPartialEquals v2 = new MyValueWithPartialEquals("s2");
        MyValueWithPartialEquals v3 = new MyValueWithPartialEquals("s1");
        r.put(key, v1);
        try {
          if (r.replace(key, v2, "should not happen")) {
            fail("v1 should not be equal to v2 on an offheap region");
          }
          if (!r.replace(key, v3, "should happen")) {
            fail("v1 should be equal to v3 on an offheap region");
          }
          r.put(key, v1);
          if (r.remove(key, v2)) {
            fail("v1 should not be equal to v2 on an offheap region");
          }
          if (!r.remove(key, v3)) {
            fail("v1 should be equal to v3 on an offheap region");
          }
        } finally {
          r.remove(key);
        }
      }
      {
        Object key = "MyPdxWithPartialEquals";
        MyPdxWithPartialEquals v1 = new MyPdxWithPartialEquals("s", "1");
        MyPdxWithPartialEquals v2 = new MyPdxWithPartialEquals("s", "2");
        MyPdxWithPartialEquals v3 = new MyPdxWithPartialEquals("t", "1");
        r.put(key, v1);
        try {
          if (r.replace(key, v3, "should not happen")) {
            fail("v1 should not be equal to v3 on an offheap region");
          }
          if (!r.replace(key, v2, "should happen")) {
            fail("v1 should be equal to v2 on an offheap region");
          }
          r.put(key, v1);
          if (r.remove(key, v3)) {
            fail("v1 should not be equal to v3 on an offheap region");
          }
          if (!r.remove(key, v2)) {
            fail("v1 should be equal to v2 on an offheap region");
          }
        } finally {
          r.remove(key);
        }
      }
      byte[] value = new byte[1024];
      /*while (value != null) */ {
        r.put("byteArray", value);
      }
      r.remove("byteArray");
      assertEquals(0, ma.getUsedMemory());

      r.put("key1", data);
      assertTrue(ma.getUsedMemory() > 0);
      r.invalidateRegion();
      assertEquals(0, ma.getUsedMemory());

      r.put("key1", data);
      assertTrue(ma.getUsedMemory() > 0);
      try {
        r.clear();
        assertEquals(0, ma.getUsedMemory());
      } catch (UnsupportedOperationException ok) {
      }

      r.put("key1", data);
      assertTrue(ma.getUsedMemory() > 0);
      if (r.getAttributes().getDataPolicy().withPersistence()) {
        r.put("key2", Integer.valueOf(1234567890));
        r.put("key3", new Long(0x007FFFFFL));
        r.put("key4", new Long(0xFF8000000L));
        assertEquals(4, r.size());
        r.close();
        assertEquals(0, ma.getUsedMemory());
        // simple test of recovery
        r = gfc.createRegionFactory(rs).setOffHeap(true).create(rName);
        assertEquals(4, r.size());
        assertEquals(data, r.get("key1"));
        assertEquals(Integer.valueOf(1234567890), r.get("key2"));
        assertEquals(new Long(0x007FFFFFL), r.get("key3"));
        assertEquals(new Long(0xFF8000000L), r.get("key4"));
        closeCache(gfc, true);
        assertEquals(0, ma.getUsedMemory());
        gfc = createCache();
        if (ma != gfc.getOffHeapStore()) {
          fail("identity of offHeapStore changed when cache was recreated");
        }
        r = gfc.createRegionFactory(rs).setOffHeap(true).create(rName);
        assertTrue(ma.getUsedMemory() > 0);
        assertEquals(4, r.size());
        assertEquals(data, r.get("key1"));
        assertEquals(Integer.valueOf(1234567890), r.get("key2"));
        assertEquals(new Long(0x007FFFFFL), r.get("key3"));
        assertEquals(new Long(0xFF8000000L), r.get("key4"));
      }

      r.destroyRegion();
      assertEquals(0, ma.getUsedMemory());

    } finally {
      if (r != null && !r.isDestroyed()) {
        r.destroyRegion();
      }
      closeCache(gfc, false);
    }
  }
コード例 #9
0
  /** check remote ops done in a normal vm are correctly distributed to PROXY regions */
  private void remoteOriginOps(DataPolicy dp, InterestPolicy ip) throws CacheException {
    initOtherId();
    AttributesFactory af = new AttributesFactory();
    af.setDataPolicy(dp);
    af.setSubscriptionAttributes(new SubscriptionAttributes(ip));
    af.setScope(Scope.DISTRIBUTED_ACK);
    CacheListener cl1 =
        new CacheListener() {
          public void afterUpdate(EntryEvent e) {
            clLastEvent = e;
            clInvokeCount++;
          }

          public void afterCreate(EntryEvent e) {
            clLastEvent = e;
            clInvokeCount++;
          }

          public void afterInvalidate(EntryEvent e) {
            clLastEvent = e;
            clInvokeCount++;
          }

          public void afterDestroy(EntryEvent e) {
            clLastEvent = e;
            clInvokeCount++;
          }

          public void afterRegionInvalidate(RegionEvent e) {
            clLastEvent = e;
            clInvokeCount++;
          }

          public void afterRegionDestroy(RegionEvent e) {
            clLastEvent = e;
            clInvokeCount++;
          }

          public void afterRegionClear(RegionEvent e) {
            clLastEvent = e;
            clInvokeCount++;
          }

          public void afterRegionCreate(RegionEvent e) {}

          public void afterRegionLive(RegionEvent e) {}

          public void close() {}
        };
    af.addCacheListener(cl1);
    Region r = createRootRegion("ProxyDUnitTest", af.create());
    this.clInvokeCount = 0;

    doCreateOtherVm();

    DMStats stats = getDMStats();
    long receivedMsgs = stats.getReceivedMessages();

    if (ip.isAll()) {
      getOtherVm()
          .invoke(
              new CacheSerializableRunnable("do put") {
                public void run2() throws CacheException {
                  Region r = getRootRegion("ProxyDUnitTest");
                  r.put("p", "v");
                }
              });
      assertEquals(1, this.clInvokeCount);
      assertEquals(Operation.CREATE, this.clLastEvent.getOperation());
      assertEquals(true, this.clLastEvent.isOriginRemote());
      assertEquals(this.otherId, this.clLastEvent.getDistributedMember());
      assertEquals(null, ((EntryEvent) this.clLastEvent).getOldValue());
      assertEquals(false, ((EntryEvent) this.clLastEvent).isOldValueAvailable()); // failure
      assertEquals("v", ((EntryEvent) this.clLastEvent).getNewValue());
      assertEquals("p", ((EntryEvent) this.clLastEvent).getKey());
      this.clInvokeCount = 0;

      getOtherVm()
          .invoke(
              new CacheSerializableRunnable("do create") {
                public void run2() throws CacheException {
                  Region r = getRootRegion("ProxyDUnitTest");
                  r.create("c", "v");
                }
              });
      assertEquals(1, this.clInvokeCount);
      assertEquals(Operation.CREATE, this.clLastEvent.getOperation());
      assertEquals(true, this.clLastEvent.isOriginRemote());
      assertEquals(this.otherId, this.clLastEvent.getDistributedMember());
      assertEquals(null, ((EntryEvent) this.clLastEvent).getOldValue());
      assertEquals(false, ((EntryEvent) this.clLastEvent).isOldValueAvailable());
      assertEquals("v", ((EntryEvent) this.clLastEvent).getNewValue());
      assertEquals("c", ((EntryEvent) this.clLastEvent).getKey());
      this.clInvokeCount = 0;

      getOtherVm()
          .invoke(
              new CacheSerializableRunnable("do update") {
                public void run2() throws CacheException {
                  Region r = getRootRegion("ProxyDUnitTest");
                  r.put("c", "v2");
                }
              });
      assertEquals(1, this.clInvokeCount);
      assertEquals(Operation.UPDATE, this.clLastEvent.getOperation());
      assertEquals(true, this.clLastEvent.isOriginRemote());
      assertEquals(this.otherId, this.clLastEvent.getDistributedMember());
      assertEquals(null, ((EntryEvent) this.clLastEvent).getOldValue());
      assertEquals(false, ((EntryEvent) this.clLastEvent).isOldValueAvailable());
      assertEquals("v2", ((EntryEvent) this.clLastEvent).getNewValue());
      assertEquals("c", ((EntryEvent) this.clLastEvent).getKey());
      this.clInvokeCount = 0;

      getOtherVm()
          .invoke(
              new CacheSerializableRunnable("do invalidate") {
                public void run2() throws CacheException {
                  Region r = getRootRegion("ProxyDUnitTest");
                  r.invalidate("c");
                }
              });
      assertEquals(1, this.clInvokeCount);
      assertEquals(Operation.INVALIDATE, this.clLastEvent.getOperation());
      assertEquals(true, this.clLastEvent.isOriginRemote());
      assertEquals(this.otherId, this.clLastEvent.getDistributedMember());
      assertEquals(null, ((EntryEvent) this.clLastEvent).getOldValue());
      assertEquals(false, ((EntryEvent) this.clLastEvent).isOldValueAvailable());
      assertEquals(null, ((EntryEvent) this.clLastEvent).getNewValue());
      assertEquals("c", ((EntryEvent) this.clLastEvent).getKey());
      this.clInvokeCount = 0;

      getOtherVm()
          .invoke(
              new CacheSerializableRunnable("do destroy") {
                public void run2() throws CacheException {
                  Region r = getRootRegion("ProxyDUnitTest");
                  r.destroy("c");
                }
              });
      assertEquals(1, this.clInvokeCount);
      assertEquals(Operation.DESTROY, this.clLastEvent.getOperation());
      assertEquals(true, this.clLastEvent.isOriginRemote());
      assertEquals(this.otherId, this.clLastEvent.getDistributedMember());
      assertEquals(null, ((EntryEvent) this.clLastEvent).getOldValue());
      assertEquals(false, ((EntryEvent) this.clLastEvent).isOldValueAvailable());
      assertEquals(null, ((EntryEvent) this.clLastEvent).getNewValue());
      assertEquals("c", ((EntryEvent) this.clLastEvent).getKey());
      this.clInvokeCount = 0;

      getOtherVm()
          .invoke(
              new CacheSerializableRunnable("do putAll") {
                public void run2() throws CacheException {
                  Region r = getRootRegion("ProxyDUnitTest");
                  Map m = new HashMap();
                  m.put("putAllKey1", "putAllValue1");
                  m.put("putAllKey2", "putAllValue2");
                  r.putAll(m);
                }
              });
      assertEquals(2, this.clInvokeCount);
      // @todo darrel; check putAll events
      this.clInvokeCount = 0;

      getOtherVm()
          .invoke(
              new CacheSerializableRunnable("do netsearch") {
                public void run2() throws CacheException {
                  Region r = getRootRegion("ProxyDUnitTest");
                  assertEquals(null, r.get("loadkey")); // total miss
                }
              });
      assertEquals(0, this.clInvokeCount);

    } else {
      getOtherVm()
          .invoke(
              new CacheSerializableRunnable("do entry ops") {
                public void run2() throws CacheException {
                  Region r = getRootRegion("ProxyDUnitTest");
                  r.put("p", "v");
                  r.create("c", "v");
                  r.put("c", "v"); // update
                  r.invalidate("c");
                  r.destroy("c");
                  {
                    Map m = new HashMap();
                    m.put("putAllKey1", "putAllValue1");
                    m.put("putAllKey2", "putAllValue2");
                    r.putAll(m);
                  }
                  assertEquals(null, r.get("loadkey")); // total miss
                }
              });

      assertEquals(0, this.clInvokeCount);
      assertEquals(0, r.size());
      // check the stats to make sure none of the above sent up messages
      assertEquals(receivedMsgs, stats.getReceivedMessages());
    }

    {
      AttributesMutator am = r.getAttributesMutator();
      CacheLoader cl =
          new CacheLoader() {
            public Object load(LoaderHelper helper) throws CacheLoaderException {
              if (helper.getKey().equals("loadkey")) {
                return "loadvalue";
              } else if (helper.getKey().equals("loadexception")) {
                throw new CacheLoaderException("expected");
              } else {
                return null;
              }
            }

            public void close() {}
          };
      am.setCacheLoader(cl);
    }

    receivedMsgs = stats.getReceivedMessages();
    getOtherVm()
        .invoke(
            new CacheSerializableRunnable("check net loader") {
              public void run2() throws CacheException {
                Region r = getRootRegion("ProxyDUnitTest");
                assertEquals("loadvalue", r.get("loadkey")); // net load
                assertEquals(null, r.get("foobar")); // total miss
                try {
                  r.get("loadexception");
                  fail("expected CacheLoaderException");
                } catch (CacheLoaderException expected) {
                }
              }
            });
    assertTrue(stats.getReceivedMessages() > receivedMsgs);
    if (ip.isAll()) {
      assertEquals(1, this.clInvokeCount);
      assertEquals(Operation.NET_LOAD_CREATE, this.clLastEvent.getOperation());
      assertEquals(true, this.clLastEvent.isOriginRemote());
      assertEquals(this.otherId, this.clLastEvent.getDistributedMember());
      assertEquals(null, ((EntryEvent) this.clLastEvent).getOldValue());
      assertEquals(false, ((EntryEvent) this.clLastEvent).isOldValueAvailable());
      this.clInvokeCount = 0;
    } else {
      assertEquals(0, this.clInvokeCount);
    }

    {
      AttributesMutator am = r.getAttributesMutator();
      am.setCacheLoader(null);
      CacheWriter cw =
          new CacheWriterAdapter() {
            public void beforeCreate(EntryEvent event) throws CacheWriterException {
              throw new CacheWriterException("expected");
            }
          };
      am.setCacheWriter(cw);
    }
    receivedMsgs = stats.getReceivedMessages();
    getOtherVm()
        .invoke(
            new CacheSerializableRunnable("check net write") {
              public void run2() throws CacheException {
                Region r = getRootRegion("ProxyDUnitTest");
                try {
                  r.put("putkey", "putvalue");
                  fail("expected CacheWriterException");
                } catch (CacheWriterException expected) {
                }
              }
            });
    assertTrue(stats.getReceivedMessages() > receivedMsgs);
    {
      AttributesMutator am = r.getAttributesMutator();
      am.setCacheWriter(null);
    }
    assertEquals(0, this.clInvokeCount);
    this.clLastEvent = null;
    getOtherVm()
        .invoke(
            new CacheSerializableRunnable("check region invalidate") {
              public void run2() throws CacheException {
                Region r = getRootRegion("ProxyDUnitTest");
                r.invalidateRegion();
              }
            });
    assertEquals(1, this.clInvokeCount);
    assertEquals(Operation.REGION_INVALIDATE, this.clLastEvent.getOperation());
    assertEquals(true, this.clLastEvent.isOriginRemote());
    assertEquals(this.otherId, this.clLastEvent.getDistributedMember());

    this.clLastEvent = null;
    getOtherVm()
        .invoke(
            new CacheSerializableRunnable("check region clear") {
              public void run2() throws CacheException {
                Region r = getRootRegion("ProxyDUnitTest");
                r.clear();
              }
            });
    assertEquals(2, this.clInvokeCount);
    assertEquals(Operation.REGION_CLEAR, this.clLastEvent.getOperation());
    assertEquals(true, this.clLastEvent.isOriginRemote());
    assertEquals(this.otherId, this.clLastEvent.getDistributedMember());

    this.clLastEvent = null;
    getOtherVm()
        .invoke(
            new CacheSerializableRunnable("check region destroy") {
              public void run2() throws CacheException {
                Region r = getRootRegion("ProxyDUnitTest");
                r.destroyRegion();
              }
            });
    assertEquals(3, this.clInvokeCount);
    assertEquals(Operation.REGION_DESTROY, this.clLastEvent.getOperation());
    assertEquals(true, this.clLastEvent.isOriginRemote());
    assertEquals(this.otherId, this.clLastEvent.getDistributedMember());
    assertTrue(r.isDestroyed());
  }