Java Code Examples for org.apache.geode.cache.Cache

The following are top voted examples for showing how to use org.apache.geode.cache.Cache. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: monarch   File: DistributedTestCase.java   Source Code and License 6 votes vote down vote up
protected static final void destroyRegions(Cache cache)
    throws InternalGemFireError, Error, VirtualMachineError {
  if (cache != null && !cache.isClosed()) {
    //try to destroy the root regions first so that
    //we clean up any persistent files.
    for (Iterator itr = cache.rootRegions().iterator(); itr.hasNext();) {
      Region root = (Region)itr.next();
      //for colocated regions you can't locally destroy a partitioned
      //region.
      if(root.isDestroyed() || root instanceof HARegion || root instanceof PartitionedRegion) {
        continue;
      }
      try {
        root.localDestroyRegion("teardown");
      }
      catch (VirtualMachineError e) {
        SystemFailure.initiateFailure(e);
        throw e;
      }
      catch (Throwable t) {
        getLogWriter().error(t);
      }
    }
  }
}
 
Example 2
Project: monarch   File: MonarchGetRegionFunction.java   Source Code and License 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void execute(FunctionContext context) {
    List<Object> args = (List<Object>) context.getArguments();

    String regionName = (String)args.get(0);

    try {
        Cache cache = CacheFactory.getAnyInstance();
        Region<Object, Object> region = cache.getRegion(regionName);
        if (region != null) {
            context.getResultSender().lastResult(true);
        }
        else {
            context.getResultSender().lastResult(false);
        }
    } catch ( RegionExistsException re) {
        context.getResultSender().lastResult(true);
    } catch (CacheClosedException e) {
        context.getResultSender().lastResult(false);
    }
}
 
Example 3
Project: monarch   File: PersistentRecoveryOrderDUnitTest.java   Source Code and License 6 votes vote down vote up
protected AsyncInvocation createPersistentRegionAsync(final VM vm,
    final boolean diskSynchronous) {
  SerializableRunnable createRegion = new SerializableRunnable("Create persistent region") {
    public void run() {
      Cache cache = getCache();
      DiskStoreFactory dsf = cache.createDiskStoreFactory();
      File dir = getDiskDirForVM(vm);
      dir.mkdirs();
      dsf.setDiskDirs(new File[] {dir});
      dsf.setMaxOplogSize(1);
      DiskStore ds = dsf.create(REGION_NAME);
      RegionFactory rf = new RegionFactory();
      rf.setDiskStoreName(ds.getName());
      rf.setDiskSynchronous(diskSynchronous);
      rf.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE);
      rf.setScope(Scope.DISTRIBUTED_ACK);
      rf.create(REGION_NAME);
    }
  };
  return vm.invokeAsync(createRegion);
}
 
Example 4
Project: monarch   File: ServerLauncherTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testStartCacheServerWhenDefaultServerDisabled() throws IOException {
  final Cache mockCache = mockContext.mock(Cache.class, "Cache");

  mockContext.checking(new Expectations() {
    {
      oneOf(mockCache).getCacheServers();
      will(returnValue(Collections.emptyList()));
    }
  });

  final ServerLauncher serverLauncher =
      new Builder().setMemberName("serverOne").setDisableDefaultServer(true).build();

  assertNotNull(serverLauncher);
  assertEquals("serverOne", serverLauncher.getMemberName());
  assertTrue(serverLauncher.isDisableDefaultServer());

  serverLauncher.startCacheServer(mockCache);
}
 
Example 5
Project: monarch   File: GetRegionsFunction.java   Source Code and License 6 votes vote down vote up
@Override
public void execute(FunctionContext functionContext) {
  try {
    Cache cache = CacheFactory.getAnyInstance();
    Set<Region<?, ?>> regions = cache.rootRegions(); // should never return a null

    if (regions == null || regions.isEmpty()) {
      functionContext.getResultSender().lastResult(null);
    } else {
      Set<RegionInformation> regionInformationSet = new HashSet<>();

      for (Region<?, ?> region : regions) {
        RegionInformation regInfo = new RegionInformation(region, true);
        regionInformationSet.add(regInfo);
      }
      functionContext.getResultSender().lastResult(regionInformationSet.toArray());
    }
  } catch (Exception e) {
    functionContext.getResultSender().sendException(e);
  }
}
 
Example 6
Project: monarch   File: QueryWithBucketParameterIntegrationTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  String regionName = "pr1";
  int totalBuckets = 40;
  int numValues = 80;
  CacheUtils.startCache();
  Cache cache = CacheUtils.getCache();
  PartitionAttributesFactory pAFactory =
      getPartitionAttributesFactoryWithPartitionResolver(totalBuckets);
  RegionFactory rf = cache.createRegionFactory(RegionShortcut.PARTITION);
  rf.setPartitionAttributes(pAFactory.create());
  PartitionedRegion pr1 = (PartitionedRegion) rf.create(regionName);
  populateRegion(pr1, numValues);
  QueryService qs = pr1.getCache().getQueryService();
  String query = "select distinct e1.value from /pr1 e1";
  queryExecutor = (DefaultQuery) CacheUtils.getQueryService().newQuery(query);
  Set<Integer> set = createAndPopulateSet(totalBuckets);
  lds = new LocalDataSet(pr1, set);
}
 
Example 7
Project: monarch   File: PutDataSerializables.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
  Properties props = new Properties();
  DistributedSystem system = DistributedSystem.connect(props);
  Cache cache = CacheFactory.create(system);
  AttributesFactory factory = new AttributesFactory();
  Region region = cache.createRegion("DataSerializable", factory.create());
  region.put("User", new User("Fred", 42));

  new CompanySerializer();
  Address address = new Address();
  Company company = new Company("My Company", address);

  region.put("Company", company);
  region.put("Employee", new Employee(43, "Bob", new Date(), company));

  Thread.sleep(60 * 1000);
}
 
Example 8
Project: monarch   File: PersistentRVVRecoveryDUnitTest.java   Source Code and License 6 votes vote down vote up
protected RegionVersionVector getDiskRVV(VM vm) throws IOException, ClassNotFoundException {
  SerializableCallable createData = new SerializableCallable("getRVV") {

    public Object call() throws Exception {
      Cache cache = getCache();
      LocalRegion region = (LocalRegion) cache.getRegion(REGION_NAME);
      RegionVersionVector rvv = region.getDiskRegion().getRegionVersionVector();
      rvv = rvv.getCloneForTransmission();
      HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT);

      // Using gemfire serialization because
      // RegionVersionVector is not java serializable
      DataSerializer.writeObject(rvv, hdos);
      return hdos.toByteArray();
    }
  };
  byte[] result = (byte[]) vm.invoke(createData);
  ByteArrayInputStream bais = new ByteArrayInputStream(result);
  return DataSerializer.readObject(new DataInputStream(bais));
}
 
Example 9
Project: monarch   File: ClientInterestNotifyDUnitTest.java   Source Code and License 6 votes vote down vote up
/**
 * Do initial puts
 */
public static void doFeed() {
  try {
    LogWriterUtils.getLogWriter().info("Putting entries...");
    Cache cacheClient = GemFireCacheImpl.getInstance();
    Region r1 = cacheClient.getRegion(Region.SEPARATOR + REGION_NAME1);
    Region r2 = cacheClient.getRegion(Region.SEPARATOR + REGION_NAME2);
    Region r3 = cacheClient.getRegion(Region.SEPARATOR + REGION_NAME3);
    r1.put("key-1", "00");
    r2.put("key-1", "00");
    r3.put("key-1", "00");
  } catch (Exception ex) {
    ex.printStackTrace();
    Assert.fail("failed while region doing ops", ex);
  }
}
 
Example 10
Project: monarch   File: DistTXPersistentDebugDUnitTest.java   Source Code and License 6 votes vote down vote up
protected static RegionAttributes getPersistentPRAttributes(final int redundancy,
    final int recoveryDelay, Cache cache, int numBuckets, boolean synchronous) {
  DiskStore ds = cache.findDiskStore("disk");
  if (ds == null) {
    ds = cache.createDiskStoreFactory().setDiskDirs(getDiskDirs()).create("disk");
  }
  AttributesFactory af = new AttributesFactory();
  PartitionAttributesFactory paf = new PartitionAttributesFactory();
  paf.setRedundantCopies(redundancy);
  paf.setRecoveryDelay(recoveryDelay);
  paf.setTotalNumBuckets(numBuckets);
  paf.setLocalMaxMemory(500);
  af.setPartitionAttributes(paf.create());
  af.setDataPolicy(DataPolicy.PERSISTENT_PARTITION);
  af.setDiskStoreName("disk");
  af.setDiskSynchronous(synchronous);
  RegionAttributes attr = af.create();
  return attr;
}
 
Example 11
Project: monarch   File: LikePredicateJUnitTest.java   Source Code and License 6 votes vote down vote up
@Override
public void hook(int spot) throws RuntimeException {
  if (spot == 12) {
    Runnable r = new Runnable() {
      @Override
      public void run() {
        Cache cache = CacheUtils.getCache();
        cache.getLogger().fine("Removing Index in LikeQueryIndexTestHook");
        QueryService qs = cache.getQueryService();
        qs.removeIndex(qs.getIndex(cache.getRegion("exampleRegion"), "status"));
      }
    };
    th = new Thread(r);
    th.start();
  }
}
 
Example 12
Project: monarch   File: CreateAlterDestroyRegionCommands.java   Source Code and License 6 votes vote down vote up
public boolean verifyDistributedRegionMbean(Cache cache, String regionName) {
  GemFireCacheImpl gemfireCache = (GemFireCacheImpl) cache;
  int federationInterval =
      gemfireCache.getDistributedSystem().getConfig().getJmxManagerUpdateRate();
  long timeEnd = System.currentTimeMillis() + federationInterval + 50;

  for (; System.currentTimeMillis() <= timeEnd;) {
    try {
      DistributedRegionMXBean bean =
          ManagementService.getManagementService(cache).getDistributedRegionMXBean(regionName);
      if (bean == null) {
        bean = ManagementService.getManagementService(cache)
            .getDistributedRegionMXBean(Region.SEPARATOR + regionName);
      }
      if (bean != null) {
        return true;
      } else {
        Thread.sleep(2);
      }
    } catch (Exception ex) {
      continue;
    }
  }
  return false;
}
 
Example 13
Project: monarch   File: ImportDataFunction.java   Source Code and License 6 votes vote down vote up
public void execute(FunctionContext context) {
  final String[] args = (String[]) context.getArguments();
  final String regionName = args[0];
  final String importFileName = args[1];

  try {
    final Cache cache = CacheFactory.getAnyInstance();
    final Region<?, ?> region = cache.getRegion(regionName);
    final String hostName = cache.getDistributedSystem().getDistributedMember().getHost();
    if (region != null) {
      RegionSnapshotService<?, ?> snapshotService = region.getSnapshotService();
      File importFile = new File(importFileName);
      snapshotService.load(new File(importFileName), SnapshotFormat.GEMFIRE);
      String successMessage = CliStrings.format(CliStrings.IMPORT_DATA__SUCCESS__MESSAGE,
          importFile.getCanonicalPath(), hostName, regionName);
      context.getResultSender().lastResult(successMessage);
    } else {
      throw new IllegalArgumentException(
          CliStrings.format(CliStrings.REGION_NOT_FOUND, regionName));
    }

  } catch (Exception e) {
    context.getResultSender().sendException(e);
  }
}
 
Example 14
Project: monarch   File: LocatorTestBase.java   Source Code and License 6 votes vote down vote up
protected int startBridgeServerWithEmbeddedLocator(final String[] groups, final String locators,
    final String[] regions, final ServerLoadProbe probe) throws IOException {
  Properties props = new Properties();
  props.setProperty(MCAST_PORT, String.valueOf(0));
  props.setProperty(START_LOCATOR, locators);
  props.setProperty(LOCATORS, locators);
  DistributedSystem ds = getSystem(props);
  Cache cache = CacheFactory.create(ds);
  AttributesFactory factory = new AttributesFactory();
  factory.setScope(Scope.DISTRIBUTED_ACK);
  factory.setEnableBridgeConflation(true);
  factory.setDataPolicy(DataPolicy.REPLICATE);
  RegionAttributes attrs = factory.create();
  for (int i = 0; i < regions.length; i++) {
    cache.createRegion(regions[i], attrs);
  }
  CacheServer server = cache.addCacheServer();
  server.setGroups(groups);
  server.setLoadProbe(probe);
  server.setPort(0);
  server.start();

  remoteObjects.put(CACHE_KEY, cache);

  return new Integer(server.getPort());
}
 
Example 15
Project: monarch   File: DiskStoreCommands.java   Source Code and License 6 votes vote down vote up
private boolean diskStoreExists(String diskStoreName) {
  Cache cache = getCache();
  ManagementService managementService = ManagementService.getExistingManagementService(cache);
  DistributedSystemMXBean dsMXBean = managementService.getDistributedSystemMXBean();
  Map<String, String[]> diskstore = dsMXBean.listMemberDiskstore();

  Set<Entry<String, String[]>> entrySet = diskstore.entrySet();

  for (Entry<String, String[]> entry : entrySet) {
    String[] value = entry.getValue();
    if (CliUtil.contains(value, diskStoreName)) {
      return true;
    }
  }

  return false;
}
 
Example 16
Project: monarch   File: ManagementTestBase.java   Source Code and License 6 votes vote down vote up
/**
 * Stops a VM as a Managing node
 *
 * @throws Exception
 */
public void stopManagingNode(VM vm1) throws Exception {
  vm1.invoke(new SerializableRunnable("Stop Being Managing Node") {
    public void run() {
      Cache existingCache = GemFireCacheImpl.getInstance();
      if (existingCache != null && !existingCache.isClosed()) {
        if (managementService.isManager()) {
          managementService.stopManager();
        }

      }

    }
  });

}
 
Example 17
Project: monarch   File: ServerLauncherTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testIsDefaultServerEnabledWhenNoCacheServersExistAndDefaultServerDisabled() {
  final Cache mockCache = mockContext.mock(Cache.class, "Cache");

  mockContext.checking(new Expectations() {
    {
      oneOf(mockCache).getCacheServers();
      will(returnValue(Collections.emptyList()));
    }
  });

  final ServerLauncher serverLauncher =
      new Builder().setMemberName("serverOne").setDisableDefaultServer(true).build();

  assertNotNull(serverLauncher);
  assertEquals("serverOne", serverLauncher.getMemberName());
  assertTrue(serverLauncher.isDisableDefaultServer());
  assertFalse(serverLauncher.isDefaultServerEnabled(mockCache));
}
 
Example 18
Project: monarch   File: CliUtil.java   Source Code and License 6 votes vote down vote up
public static Set<String> getAllRegionNames() {
  Cache cache = CacheFactory.getAnyInstance();
  Set<String> regionNames = new HashSet<String>();
  Set<Region<?, ?>> rootRegions = cache.rootRegions();

  Iterator<Region<?, ?>> rootRegionIters = rootRegions.iterator();

  while (rootRegionIters.hasNext()) {
    Region<?, ?> rootRegion = rootRegionIters.next();
    regionNames.add(rootRegion.getFullPath().substring(1));

    Set<Region<?, ?>> subRegions = rootRegion.subregions(true);
    Iterator<Region<?, ?>> subRegionIters = subRegions.iterator();

    while (subRegionIters.hasNext()) {
      Region<?, ?> subRegion = subRegionIters.next();
      regionNames.add(subRegion.getFullPath().substring(1));
    }
  }
  return regionNames;
}
 
Example 19
Project: monarch   File: PersistentPartitionedRegionTestBase.java   Source Code and License 6 votes vote down vote up
protected void invalidateData(VM vm, final int startKey, final int endKey) {
  SerializableRunnable createData = new SerializableRunnable() {

    public void run() {
      Cache cache = getCache();
      Region region = cache.getRegion(PR_REGION_NAME);

      for (int i = startKey; i < endKey; i++) {
        region.destroy(i);
        region.create(i, null);
        region.invalidate(i);
      }
    }
  };
  vm.invoke(createData);
}
 
Example 20
Project: monarch   File: ClusterConfigurationService.java   Source Code and License 6 votes vote down vote up
public ClusterConfigurationService(Cache cache) throws IOException {
  this.cache = (GemFireCacheImpl) cache;
  Properties properties = cache.getDistributedSystem().getProperties();
  // resolve the cluster config dir
  String clusterConfigRootDir = properties.getProperty(CLUSTER_CONFIGURATION_DIR);

  if (StringUtils.isBlank(clusterConfigRootDir)) {
    clusterConfigRootDir = System.getProperty("user.dir");
  } else {
    File diskDir = new File(clusterConfigRootDir);
    if (!diskDir.exists() && !diskDir.mkdirs()) {
      throw new IOException("Cannot create directory : " + clusterConfigRootDir);
    }
    clusterConfigRootDir = diskDir.getCanonicalPath();
  }

  // resolve the file paths
  String configDiskDirName =
      CLUSTER_CONFIG_DISK_DIR_PREFIX + cache.getDistributedSystem().getName();

  configDirPath = FilenameUtils.concat(clusterConfigRootDir, CLUSTER_CONFIG_ARTIFACTS_DIR_NAME);
  configDiskDirPath = FilenameUtils.concat(clusterConfigRootDir, configDiskDirName);
  sharedConfigLockingService = getSharedConfigLockService(cache.getDistributedSystem());
  status.set(SharedConfigurationStatus.NOT_STARTED);
}
 
Example 21
Project: monarch   File: JSONFormatterJUnitTest.java   Source Code and License 6 votes vote down vote up
private void ValidatePdxInstanceToJsonConversion() {

    Cache c = CacheFactory.getAnyInstance();
    Region region = c.getRegion("primitiveKVStore");

    TestObjectForJSONFormatter actualTestObject = new TestObjectForJSONFormatter();
    actualTestObject.defaultInitialization();

    // Testcase-1: PdxInstance to Json conversion
    // put Object and getvalue as Pdxinstance
    region.put("201", actualTestObject);
    Object receivedObject = region.get("201");

    // PdxInstance->Json conversion
    if (receivedObject instanceof PdxInstance) {
      PdxInstance pi = (PdxInstance) receivedObject;
      String json = JSONFormatter.toJSON(pi);

      verifyJsonWithJavaObject(json, actualTestObject);
    } else {
      fail("receivedObject is expected to be of type PdxInstance");
    }

  }
 
Example 22
Project: monarch   File: CacheXmlGenerator.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a new <code>CacheXmlGenerator</code> that generates XML for a given
 * <code>ClientCache</code>.
 */
private CacheXmlGenerator(ClientCache cache, boolean useSchema, String version,
    boolean includeKeysValues) {
  this.cache = (Cache) cache;
  this.useSchema = useSchema;
  this.version = CacheXmlVersion.valueForVersion(version);
  this.includeKeysValues = includeKeysValues;
  this.generateDefaults = true;

  if (cache instanceof ClientCacheCreation) {
    this.creation = (ClientCacheCreation) cache;
    this.creation.startingGenerate();

  } else {
    this.creation = new ClientCacheCreation();
    if (generateDefaults() || cache.getCopyOnRead()) {
      this.creation.setCopyOnRead(cache.getCopyOnRead());
    }
  }
}
 
Example 23
Project: monarch   File: ClientHealthStatsDUnitTest.java   Source Code and License 6 votes vote down vote up
private static void verifyStats(int serverPort) throws Exception {
  Cache cache = GemFireCacheImpl.getInstance();
  ManagementService service = ManagementService.getExistingManagementService(cache);
  CacheServerMXBean serverBean = service.getLocalCacheServerMXBean(serverPort);
  CacheClientNotifier ccn = CacheClientNotifier.getInstance();
  CacheClientProxy ccp = ccn.getClientProxies().iterator().next();
  cache.getLoggerI18n().info(LocalizedStrings.DEBUG, "getQueueSize() " + ccp.getQueueSize());
  cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
      "getQueueSizeStat() " + ccp.getQueueSizeStat());
  cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
      "getEventsEnqued() " + ccp.getHARegionQueue().getStatistics().getEventsEnqued());
  cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
      "getEventsDispatched() " + ccp.getHARegionQueue().getStatistics().getEventsDispatched());
  cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
      "getEventsRemoved() " + ccp.getHARegionQueue().getStatistics().getEventsRemoved());
  cache.getLoggerI18n().info(LocalizedStrings.DEBUG,
      "getNumVoidRemovals() " + ccp.getHARegionQueue().getStatistics().getNumVoidRemovals());
  assertEquals(ccp.getQueueSize(), ccp.getQueueSizeStat());
  ClientQueueDetail queueDetails = serverBean.showClientQueueDetails()[0];
  assertEquals(queueDetails.getQueueSize(), ccp.getQueueSizeStat());
}
 
Example 24
Project: monarch   File: PersistentReplicatedTestBase.java   Source Code and License 6 votes vote down vote up
protected AsyncInvocation createPersistentRegionAsync(final VM vm) {
  SerializableRunnable createRegion = new SerializableRunnable("Create persistent region") {
    public void run() {
      Cache cache = getCache();
      DiskStoreFactory dsf = cache.createDiskStoreFactory();
      File dir = getDiskDirForVM(vm);
      dir.mkdirs();
      dsf.setDiskDirs(new File[] {dir});
      dsf.setMaxOplogSize(1);
      DiskStore ds = dsf.create(REGION_NAME);
      RegionFactory rf = new RegionFactory();
      rf.setDiskStoreName(ds.getName());
      rf.setDiskSynchronous(true);
      rf.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE);
      rf.setScope(Scope.DISTRIBUTED_ACK);
      rf.create(REGION_NAME);
    }
  };
  return vm.invokeAsync(createRegion);
}
 
Example 25
Project: monarch   File: ListIndexCommandDUnitTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <T extends Comparable<T>, B extends AbstractBean<T>> B query(final Cache cache,
    final String queryString) {
  try {
    getLogWriter().info(String.format("Running Query (%1$s) in GemFire...", queryString));

    final SelectResults<B> results =
        (SelectResults<B>) cache.getQueryService().newQuery(queryString).execute();

    getLogWriter()
        .info(String.format("Running Query (%1$s) in GemFire returned (%2$d) result(s).",
            queryString, results.size()));

    return (results.iterator().hasNext() ? results.iterator().next() : null);
  } catch (Exception e) {
    throw new RuntimeException(
        String.format("An error occurred running Query (%1$s)!", queryString), e);
  }
}
 
Example 26
Project: monarch   File: ListDiskStoresFunction.java   Source Code and License 6 votes vote down vote up
public void execute(final FunctionContext context) {
  final Set<DiskStoreDetails> memberDiskStores = new HashSet<DiskStoreDetails>();

  try {
    final Cache cache = getCache();

    if (cache instanceof InternalCache) {
      final InternalCache gemfireCache = (InternalCache) cache;

      final DistributedMember member = gemfireCache.getMyId();

      for (final DiskStore memberDiskStore : gemfireCache.listDiskStoresIncludingRegionOwned()) {
        memberDiskStores.add(new DiskStoreDetails(memberDiskStore.getDiskStoreUUID(),
            memberDiskStore.getName(), member.getId(), member.getName()));
      }
    }

    context.getResultSender().lastResult(memberDiskStores);
  } catch (Exception e) {
    context.getResultSender().sendException(e);
  }
}
 
Example 27
Project: monarch   File: DistributedTransactionDUnitTest.java   Source Code and License 6 votes vote down vote up
protected RegionAttributes getPersistentPRAttributes(final int redundancy,
    final int recoveryDelay, Cache cache, int numBuckets, boolean synchronous) {
  DiskStore ds = cache.findDiskStore("disk");
  if (ds == null) {
    ds = cache.createDiskStoreFactory().setDiskDirs(getDiskDirs()).create("disk");
  }
  AttributesFactory af = new AttributesFactory();
  PartitionAttributesFactory paf = new PartitionAttributesFactory();
  paf.setRedundantCopies(redundancy);
  paf.setRecoveryDelay(recoveryDelay);
  paf.setTotalNumBuckets(numBuckets);
  paf.setLocalMaxMemory(500);
  af.setPartitionAttributes(paf.create());
  af.setDataPolicy(DataPolicy.PERSISTENT_PARTITION);
  af.setDiskStoreName("disk");
  af.setDiskSynchronous(synchronous);
  RegionAttributes attr = af.create();
  return attr;
}
 
Example 28
Project: monarch   File: GetStackTracesFunction.java   Source Code and License 6 votes vote down vote up
@Override
public void execute(FunctionContext context) {
  try {
    Cache cache = CacheFactory.getAnyInstance();
    String memberNameOrId = cache.getDistributedSystem().getDistributedMember().getName();

    if (memberNameOrId == null) {
      memberNameOrId = cache.getDistributedSystem().getDistributedMember().getId();
    }
    StackTracesPerMember stackTracePerMember =
        new StackTracesPerMember(memberNameOrId, OSProcess.zipStacks());
    context.getResultSender().lastResult(stackTracePerMember);
  } catch (Exception e) {
    context.getResultSender().sendException(e);
  }
}
 
Example 29
Project: monarch   File: PRQueryDUnitHelper.java   Source Code and License 5 votes vote down vote up
/**
 * This function creates a Accessor node region on the given PR given the scope parameter.
 * 
 * @param regionName
 * @return cacheSerializable object
 */

public CacheSerializableRunnable getCacheSerializableRunnableForPRAccessorCreate(
    final String regionName, final int redundancy, final Class constraint) {
  SerializableRunnable createPrRegion;
  createPrRegion = new CacheSerializableRunnable(regionName) {
    public void run2() throws CacheException {
      Cache cache = getCache();
      Region partitionedregion = null;
      int maxMem = 0;
      AttributesFactory attr = new AttributesFactory();
      attr.setValueConstraint(constraint);
      PartitionAttributesFactory paf = new PartitionAttributesFactory();
      PartitionAttributes prAttr =
          paf.setLocalMaxMemory(maxMem).setRedundantCopies(redundancy).create();
      attr.setPartitionAttributes(prAttr);
      partitionedregion = cache.createRegion(regionName, attr.create());
      assertNotNull(
          "PRQueryDUnitHelper#getCacheSerializableRunnableForPRAccessorCreate: Partitioned Region "
              + regionName + " not in cache",
          cache.getRegion(regionName));
      assertNotNull(
          "PRQueryDUnitHelper#getCacheSerializableRunnableForPRAccessorCreate: Partitioned Region ref null",
          partitionedregion);
      assertTrue(
          "PRQueryDUnitHelper#getCacheSerializableRunnableForPRAccessorCreate: Partitioned Region ref claims to be destroyed",
          !partitionedregion.isDestroyed());
    }
  };

  return (CacheSerializableRunnable) createPrRegion;
}
 
Example 30
Project: monarch   File: ListAndDescribeRegionDUnitTest.java   Source Code and License 5 votes vote down vote up
private void createPartitionedRegion1() {
  final Cache cache = getCache();
  // Create the data region
  RegionFactory<String, Integer> dataRegionFactory =
      cache.createRegionFactory(RegionShortcut.PARTITION);
  dataRegionFactory.create(PR1);
}
 
Example 31
Project: monarch   File: GFSnapshotDUnitTest.java   Source Code and License 5 votes vote down vote up
private void configureAndStartServer(final int locatorPort, final String serverHostName,
    final Properties properties) throws IOException {
  final String memberName = getUniqueName() + "-server";
  final File workingDirectory = temporaryFolder.newFolder(memberName);
  final File pdxDirectory = temporaryFolder.newFolder(memberName + "-pdx");
  final File diskStoreDirectory = temporaryFolder.newFolder(memberName + "-disk");


  ServerLauncher.Builder builder = new ServerLauncher.Builder();

  for (String propertyName : properties.stringPropertyNames()) {
    builder.set(propertyName, properties.getProperty(propertyName));
  }

  ServerLauncher serverLauncher =
      builder.set("locators", serverHostName + "[" + locatorPort + "]").setMemberName(memberName)
          .set("log-level", "config").setHostNameForClients(serverHostName)
          .setServerBindAddress(serverHostName).setServerPort(0)
          .setWorkingDirectory(workingDirectory.getCanonicalPath()).setPdxDiskStore("pdxDS")
          .setPdxPersistent(true).build();
  serverLauncher.start();

  Cache cache = CacheFactory.getAnyInstance();

  cache.createDiskStoreFactory().setDiskDirsAndSizes(new File[] {pdxDirectory}, new int[] {16000})
      .create("pdxDS");

  cache.createDiskStoreFactory()
      .setDiskDirsAndSizes(new File[] {diskStoreDirectory}, new int[] {16000})
      .create("diskStore");

  RegionFactory<Object, Object> regionFactory = cache.createRegionFactory();
  regionFactory.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE).setScope(Scope.DISTRIBUTED_ACK)
      .setDiskStoreName("diskStore").create("TestRegion");
}
 
Example 32
Project: monarch   File: GroupByDUnitImpl.java   Source Code and License 5 votes vote down vote up
@Override
@Test
public void testAggregateFuncMin() throws Exception {
  Host host = Host.getHost(0);
  final VM vm0 = host.getVM(0);
  final VM vm1 = host.getVM(1);
  final VM vm2 = host.getVM(2);
  final VM vm3 = host.getVM(3);
  Cache cache = this.getCache();
  GroupByTestInterface test = createTestInstance();
  test.testAggregateFuncMin();
  this.closeCache(vm0, vm1, vm2, vm3);
}
 
Example 33
Project: monarch   File: PDXAsyncEventQueueDUnitTest.java   Source Code and License 5 votes vote down vote up
private void putInRegion(VM vm, final Object key, final int value) {
  SerializableCallable createSystem = new SerializableCallable() {
    public Object call() throws Exception {
      Cache cache = getCache();
      Region region1 = cache.getRegion("region");
      region1.put(key, new SimpleClass(value, (byte) value));
      return null;
    }
  };
  vm.invoke(createSystem);
}
 
Example 34
Project: monarch   File: PRQueryDUnitHelper.java   Source Code and License 5 votes vote down vote up
/**
 * This function creates a appropriate region PR given the scope & the redundancy parameters *
 * 
 * @param regionName
 * @param redundancy
 * @return cacheSerializable object
 */
public CacheSerializableRunnable getCacheSerializableRunnableForPRCreate(final String regionName,
    final int redundancy, final Class constraint) {

  SerializableRunnable createPrRegion;
  createPrRegion = new CacheSerializableRunnable(regionName) {
    @Override
    public void run2() throws CacheException {

      Cache cache = getCache();
      Region partitionedregion = null;
      AttributesFactory attr = new AttributesFactory();
      attr.setValueConstraint(constraint);

      PartitionAttributesFactory paf = new PartitionAttributesFactory();
      PartitionAttributes prAttr = paf.setRedundantCopies(redundancy).create();

      attr.setPartitionAttributes(prAttr);

      partitionedregion = cache.createRegion(regionName, attr.create());
      assertNotNull(
          "PRQueryDUnitHelper#getCacheSerializableRunnableForPRCreateWithRedundancy: Partitioned Region "
              + regionName + " not in cache",
          cache.getRegion(regionName));
      assertNotNull(
          "PRQueryDUnitHelper#getCacheSerializableRunnableForPRCreateWithRedundancy: Partitioned Region ref null",
          partitionedregion);
      assertTrue(
          "PRQueryDUnitHelper#getCacheSerializableRunnableForPRCreateWithRedundancy: Partitioned Region ref claims to be destroyed",
          !partitionedregion.isDestroyed());
    }
  };

  return (CacheSerializableRunnable) createPrRegion;
}
 
Example 35
Project: monarch   File: GatewayReceiverCreation.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("deprecation")
public GatewayReceiverCreation(Cache cache, int startPort, int endPort, int timeBetPings,
    int buffSize, String bindAdd, List<GatewayTransportFilter> filters, String hostnameForSenders,
    boolean manualStart) {
  this.cache = cache;

  /*
   * If user has set hostNameForSenders then it should take precedence over bindAddress. If user
   * hasn't set either hostNameForSenders or bindAddress then getLocalHost().getHostName() should
   * be used.
   */
  if (hostnameForSenders == null || hostnameForSenders.isEmpty()) {
    if (bindAdd == null || bindAdd.isEmpty()) {
      try {
        logger
            .warn(LocalizedMessage.create(LocalizedStrings.GatewayReceiverImpl_USING_LOCAL_HOST));
        this.host = SocketCreator.getLocalHost().getHostName();
      } catch (UnknownHostException e) {
        throw new IllegalStateException(
            LocalizedStrings.GatewayReceiverImpl_COULD_NOT_GET_HOST_NAME.toLocalizedString(), e);
      }
    } else {
      this.host = bindAdd;
    }
  } else {
    this.host = hostnameForSenders;
  }


  this.startPort = startPort;
  this.endPort = endPort;
  this.maxTimeBetweenPings = timeBetPings;
  this.socketBufferSize = buffSize;
  this.bindAddress = bindAdd;
  this.transFilter = filters;
  this.manualStart = manualStart;
}
 
Example 36
Project: monarch   File: ClusterConfig.java   Source Code and License 5 votes vote down vote up
public void verifyServer(Member server) throws ClassNotFoundException {
  // verify files exist in filesystem
  Set<String> expectedJarNames = this.getJarNames().stream().map(ClusterConfig::getServerJarName)
      .collect(Collectors.toSet());
  Set<String> actualJarNames = toSetIgnoringHiddenFiles(
      server.getWorkingDir().list((dir, filename) -> filename.contains(".jar")));
  assertThat(actualJarNames).isEqualTo(expectedJarNames);

  // verify config exists in memory
  server.invoke(() -> {
    Cache cache = GemFireCacheImpl.getInstance();

    // TODO: set compare to fail if there are extra regions
    for (String region : this.getRegions()) {
      assertThat(cache.getRegion(region)).isNotNull();
    }

    if (!StringUtils.isBlank(this.getMaxLogFileSize())) {
      Properties props = cache.getDistributedSystem().getProperties();
      assertThat(props.getProperty(LOG_FILE_SIZE_LIMIT)).isEqualTo(this.getMaxLogFileSize());
    }

    for (String jar : this.getJarNames()) {
      JarClassLoader jarClassLoader = findJarClassLoader(jar);
      assertThat(jarClassLoader).isNotNull();
      assertThat(Class.forName(nameOfClassContainedInJar(jar), true, jarClassLoader)).isNotNull();
    }
  });
}
 
Example 37
Project: monarch   File: ClientServerMiscDUnitTest.java   Source Code and License 5 votes vote down vote up
public static void closeRegion1() {
  try {
    Cache cache = new ClientServerMiscDUnitTest().getCache();
    Region r1 = cache.getRegion(Region.SEPARATOR + REGION_NAME1);
    assertNotNull(r1);
    r1.close();
  } catch (Exception e) {
    e.printStackTrace();
    Assert.fail("Test failed due to Exception during closeRegion1", e);
  }
}
 
Example 38
Project: monarch   File: IndexMaintenanceAsynchJUnitTest.java   Source Code and License 5 votes vote down vote up
private static void init() {
  try {
    String queryString;
    Query query;
    Object result;
    Cache cache = CacheUtils.getCache();
    region = CacheUtils.createRegion("portfolios", Portfolio.class, false);
    for (int i = 0; i < 4; i++) {
      region.put("" + i, new Portfolio(i));
    }
    qs = cache.getQueryService();
    index = (IndexProtocol) qs.createIndex("statusIndex", IndexType.FUNCTIONAL, "status",
        "/portfolios");
    IndexStatistics stats = index.getStatistics();
    assertEquals(4, stats.getNumUpdates());

    // queryString= "SELECT DISTINCT * FROM /portfolios p, p.positions.values pos where
    // pos.secId='IBM'";
    queryString = "SELECT DISTINCT * FROM /portfolios";
    query = CacheUtils.getQueryService().newQuery(queryString);

    result = query.execute();

  } catch (Exception e) {
    e.printStackTrace();
  }
  isInitDone = true;
}
 
Example 39
Project: monarch   File: ForceInvalidateEvictionDUnitTest.java   Source Code and License 5 votes vote down vote up
private void checkValue(VM vm, final Serializable key, final Object expected) {
  final String name = getUniqueName();
  vm.invoke(new SerializableRunnable() {
    public void run() {
      Cache cache = getCache();
      final LocalRegion region = (LocalRegion) cache.getRegion(name);

      Wait.waitForCriterion(new WaitCriterion() {

        public boolean done() {
          Object value = null;
          try {
            value = region.getValueInVM(key);
            if (value instanceof CachedDeserializable) {
              value = ((CachedDeserializable) value).getDeserializedForReading();
            }
          } catch (EntryNotFoundException e) {
            // ok
          }
          return expected == null ? value == null : expected.equals(value);
        }

        public String description() {
          return "Value did not become " + expected + " after 30s: " + region.getValueInVM(key);
        }
      }, 30000, 100, true);

    }
  });
}
 
Example 40
Project: monarch   File: CacheXml70DUnitTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testConcurrentAsyncEventQueue() {
  getSystem();
  CacheCreation cache = new CacheCreation();

  String id = "WBCLChannel";
  AsyncEventQueueFactory factory = cache.createAsyncEventQueueFactory();
  factory.setBatchSize(100);
  factory.setBatchTimeInterval(500);
  factory.setBatchConflationEnabled(true);
  factory.setMaximumQueueMemory(200);
  factory.setDiskSynchronous(true);
  factory.setDispatcherThreads(5);
  factory.setOrderPolicy(OrderPolicy.THREAD);

  AsyncEventListener eventListener = new MyAsyncEventListener();
  AsyncEventQueue asyncEventQueue = factory.create(id, eventListener);

  RegionAttributesCreation attrs = new RegionAttributesCreation();
  attrs.addAsyncEventQueueId(asyncEventQueue.getId());
  cache.createRegion("UserRegion", attrs);

  testXml(cache);
  Cache c = getCache();
  assertNotNull(c);

  Set<AsyncEventQueue> asyncEventQueuesOnCache = c.getAsyncEventQueues();
  assertTrue("Size of asyncEventQueues should be greater than 0",
      asyncEventQueuesOnCache.size() > 0);

  for (AsyncEventQueue asyncEventQueueOnCache : asyncEventQueuesOnCache) {
    validateConcurrentAsyncEventQueue(asyncEventQueue, asyncEventQueueOnCache);
  }
}
 
Example 41
Project: monarch   File: GroupByDUnitImpl.java   Source Code and License 5 votes vote down vote up
@Override
@Test
public void testComplexValueAggregateFuncAvgDistinct() throws Exception {
  Host host = Host.getHost(0);
  final VM vm0 = host.getVM(0);
  final VM vm1 = host.getVM(1);
  final VM vm2 = host.getVM(2);
  final VM vm3 = host.getVM(3);
  Cache cache = this.getCache();
  GroupByTestInterface test = createTestInstance();
  test.testComplexValueAggregateFuncAvgDistinct();
  this.closeCache(vm0, vm1, vm2, vm3);
}
 
Example 42
Project: monarch   File: PRQueryDUnitHelper.java   Source Code and License 5 votes vote down vote up
public CacheSerializableRunnable getCacheSerializableRunnableForDefineIndex(
    final String prRegionName, final ArrayList<String> indexName,
    final ArrayList<String> indexedExpression, final ArrayList<String> fromClause) {

  SerializableRunnable prIndexCreator = new CacheSerializableRunnable("PartitionedIndexCreator") {
    @Override
    public void run2() {
      List<Index> indexes = null;
      try {
        Cache cache = getCache();
        QueryService qs = cache.getQueryService();
        Region region = cache.getRegion(prRegionName);
        for (int i = 0; i < indexName.size(); i++) {
          qs.defineIndex(indexName.get(i), indexedExpression.get(i),
              fromClause == null ? region.getFullPath() : fromClause.get(i));
        }
        indexes = qs.createDefinedIndexes();
      } catch (Exception ex) {
        if (ex instanceof MultiIndexCreationException) {
          StringBuffer sb = new StringBuffer();
          for (Exception e : ((MultiIndexCreationException) ex).getExceptionsMap().values()) {
            sb.append(e.getMessage()).append("\n");
          }
          fail("Multi index creation failed, " + sb);
        } else {
          Assert.fail("Creating Index in this vm failed : ", ex);
        }
      }
      assertNotNull("Indexes should have been created.", indexes);
    }
  };
  return (CacheSerializableRunnable) prIndexCreator;
}
 
Example 43
Project: monarch   File: PRQueryDUnitHelper.java   Source Code and License 5 votes vote down vote up
public CacheSerializableRunnable getCacheSerializableRunnableForReplicatedRegionCreation(
    final String regionName) {
  SerializableRunnable createPrRegion;
  createPrRegion = new CacheSerializableRunnable(regionName) {
    @Override
    public void run2() throws CacheException {
      Cache cache = getCache();
      Region localRegion = null;
      try {
        localRegion = cache.createRegionFactory(RegionShortcut.REPLICATE).create(regionName);
      } catch (IllegalStateException ex) {
        org.apache.geode.test.dunit.LogWriterUtils.getLogWriter().warning(
            "PRQueryDUnitHelper#getCacheSerializableRunnableForPRCreate: Creation caught IllegalStateException",
            ex);
      }
      assertNotNull(
          "PRQueryDUnitHelper#getCacheSerializableRunnableForPRCreate: Partitioned Region "
              + regionName + " not in cache",
          cache.getRegion(regionName));
      assertNotNull(
          "PRQueryDUnitHelper#getCacheSerializableRunnableForPRCreate: Partitioned Region ref null",
          localRegion);
      assertTrue(
          "PRQueryDUnitHelper#getCacheSerializableRunnableForPRCreate: Partitioned Region ref claims to be destroyed",
          !localRegion.isDestroyed());
    }
  };

  return (CacheSerializableRunnable) createPrRegion;
}
 
Example 44
Project: monarch   File: ConflationDUnitTest.java   Source Code and License 5 votes vote down vote up
private Cache createCache(Properties props) throws Exception {
  DistributedSystem ds = getSystem(props);
  Cache cache = CacheFactory.create(ds);
  if (cache == null) {
    throw new Exception("CacheFactory.create() returned null ");
  }
  return cache;
}
 
Example 45
Project: monarch   File: GroupByDUnitImpl.java   Source Code and License 5 votes vote down vote up
@Test
public void testLimitWithGroupBy() throws Exception {
  Host host = Host.getHost(0);
  final VM vm0 = host.getVM(0);
  final VM vm1 = host.getVM(1);
  final VM vm2 = host.getVM(2);
  final VM vm3 = host.getVM(3);
  Cache cache = this.getCache();
  GroupByTestInterface test = createTestInstance();
  test.testLimitWithGroupBy();
  this.closeCache(vm0, vm1, vm2, vm3);
}
 
Example 46
Project: monarch   File: PdxGroupByPartitionedQueryDUnitTest.java   Source Code and License 5 votes vote down vote up
private Region createAccessor(String regionName, Class valueConstraint) {

    Cache cache = getCache();
    PartitionAttributesFactory paf = new PartitionAttributesFactory();
    paf.setTotalNumBuckets(10);
    paf.setLocalMaxMemory(0);
    return cache.createRegionFactory(RegionShortcut.PARTITION_PROXY)
        .setValueConstraint(valueConstraint).setPartitionAttributes(paf.create())
        .create(regionName);
  }
 
Example 47
Project: monarch   File: OffHeapManagementDUnitTest.java   Source Code and License 5 votes vote down vote up
/**
 * Removes off-heap region and disconnects.
 */
protected void cleanup() {
  Cache existingCache = basicGetCache();

  if (null != existingCache && !existingCache.isClosed()) {
    Region region = getCache().getRegion(OFF_HEAP_REGION_NAME);

    if (null != region) {
      region.destroyRegion();
    }
  }

  disconnectFromDS();
}
 
Example 48
Project: monarch   File: TestDiskRegion.java   Source Code and License 5 votes vote down vote up
public static void main1(String[] args) throws Exception {
  DistributedSystem system = DistributedSystem.connect(new java.util.Properties());
  Cache cache = CacheFactory.create(system);
  AttributesFactory factory = new AttributesFactory();
  factory.setEvictionAttributes(EvictionAttributes.createLRUMemoryAttributes(2,
      (ObjectSizer) null, EvictionAction.OVERFLOW_TO_DISK));
  factory.setCacheListener(new CacheListenerAdapter() {
    public void afterUpdate(EntryEvent event) {
      System.out.println("UPDATE: " + event.getKey() + " -> (" + event.getOldValue() + " -> "
          + event.getNewValue() + ")");
    }
  });

  LocalRegion region = (LocalRegion) cache.createRegion("TestDiskRegion", factory.create());
  DiskRegion dr = region.getDiskRegion();
  DiskRegionStats diskStats = dr.getStats();
  LRUStatistics lruStats = getLRUStats(region);

  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Hit enter to perform action");
  for (int i = 0; true; i++) {
    br.readLine();
    // Thread.sleep(500);
    Object key = new Integer(i);
    Object value = new byte[200000];
    region.put(key, value);
    System.out.println(key + " -> " + value + " evictions = " + lruStats.getEvictions()
        + ", writes = " + diskStats.getWrites());
  }
}
 
Example 49
Project: monarch   File: AbstractCommandsSupport.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("deprecated")
protected DistributedMember getMember(final Cache cache, final String memberName) {
  for (final DistributedMember member : getMembers(cache)) {
    if (memberName.equalsIgnoreCase(member.getName())
        || memberName.equalsIgnoreCase(member.getId())) {
      return member;
    }
  }

  throw new MemberNotFoundException(
      CliStrings.format(CliStrings.MEMBER_NOT_FOUND_ERROR_MESSAGE, memberName));
}
 
Example 50
Project: monarch   File: QueryIndexUsingXMLDUnitTest.java   Source Code and License 5 votes vote down vote up
public CacheSerializableRunnable loadRegion(final String name) {
  CacheSerializableRunnable sr = new CacheSerializableRunnable("load region on " + name) {
    public void run2() {
      Cache cache = getCache();
      LogWriter logger = cache.getLogger();
      Region region = cache.getRegion(name);
      for (int i = 0; i < 100; i++) {
        region.put("" + i, new Portfolio(i));
      }
    }
  };
  return sr;
}
 
Example 51
Project: monarch   File: CreateAlterDestroyRegionCommands.java   Source Code and License 5 votes vote down vote up
private void validateRegionPathAndParent(Cache cache, String regionPath) {
  if (regionPath == null || "".equals(regionPath)) {
    throw new IllegalArgumentException(CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH);
  }
  // If a region path indicates a sub-region, check whether the parent region exists
  RegionPath regionPathData = new RegionPath(regionPath);
  String parentRegionPath = regionPathData.getParent();
  if (parentRegionPath != null && !Region.SEPARATOR.equals(parentRegionPath)) {
    if (!regionExists(cache, parentRegionPath)) {
      throw new IllegalArgumentException(
          CliStrings.format(CliStrings.CREATE_REGION__MSG__PARENT_REGION_FOR_0_DOESNOT_EXIST,
              new Object[] {regionPath}));
    }
  }
}
 
Example 52
Project: monarch   File: AlterMockRegionExtensionFunction.java   Source Code and License 5 votes vote down vote up
@Override
public void execute(FunctionContext context) {
  final Cache cache = CacheFactory.getAnyInstance();

  final Region<?, ?> region = cache.getRegion((String) ((Object[]) context.getArguments())[0]);
  if (!(region instanceof Extensible)) {
    throw new FunctionException("Not extensible region.");
  }

  final String value = (String) ((Object[]) context.getArguments())[1];

  @SuppressWarnings("unchecked")
  final Extensible<Region<?, ?>> extensible = (Extensible<Region<?, ?>>) region;
  for (Extension<Region<?, ?>> extension : extensible.getExtensionPoint().getExtensions()) {
    if (extension instanceof MockRegionExtension) {
      ((MockRegionExtension) extension).setValue(value);
    }
  }

  XmlEntity xmlEntity = new XmlEntity(CacheXml.REGION, "name", region.getName());

  final ResultSender<Object> resultSender = context.getResultSender();
  final String memberNameOrId =
      CliUtil.getMemberNameOrId(cache.getDistributedSystem().getDistributedMember());

  resultSender.lastResult(new CliFunctionResult(memberNameOrId, xmlEntity,
      CliStrings.format("Mock region extension \"{0}\" altered on \"{1}\"",
          new Object[] {region.getFullPath(), memberNameOrId})));

}
 
Example 53
Project: monarch   File: CountStarJUnitTest.java   Source Code and License 5 votes vote down vote up
private void createPartitionedRegion() {
  Cache cache = CacheUtils.getCache();
  PartitionAttributesFactory prAttFactory = new PartitionAttributesFactory();
  AttributesFactory attributesFactory = new AttributesFactory();
  attributesFactory.setPartitionAttributes(prAttFactory.create());
  RegionAttributes regionAttributes = attributesFactory.create();
  Region region = cache.createRegion(regionName, regionAttributes);

  for (int i = 1; i <= numElem; i++) {
    Portfolio obj = new Portfolio(i);
    region.put(i, obj);
    CacheUtils.log(obj);
  }
}
 
Example 54
Project: monarch   File: PdxRenameJUnitTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testGetPdxTypes() throws Exception {
  String DS_NAME = "PdxRenameJUnitTestDiskStore";
  Properties props = new Properties();
  props.setProperty(MCAST_PORT, "0");
  props.setProperty(LOCATORS, "");
  File f = new File(DS_NAME);
  f.mkdir();
  try {
    final Cache cache =
        (new CacheFactory(props)).setPdxPersistent(true).setPdxDiskStore(DS_NAME).create();
    try {
      DiskStoreFactory dsf = cache.createDiskStoreFactory();
      dsf.setDiskDirs(new File[] {f});
      dsf.create(DS_NAME);
      RegionFactory<String, PdxValue> rf1 =
          cache.createRegionFactory(RegionShortcut.LOCAL_PERSISTENT);
      rf1.setDiskStoreName(DS_NAME);
      Region<String, PdxValue> region1 = rf1.create("region1");
      region1.put("key1", new PdxValue(1));
      cache.close();

      Collection<PdxType> types = DiskStoreImpl.getPdxTypes(DS_NAME, new File[] {f});
      assertEquals(1, types.size());
      assertEquals(PdxValue.class.getName(), types.iterator().next().getClassName());
    } finally {
      if (!cache.isClosed()) {
        cache.close();
      }
    }
  } finally {
    FileUtil.delete(f);
  }
}
 
Example 55
Project: monarch   File: OrderByPartitionedDUnitTest.java   Source Code and License 5 votes vote down vote up
private void createPR(VM vm, final String regionName, final Class valueConstraint) {
  vm.invoke(new SerializableRunnable("create data store") {
    public void run() {
      Cache cache = getCache();
      PartitionAttributesFactory paf = new PartitionAttributesFactory();
      paf.setTotalNumBuckets(10);
      cache.createRegionFactory(RegionShortcut.PARTITION).setValueConstraint(valueConstraint)
          .setPartitionAttributes(paf.create()).create(regionName);
    }
  });
}
 
Example 56
Project: monarch   File: AuthorizeRequest.java   Source Code and License 5 votes vote down vote up
public AuthorizeRequest(String authzFactoryName, ClientProxyMembershipID id, Principal principal,
    Cache cache) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException,
    InvocationTargetException, NotAuthorizedException {
  this(authzFactoryName, id.getDistributedMember(), principal, cache);
  this.id = id;
  if (this.logger.infoEnabled()) {
    this.logger.info(
        LocalizedStrings.AuthorizeRequest_AUTHORIZEREQUEST_CLIENT_0_IS_SETTING_AUTHORIZATION_CALLBACK_TO_1,
        new Object[] {id, authzFactoryName});
  }
}
 
Example 57
Project: monarch   File: CacheXmlGeode10DUnitTest.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Test
public void testEnableOffHeapMemory() {
  try {
    System.setProperty(DistributionConfig.GEMFIRE_PREFIX + OFF_HEAP_MEMORY_SIZE, "1m");

    final String regionName = "testEnableOffHeapMemory";

    final CacheCreation cache = new CacheCreation();
    final RegionAttributesCreation attrs = new RegionAttributesCreation(cache);
    attrs.setOffHeap(true);
    assertEquals(true, attrs.getOffHeap());

    final Region regionBefore = cache.createRegion(regionName, attrs);
    assertNotNull(regionBefore);
    assertEquals(true, regionBefore.getAttributes().getOffHeap());

    testXml(cache);

    final Cache c = getCache();
    assertNotNull(c);

    final Region regionAfter = c.getRegion(regionName);
    assertNotNull(regionAfter);
    assertEquals(true, regionAfter.getAttributes().getOffHeap());
    assertEquals(true, ((LocalRegion) regionAfter).getOffHeap());
    regionAfter.localDestroyRegion();
  } finally {
    System.clearProperty(DistributionConfig.GEMFIRE_PREFIX + OFF_HEAP_MEMORY_SIZE);
  }
}
 
Example 58
Project: monarch   File: QueryJUnitTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testThreadSafetyOfCompiledSelectScopeId() throws Exception {
  try {
    Cache cache = CacheUtils.getCache();
    RegionFactory<Integer, Portfolio> rf = cache.createRegionFactory(RegionShortcut.PARTITION);
    Region r = rf.create("keyzset");
    for (int i = 0; i < 100; i++) {
      r.put(i, new Portfolio(i));
    }
    ScopeThreadingTestHook scopeIDTestHook = new ScopeThreadingTestHook(3);
    DefaultQuery.testHook = scopeIDTestHook;
    QueryService qs = cache.getQueryService();
    Query q = qs.newQuery(
        "SELECT DISTINCT * FROM /keyzset.keySet key WHERE key.id > 0 AND key.id <= 0 ORDER BY key asc LIMIT $3");
    Thread q1 = new Thread(new QueryRunnable(q, new Object[] {10, 20, 10}));
    Thread q2 = new Thread(new QueryRunnable(q, new Object[] {5, 10, 5}));
    Thread q3 = new Thread(new QueryRunnable(q, new Object[] {2, 10, 8}));
    q1.start();
    q2.start();
    q3.start();
    q1.join();
    q2.join();
    q3.join();
    assertEquals("Exceptions were thrown due to DefaultQuery not being thread-safe", true,
        scopeIDTestHook.isOk());
  } finally {
    DefaultQuery.testHook = null;
  }
}
 
Example 59
Project: monarch   File: TransactionsWithOverflowTest.java   Source Code and License 5 votes vote down vote up
private String createDiskStoreAndGetName() {
  Cache cache = getCache();
  File[] diskDirs = new File[1];
  diskDirs[0] = new File("diskRegionDirs/" + getClass().getCanonicalName());
  diskDirs[0].mkdirs();
  DiskStoreFactory diskStoreFactory = cache.createDiskStoreFactory();
  diskStoreFactory.setDiskDirs(diskDirs);
  String diskStoreName = getClass().getName();
  diskStoreFactory.create(diskStoreName);
  return diskStoreName;
}
 
Example 60
Project: monarch   File: HashIndexQueryIntegrationTest.java   Source Code and License 5 votes vote down vote up
private void createPartitionedRegion(String regionName, boolean synchMaintenance)
    throws ParseException {
  Cache cache = CacheUtils.getCache();
  PartitionAttributesFactory prAttFactory = new PartitionAttributesFactory();
  AttributesFactory attributesFactory = new AttributesFactory();
  attributesFactory.setPartitionAttributes(prAttFactory.create());
  attributesFactory.setIndexMaintenanceSynchronous(synchMaintenance);
  RegionAttributes regionAttributes = attributesFactory.create();
  region = cache.createRegion(regionName, regionAttributes);
}