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

The following are top voted examples for showing how to use org.apache.geode.cache.CacheFactory. 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: CacheServerMaxConnectionsJUnitTest.java   Source Code and License 6 votes vote down vote up
/**
 * Creates and starts the server instance
 */
private int createServer() throws IOException {
  CacheServer server = null;
  Properties p = new Properties();
  // make it a loner
  p.put(MCAST_PORT, "0");
  p.put(LOCATORS, "");
  this.system = DistributedSystem.connect(p);
  this.cache = CacheFactory.create(system);
  server = this.cache.addCacheServer();
  int port = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
  server.setMaxConnections(MAX_CNXS);
  server.setMaxThreads(getMaxThreads());
  server.setPort(port);
  server.start();
  return server.getPort();
}
 
Example 2
Project: monarch   File: MTableDUnitHelper.java   Source Code and License 6 votes vote down vote up
public void cleanUpAllVMs() throws Exception {
  invokeInEveryVM(new SerializableCallable() {
    @Override
    public Object call() throws Exception {
      Cache c = null;
      try {
        c = CacheFactory.getAnyInstance();
        if (c != null) {
          c.close();
        }
      } catch (CacheClosedException e) {
      }
      return null;
    }
  });
}
 
Example 3
Project: monarch   File: SnapshotDUnitTest.java   Source Code and License 6 votes vote down vote up
public void loadCache() throws Exception {
  SerializableCallable setup = new SerializableCallable() {
    @Override
    public Object call() throws Exception {
      CacheFactory cf =
          new CacheFactory().setPdxSerializer(new MyPdxSerializer()).setPdxPersistent(true);

      Cache cache = getCache(cf);
      DiskStore ds = cache.createDiskStoreFactory().setMaxOplogSize(1).setDiskDirs(getDiskDirs())
          .create("snapshotTest");

      RegionGenerator rgen = new RegionGenerator();

      for (final RegionType rt : RegionType.values()) {
        for (final SerializationType st : SerializationType.values()) {
          rgen.createRegion(cache, ds.getName(), rt, "test-" + rt.name() + "-" + st.name());
        }
      }
      return null;
    }
  };

  forEachVm(setup, true);
}
 
Example 4
Project: monarch   File: GetRegions.java   Source Code and License 6 votes vote down vote up
public void execute(FunctionContext context) {

    ArrayList<String> vals = new ArrayList<String>();

    Cache c = null;
    try {
      c = CacheFactory.getAnyInstance();
    } catch (CacheClosedException ex) {
      vals.add("NoCacheResult");
      context.getResultSender().lastResult(vals);
    }

    final Set<Region<?, ?>> regionSet = c.rootRegions();
    for (Region<?, ?> r : regionSet) {
      vals.add(r.getName());
    }

    context.getResultSender().lastResult(vals);
  }
 
Example 5
Project: monarch   File: QueryUsingFunctionContextDUnitTest.java   Source Code and License 6 votes vote down vote up
/**
 * This function puts portfolio objects into the created Region (PR or Local) *
 *
 * @param regionName
 * @param portfolio
 * @param to
 * @param from
 * @return cacheSerializable object
 */
public CacheSerializableRunnable getCacheSerializableRunnableForPRPuts(final String regionName,
    final Object[] portfolio, final int from, final int to) {
  SerializableRunnable puts = new CacheSerializableRunnable("Region Puts") {
    @Override
    public void run2() throws CacheException {
      Cache cache = CacheFactory.getAnyInstance();
      Region region = cache.getRegion(regionName);
      for (int j = from; j < to; j++)
        region.put(new Integer(j), portfolio[j]);
      LogWriterUtils.getLogWriter()
          .info("getCacheSerializableRunnableForPRPuts: Inserted Portfolio data on Region "
              + regionName);
    }
  };
  return (CacheSerializableRunnable) puts;
}
 
Example 6
Project: monarch   File: CreateMockCacheExtensionFunction.java   Source Code and License 6 votes vote down vote up
@Override
public void execute(FunctionContext context) {
  final Cache cache = CacheFactory.getAnyInstance();

  if (!(cache instanceof Extensible)) {
    throw new FunctionException("Not extensible cache.");
  }

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

  @SuppressWarnings("unchecked")
  final Extensible<Cache> extensible = (Extensible<Cache>) cache;
  final MockCacheExtension extension = new MockCacheExtension(value);
  extension.beforeCreate(extensible, cache);
  extension.onCreate(extensible, extensible);

  final XmlEntity xmlEntity =
      XmlEntity.builder().withType(ELEMENT_CACHE).withNamespace(PREFIX, NAMESPACE).build();

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

  resultSender.lastResult(new CliFunctionResult(memberNameOrId, xmlEntity, CliStrings
      .format("Mock cache extension created on \"{0}\"", new Object[] {memberNameOrId})));
}
 
Example 7
Project: monarch   File: Bug51400DUnitTest.java   Source Code and License 6 votes vote down vote up
public static Integer createServerCache(Integer mcastPort, Integer maxMessageCount)
    throws Exception {
  Properties props = new Properties();
  props.setProperty(LOCATORS, "localhost[" + DistributedTestUtils.getDUnitLocatorPort() + "]");

  Bug51400DUnitTest test = new Bug51400DUnitTest();
  DistributedSystem ds = test.getSystem(props);
  ds.disconnect();
  cache = (GemFireCacheImpl) CacheFactory.create(test.getSystem());
  // cache = (GemFireCacheImpl) new CacheFactory(props).create();

  RegionFactory<String, String> rf = cache.createRegionFactory(RegionShortcut.REPLICATE);

  rf.setConcurrencyChecksEnabled(false);

  Region<String, String> region = rf.create(REGION_NAME);

  CacheServer server = cache.addCacheServer();
  server.setMaximumMessageCount(maxMessageCount);
  server.setPort(AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET));
  server.start();
  return server.getPort();
}
 
Example 8
Project: monarch   File: ChangeLogLevelFunction.java   Source Code and License 6 votes vote down vote up
@Override
public void execute(FunctionContext context) {
  Cache cache = CacheFactory.getAnyInstance();
  Map<String, String> result = new HashMap<String, String>();
  try {
    LogWriterLogger logwriterLogger = (LogWriterLogger) cache.getLogger();
    Object[] args = (Object[]) context.getArguments();
    final String logLevel = (String) args[0];
    Level log4jLevel = LogWriterLogger.logWriterNametoLog4jLevel(logLevel);
    logwriterLogger.setLevel(log4jLevel);
    System.setProperty(DistributionConfig.GEMFIRE_PREFIX + LOG_LEVEL, logLevel);
    // LOG:CONFIG:
    logger.info(LogMarker.CONFIG, "GFSH Changed log level to {}", log4jLevel);
    result.put(cache.getDistributedSystem().getDistributedMember().getId(),
        "New log level is " + log4jLevel);
    context.getResultSender().lastResult(result);
  } catch (Exception ex) {
    // LOG:CONFIG:
    logger.info(LogMarker.CONFIG, "GFSH Changing log level exception {}", ex.getMessage(), ex);
    result.put(cache.getDistributedSystem().getDistributedMember().getId(),
        "ChangeLogLevelFunction exception " + ex.getMessage());
    context.getResultSender().lastResult(result);
  }
}
 
Example 9
Project: monarch   File: ExportDataFunction.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 fileName = args[1];

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

  } catch (Exception e) {
    context.getResultSender().sendException(e);
  }
}
 
Example 10
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 11
Project: monarch   File: Bug47388DUnitTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("deprecation")
public static Integer createCacheServerWithPRDatastore() throws Exception {
  Properties props = new Properties();
  Bug47388DUnitTest test = new Bug47388DUnitTest();
  DistributedSystem ds = test.getSystem(props);
  ds.disconnect();
  cache = (GemFireCacheImpl) CacheFactory.create(test.getSystem());

  RegionFactory<String, String> rf = cache.createRegionFactory(RegionShortcut.PARTITION);

  rf.setEntryTimeToLive(new ExpirationAttributes(3, ExpirationAction.DESTROY))
      .setPartitionAttributes(new PartitionAttributesFactory<String, String>()
          .setRedundantCopies(1).setTotalNumBuckets(4).create())
      .setConcurrencyChecksEnabled(false);

  rf.create(REGION_NAME);

  CacheServer server = cache.addCacheServer();
  server.setPort(AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET));
  server.start();
  return server.getPort();
}
 
Example 12
Project: monarch   File: RegionCloseDUnitTest.java   Source Code and License 6 votes vote down vote up
public static void VerifyClientProxyOnServerBeforeClose() {
  Cache c = CacheFactory.getAnyInstance();
  assertEquals("More than one CacheServer", 1, c.getCacheServers().size());


  final CacheServerImpl bs = (CacheServerImpl) c.getCacheServers().iterator().next();
  WaitCriterion ev = new WaitCriterion() {
    public boolean done() {
      return bs.getAcceptor().getCacheClientNotifier().getClientProxies().size() == 1;
    }

    public String description() {
      return null;
    }
  };
  Wait.waitForCriterion(ev, 15 * 1000, 200, true);
  assertEquals(1, bs.getAcceptor().getCacheClientNotifier().getClientProxies().size());

  Iterator iter = bs.getAcceptor().getCacheClientNotifier().getClientProxies().iterator();
  if (iter.hasNext()) {
    CacheClientProxy proxy = (CacheClientProxy) iter.next();
    clientMembershipId = proxy.getProxyID().toString();
    assertNotNull(proxy.getHARegion());
  }
}
 
Example 13
Project: monarch   File: CliUtilDUnitTest.java   Source Code and License 6 votes vote down vote up
public void verifyExecuteFunction() {
  DunitFunction function = new DunitFunction("myfunction");
  Set<DistributedMember> set;
  try {
    @SuppressWarnings("rawtypes")
    Region region1 = CacheFactory.getAnyInstance().getRegion(COMMON_REGION);
    region1.clear();
    set = CliUtil.findMembersOrThrow(GROUP1, null);
    assertEquals(2, set.size());
    ResultCollector collector = CliUtil.executeFunction(function, "executeOnGroup", set);
    collector.getResult();
    assertEquals(2, region1.size());
    assertTrue(region1.containsKey(MEMBER_1_GROUP1));
    assertTrue(region1.containsKey(MEMBER_2_GROUP1));
    assertEquals("executeOnGroup", region1.get(MEMBER_1_GROUP1));
    assertEquals("executeOnGroup", region1.get(MEMBER_2_GROUP1));
  } catch (CommandResultException e) {
    Assert.fail("Error during querying members", e);
  }
}
 
Example 14
Project: monarch   File: ClearMultiVmDUnitTest.java   Source Code and License 6 votes vote down vote up
public static void createCache() {
  try {
    ds = (new ClearMultiVmDUnitTest()).getSystem(props);
    cache = CacheFactory.create(ds);
    AttributesFactory factory = new AttributesFactory();
    factory.setScope(Scope.DISTRIBUTED_ACK);
    factory.setConcurrencyChecksEnabled(true);
    RegionAttributes attr = factory.create();
    region = cache.createRegion("map", attr);

    AttributesFactory factory1 = new AttributesFactory();
    factory1.setScope(Scope.DISTRIBUTED_ACK);
    factory.setConcurrencyChecksEnabled(true);
    factory1.setDataPolicy(DataPolicy.REPLICATE);
    paperWork = cache.createRegion("paperWork", factory1.create());

  } catch (Exception ex) {
    ex.printStackTrace();
  }
}
 
Example 15
Project: monarch   File: UpdateTableFunction.java   Source Code and License 6 votes vote down vote up
private void updateInMemory(final String tableName, final Filter filter,
    Map<Integer, Object> colValues, final TableDescriptor td) {
  /**
   * For all primary buckets for the region For all the blocks in a bucket If the block falls in
   * range lock the block Process all records in block and re-arrange.
   */
  if (td == null) {
    throw new FTableNotExistsException("Table not found: " + tableName);
  }
  int totalBuckets = td.getTotalNumOfSplits();
  Region region = CacheFactory.getAnyInstance().getRegion(tableName);
  for (int i = 0; i < totalBuckets; i++) {
    BucketRegion br = ((PartitionedRegion) region).getDataStore().getLocalBucketById(i);
    if (br != null && br.getBucketAdvisor().isHosting() && br.getBucketAdvisor().isPrimary()) {
      updateBucket(region, br, filter, colValues, td);
    }
  }
}
 
Example 16
Project: monarch   File: UpdateTableFunction.java   Source Code and License 6 votes vote down vote up
private void updateInTiers(final String tableName, final Filter filter,
    Map<Integer, Object> colValues, final TableDescriptor td) throws IOException {
  if (td == null) {
    throw new FTableNotExistsException("Table not found: " + tableName);
  }
  int totalBuckets = td.getTotalNumOfSplits();
  Region region = CacheFactory.getAnyInstance().getRegion(tableName);
  for (Map.Entry<String, TierStoreConfiguration> tierEntry : ((FTableDescriptor) td)
      .getTierStores().entrySet()) {
    String storeName = tierEntry.getKey();
    TierStore store = StoreHandler.getInstance().getTierStore(storeName);
    boolean isShared = store instanceof SharedTierStore;
    for (int i = 0; i < totalBuckets; i++) {
      BucketRegion br = ((PartitionedRegion) region).getDataStore().getLocalBucketById(i);
      if (br != null && br.getBucketAdvisor().isHosting()) {
        if (!isShared || br.getBucketAdvisor().isPrimary()) {
          updateTierBucket(store, tableName, i, filter, colValues, td,
              tierEntry.getValue().getTierProperties());
        }
      }
    }
  }
}
 
Example 17
Project: monarch   File: TestXACacheLoader.java   Source Code and License 6 votes vote down vote up
private Object loadFromDatabase(Object ob) {
  Object obj = null;
  try {
    Context ctx = CacheFactory.getAnyInstance().getJNDIContext();
    DataSource ds = (DataSource) ctx.lookup("java:/XAPooledDataSource");
    Connection conn = ds.getConnection();
    Statement stm = conn.createStatement();
    ResultSet rs = stm.executeQuery("select name from " + tableName + " where id = ("
        + (new Integer(ob.toString())).intValue() + ")");
    rs.next();
    obj = rs.getString(1);
    stm.close();
    conn.close();
    return obj;
  } catch (Exception e) {
    e.printStackTrace();
  }
  // conn.close();
  return obj;
}
 
Example 18
Project: monarch   File: ForceEvictFTableFunction.java   Source Code and License 6 votes vote down vote up
private void flushFromMemory(final String tableName) {
  /**
   * For all primary buckets for the region For all the blocks in a bucket If the block falls in
   * range lock the block Process all records in block and re-arrange.
   */
  TableDescriptor td = MCacheFactory.getAnyInstance().getTableDescriptor(tableName);
  if (td == null) {
    throw new FTableNotExistsException("Table not found: " + tableName);
  }
  int totalBuckets = td.getTotalNumOfSplits();
  Region region = CacheFactory.getAnyInstance().getRegion(tableName);
  for (int i = 0; i < totalBuckets; i++) {
    BucketRegion br = ((PartitionedRegion) region).getDataStore().getLocalBucketById(i);
    if (br != null && br.getBucketAdvisor().isHosting() && br.getBucketAdvisor().isPrimary()) {
      flushFromBucket(br);
    }
  }
}
 
Example 19
Project: monarch   File: InternalClientMembership.java   Source Code and License 6 votes vote down vote up
/**
 * Caller must synchronize on cache.allClientServersLock
 * 
 * @return all the clients
 */
public static Map getConnectedClients() {

  // Get all clients
  Map allClients = new HashMap();
  for (Iterator bsii = CacheFactory.getAnyInstance().getCacheServers().iterator(); bsii
      .hasNext();) {
    CacheServerImpl bsi = (CacheServerImpl) bsii.next();
    AcceptorImpl ai = bsi.getAcceptor();
    if (ai != null && ai.getCacheClientNotifier() != null) {
      allClients.putAll(ai.getCacheClientNotifier().getAllClients());
    }
  }

  // Fill in the missing info, if HealthMonitor started
  if (ClientHealthMonitor.getInstance() != null)
    ClientHealthMonitor.getInstance().fillInClientInfo(allClients);

  return allClients;
}
 
Example 20
Project: monarch   File: DistributedRegionFunctionExecutionDUnitTest.java   Source Code and License 6 votes vote down vote up
public static void bug41118() {
  InternalDistributedSystem ds = new DistributedRegionFunctionExecutionDUnitTest().getSystem();
  assertNotNull(ds);
  ds.disconnect();
  Properties props = new Properties();
  props.setProperty(MCAST_PORT, "0");
  ds = (InternalDistributedSystem) DistributedSystem.connect(props);

  DM dm = ds.getDistributionManager();
  assertEquals("Distributed System is not loner", true, dm instanceof LonerDistributionManager);

  Cache cache = CacheFactory.create(ds);
  AttributesFactory factory = new AttributesFactory();
  factory.setScope(Scope.LOCAL);
  factory.setDataPolicy(DataPolicy.REPLICATE);
  assertNotNull(cache);
  region = cache.createRegion(REGION_NAME, factory.create());
  try {
    executeInlineFunction();
    ds.disconnect();
  } catch (Exception e) {
    LogWriterUtils.getLogWriter().info("Exception Occured : " + e.getMessage());
    e.printStackTrace();
    Assert.fail("Test failed", e);
  }
}
 
Example 21
Project: monarch   File: PutAllCallBkRemoteVMDUnitTest.java   Source Code and License 6 votes vote down vote up
public static synchronized void createCacheForVM0() {
  try {
    ds = (new PutAllCallBkRemoteVMDUnitTest()).getSystem(props);
    cache = CacheFactory.create(ds);
    AttributesFactory factory = new AttributesFactory();
    factory.setDataPolicy(DataPolicy.REPLICATE);
    factory.setScope(Scope.DISTRIBUTED_ACK);
    RegionAttributes attr1 = factory.create();
    paperRegion = cache.createRegion("paper", attr1);
    RegionAttributes attr = factory.create();
    region = cache.createRegion("map", attr);

  } catch (CacheException ex) {
    throw new RuntimeException("vm0 cache creation exception", ex);
  }
}
 
Example 22
Project: monarch   File: MTableDUnitHelper.java   Source Code and License 5 votes vote down vote up
public Object startServerOn(VM vm, final String locators) {
  try {
    return vm.invoke(new SerializableCallable() {

      @Override
      public Object call() throws Exception {
        Properties props = new Properties();
        props.setProperty(DistributionConfig.LOG_LEVEL_NAME, String.valueOf("config"));
        props.setProperty(DistributionConfig.LOG_FILE_NAME, "system.log");
        props.setProperty(DistributionConfig.MCAST_PORT_NAME, String.valueOf(0));
        props.setProperty(DistributionConfig.LOCATORS_NAME, locators);
        props.setProperty(DistributionConfig.STATISTIC_ARCHIVE_FILE_NAME, "Stats");
        Cache c = null;
        try {
          c = CacheFactory.getAnyInstance();
          c.close();
        } catch (CacheClosedException cce) {
        }
        c = CacheFactory.create(getSystem(props));
        CacheServer s = c.addCacheServer();
        int port = AvailablePortHelper.getRandomAvailableTCPPort();
        s.setPort(port);
        s.start();

        //registerFunction();
        return port;
      }
    });
  } catch (RMIException e) {
    e.printStackTrace();
  }
  return null;
}
 
Example 23
Project: monarch   File: QueryUsingFunctionContextDUnitTest.java   Source Code and License 5 votes vote down vote up
private void createProxyRegs() {
  ClientCache cache = (ClientCache) CacheFactory.getAnyInstance();
  cache.createClientRegionFactory(ClientRegionShortcut.PROXY).create(repRegionName);

  cache.createClientRegionFactory(ClientRegionShortcut.PROXY).create(localRegionName);

  cache.createClientRegionFactory(ClientRegionShortcut.PROXY).create(PartitionedRegionName1);
  cache.createClientRegionFactory(ClientRegionShortcut.PROXY).create(PartitionedRegionName2);
  cache.createClientRegionFactory(ClientRegionShortcut.PROXY).create(PartitionedRegionName3);
  cache.createClientRegionFactory(ClientRegionShortcut.PROXY).create(PartitionedRegionName4);
  cache.createClientRegionFactory(ClientRegionShortcut.PROXY).create(PartitionedRegionName5);
}
 
Example 24
Project: monarch   File: SnapshotPerformanceDUnitTest.java   Source Code and License 5 votes vote down vote up
private void createCache() throws Exception {
  SerializableCallable setup = new SerializableCallable() {
    @Override
    public Object call() throws Exception {
      CacheFactory cf = new CacheFactory().setPdxSerializer(new MyPdxSerializer());

      getCache(cf);
      return null;
    }
  };

  SnapshotDUnitTest.forEachVm(setup, true);
}
 
Example 25
Project: monarch   File: PdxInstanceSortedHelper.java   Source Code and License 5 votes vote down vote up
public PdxInstanceSortedHelper(String className, JSONToPdxMapper parent) {
  GemFireCacheImpl gci = (GemFireCacheImpl) CacheFactory.getAnyInstance();
  if (logger.isTraceEnabled()) {
    logger.trace("ClassName {}", className);
  }
  m_PdxName = className;
  m_parent = parent;
}
 
Example 26
Project: monarch   File: TransactionsWithOverflowTest.java   Source Code and License 5 votes vote down vote up
private Cache getCache() {
  if (cache == null) {
    Properties props = new Properties();
    props.setProperty(LOCATORS, "");
    props.setProperty(MCAST_PORT, "0");
    cache = new CacheFactory(props).create();
  }
  return cache;
}
 
Example 27
Project: monarch   File: BeanUtilFuncs.java   Source Code and License 5 votes vote down vote up
public static DistributedMember getDistributedMemberByNameOrId(String memberNameOrId) {
  DistributedMember memberFound = null;

  if (memberNameOrId != null) {
    Cache cache = CacheFactory.getAnyInstance();
    Set<DistributedMember> memberSet = CliUtil.getAllMembers(cache);
    for (DistributedMember member : memberSet) {
      if (memberNameOrId.equals(member.getId()) || memberNameOrId.equals(member.getName())) {
        memberFound = member;
        break;
      }
    }
  }
  return memberFound;
}
 
Example 28
Project: monarch   File: CliUtilDUnitTest.java   Source Code and License 5 votes vote down vote up
@Override
public void execute(FunctionContext context) {
  Object object = context.getArguments();
  Cache cache = CacheFactory.getAnyInstance();
  @SuppressWarnings("rawtypes")
  Region region = cache.getRegion(COMMON_REGION);
  String id = cache.getDistributedSystem().getDistributedMember().getName();
  region.put(id, object);
  LogWriterUtils.getLogWriter().info("Completed executeFunction on member : " + id);
  context.getResultSender().lastResult(true);
}
 
Example 29
Project: monarch   File: AmpoolRegionMapFactoryTest.java   Source Code and License 5 votes vote down vote up
@After
public void tearDown() throws Exception {
  try {
    Cache cache = CacheFactory.getAnyInstance();
    cache.close();
  } catch (Exception ex) {
    // cache is already closed
  }

}
 
Example 30
Project: monarch   File: RestAgent.java   Source Code and License 5 votes vote down vote up
/**
 * This method will create a REPLICATED region named _ParameterizedQueries__. In developer REST
 * APIs, this region will be used to store the queryId and queryString as a key and value
 * respectively.
 */
public static void createParameterizedQueryRegion() {
  try {
    if (logger.isDebugEnabled()) {
      logger.debug("Starting creation of  __ParameterizedQueries__ region");
    }
    GemFireCacheImpl cache = (GemFireCacheImpl) CacheFactory.getAnyInstance();
    if (cache != null) {
      // cache.getCacheConfig().setPdxReadSerialized(true);
      final InternalRegionArguments regionArguments = new InternalRegionArguments();
      regionArguments.setIsUsedForMetaRegion(true);
      final AttributesFactory<String, String> attributesFactory =
          new AttributesFactory<String, String>();

      attributesFactory.setConcurrencyChecksEnabled(false);
      attributesFactory.setDataPolicy(DataPolicy.REPLICATE);
      attributesFactory.setKeyConstraint(String.class);
      attributesFactory.setScope(Scope.DISTRIBUTED_ACK);
      attributesFactory.setStatisticsEnabled(false);
      attributesFactory.setValueConstraint(String.class);

      final RegionAttributes<String, String> regionAttributes = attributesFactory.create();

      cache.createVMRegion("__ParameterizedQueries__", regionAttributes, regionArguments);
      if (logger.isDebugEnabled()) {
        logger.debug("Successfully created __ParameterizedQueries__ region");
      }
    } else {
      logger.error("Cannot create ParameterizedQueries Region as no cache found!");
    }
  } catch (Exception e) {
    if (logger.isDebugEnabled()) {
      logger.debug("Error creating __ParameterizedQueries__ Region with cause {}", e.getMessage(),
          e);
    }
  }
}
 
Example 31
Project: monarch   File: PutAllWithIndexPerfDUnitTest.java   Source Code and License 5 votes vote down vote up
/**
 * Starts a bridge server on the given port, using the given deserializeValues and
 * notifyBySubscription to serve up the given region.
 */
protected void startBridgeServer(int port, boolean notifyBySubscription) throws IOException {

  Cache cache = CacheFactory.getAnyInstance();
  CacheServer bridge = cache.addCacheServer();
  bridge.setPort(port);
  bridge.start();
  bridgeServerPort = bridge.getPort();
}
 
Example 32
Project: monarch   File: PdxSerializableJUnitTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testNoDiskStore() throws Exception {
  this.c.close();
  this.c = (GemFireCacheImpl) new CacheFactory().set(MCAST_PORT, "0").setPdxPersistent(true)
      .setPdxDiskStore("doesNotExist").create();
  HeapDataOutputStream out = new HeapDataOutputStream(Version.CURRENT);
  PdxSerializable object = new SimpleClass(1, (byte) 5, null);
  try {
    DataSerializer.writeObject(object, out);
    throw new Exception("expected PdxInitializationException");
  } catch (PdxInitializationException expected) {
  }
}
 
Example 33
Project: monarch   File: AsyncEventQueueTestBase.java   Source Code and License 5 votes vote down vote up
public static void createCacheWithoutLocator(Integer mCastPort) {
  AsyncEventQueueTestBase test = new AsyncEventQueueTestBase();
  Properties props = test.getDistributedSystemProperties();
  props.setProperty(MCAST_PORT, "" + mCastPort);
  InternalDistributedSystem ds = test.getSystem(props);
  cache = CacheFactory.create(ds);
}
 
Example 34
Project: monarch   File: DurableClientReconnectDUnitTest.java   Source Code and License 5 votes vote down vote up
private void createCache(Properties props) {
  try {
    DistributedSystem ds = getSystem(props);
    assertNotNull(ds);
    ds.disconnect();
    ds = getSystem(props);
    cache = CacheFactory.create(ds);
    assertNotNull(cache);
  } catch (Exception e) {
    Assert.fail("test failed due to ", e);
  }
}
 
Example 35
Project: monarch   File: DeclarativeIndexCreationJUnitTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  Properties props = new Properties();
  props.setProperty(CACHE_XML_FILE, TestUtil.getResourcePath(getClass(), "cachequeryindex.xml"));
  props.setProperty(MCAST_PORT, "0");
  ds = DistributedSystem.connect(props);
  cache = CacheFactory.create(ds);
}
 
Example 36
Project: monarch   File: AsyncEventQueueTestBase.java   Source Code and License 5 votes vote down vote up
protected static void createCache(Integer locPort) {
  AsyncEventQueueTestBase test = new AsyncEventQueueTestBase();
  Properties props = test.getDistributedSystemProperties();
  props.setProperty(MCAST_PORT, "0");
  props.setProperty(LOCATORS, "localhost[" + locPort + "]");
  InternalDistributedSystem ds = test.getSystem(props);
  cache = CacheFactory.create(ds);
}
 
Example 37
Project: monarch   File: InterestListRecoveryDUnitTest.java   Source Code and License 5 votes vote down vote up
public static Set getCacheClientProxies() {
  Cache c = CacheFactory.getAnyInstance();
  assertEquals("More than one CacheServer", 1, c.getCacheServers().size());
  CacheServerImpl bs = (CacheServerImpl) c.getCacheServers().iterator().next();
  assertNotNull(bs);
  assertNotNull(bs.getAcceptor());
  assertNotNull(bs.getAcceptor().getCacheClientNotifier());
  return new HashSet(bs.getAcceptor().getCacheClientNotifier().getClientProxies());
}
 
Example 38
Project: monarch   File: ExceptionHandlingJUnitTest.java   Source Code and License 5 votes vote down vote up
@BeforeClass
public static void caseSetUp() throws Exception {
  Properties properties = new Properties();
  properties.setProperty(MCAST_PORT, "0");
  properties.setProperty(LOCATORS, "");
  distributedSystem = DistributedSystem.connect(properties);
  Cache cache = CacheFactory.create(distributedSystem);
  AttributesFactory factory = new AttributesFactory();
  factory.setScope(Scope.GLOBAL);
  RegionAttributes regionAttributes = factory.create();
  testRegion = cache.createRegion("TestRegion", regionAttributes);
}
 
Example 39
Project: monarch   File: PdxClientServerDUnitTest.java   Source Code and License 5 votes vote down vote up
private int createServerRegionWithPersistence(VM vm, final boolean persistentPdxRegistry) {
  SerializableCallable createRegion = new SerializableCallable() {
    public Object call() throws Exception {
      CacheFactory cf = new CacheFactory();
      if (persistentPdxRegistry) {
        cf.setPdxPersistent(true).setPdxDiskStore("store");
      }
      //
      Cache cache = getCache(cf);
      cache.createDiskStoreFactory().setDiskDirs(getDiskDirs()).create("store");

      AttributesFactory af = new AttributesFactory();
      af.setScope(Scope.DISTRIBUTED_ACK);
      af.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE);
      af.setDiskStoreName("store");
      createRootRegion("testSimplePdx", af.create());

      CacheServer server = getCache().addCacheServer();
      int port = AvailablePortHelper.getRandomAvailableTCPPort();
      server.setPort(port);
      server.start();
      return port;
    }
  };

  return (Integer) vm.invoke(createRegion);
}
 
Example 40
Project: monarch   File: MemoryMonitorOffHeapJUnitTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  Properties p = new Properties();
  p.setProperty(MCAST_PORT, "0");
  p.setProperty(OFF_HEAP_MEMORY_SIZE, "1m");
  this.ds = DistributedSystem.connect(p);
  this.cache = (GemFireCacheImpl) CacheFactory.create(this.ds);
  logger.info(addExpectedAbove);
  logger.info(addExpectedBelow);
}
 
Example 41
Project: monarch   File: HARegionQueueStartStopJUnitTest.java   Source Code and License 5 votes vote down vote up
/**
 * Creates the cache instance for the test
 * 
 * @return the cache instance
 * @throws CacheException - thrown if any exception occurs in cache creation
 */
private Cache createCache() throws CacheException {
  final Properties props = new Properties();
  props.setProperty(LOCATORS, "");
  props.setProperty(MCAST_PORT, "0");
  return CacheFactory.create(DistributedSystem.connect(props));
}
 
Example 42
Project: monarch   File: TestDiskRegion.java   Source Code and License 5 votes vote down vote up
/**
 * Byte arrays
 */
public static void main4(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));
  LocalRegion region = (LocalRegion) cache.createRegion("TestDiskRegion", factory.create());
  // DiskRegion dr = region.getDiskRegion();
  // DiskRegionStats diskStats = dr.getStats();
  // LRUStatistics lruStats = getLRUStats(region);

  // int total;
  // for (total = 0; lruStats.getEvictions() > 100; total++) {
  // region.put(new Integer(total), String.valueOf(total).getBytes());
  // }

  // for (int i = 0; i < total; i++) {
  // byte[] bytes = (byte[]) region.get(new Integer(i));
  // Assert.assertTrue((new String(bytes)).equals(String.valueOf(i)));
  // }

  for (int i = 0; i < 100000; i++) {
    System.out.println(i);
    region.put(String.valueOf(i), String.valueOf(i).getBytes());
  }
}
 
Example 43
Project: monarch   File: PutAllGlobalLockJUnitTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  Properties properties = new Properties();
  properties.setProperty(MCAST_PORT, "0");
  properties.setProperty(LOCATORS, "");
  DistributedSystem distributedSystem = DistributedSystem.connect(properties);
  Cache cache = CacheFactory.create(distributedSystem);
  AttributesFactory factory = new AttributesFactory();
  factory.setScope(Scope.GLOBAL);
  factory.setCacheListener(new Listener());
  RegionAttributes regionAttributes = factory.create();
  testRegion = cache.createRegion("TestRegion", regionAttributes);
}
 
Example 44
Project: monarch   File: Bug36457DUnitTest.java   Source Code and License 5 votes vote down vote up
private void createCache(Properties props) throws Exception {
  DistributedSystem ds = getSystem(props);
  ds.disconnect();
  ds = getSystem(props);
  assertNotNull(ds);
  cache = CacheFactory.create(ds);
  assertNotNull(cache);
}
 
Example 45
Project: monarch   File: OnGroupsFunctionExecutionDUnitTest.java   Source Code and License 5 votes vote down vote up
private void initVM(VM vm, final String groups, final String regionName,
    final boolean startServer) {
  vm.invoke(new SerializableCallable() {
    @Override
    public Object call() throws Exception {
      Properties props = new Properties();
      props.put(GROUPS, groups);
      if (regionName != null) {
        Cache c = null;
        try {
          c = CacheFactory.getInstance(getSystem(props));
          c.close();
        } catch (CacheClosedException cce) {
        }
        c = CacheFactory.create(getSystem(props));
        c.createRegionFactory(RegionShortcut.PARTITION).create(regionName);
        if (startServer) {
          CacheServer s = c.addCacheServer();
          s.setPort(AvailablePortHelper.getRandomAvailableTCPPort());
          s.start();
        }
      } else {
        getSystem(props);
      }
      return null;
    }
  });
}
 
Example 46
Project: monarch   File: RegionDestroyFunction.java   Source Code and License 5 votes vote down vote up
@Override
public void execute(FunctionContext context) {
  String regionPath = null;
  try {
    String functionId = context.getFunctionId();
    if (getId().equals(functionId)) {
      Object arguments = context.getArguments();
      if (arguments != null) {
        regionPath = (String) arguments;
        Cache cache = CacheFactory.getAnyInstance();
        Region<?, ?> region = cache.getRegion(regionPath);
        region.destroyRegion();
        String regionName =
            regionPath.startsWith(Region.SEPARATOR) ? regionPath.substring(1) : regionPath;
        XmlEntity xmlEntity = new XmlEntity(CacheXml.REGION, "name", regionName);
        context.getResultSender().lastResult(new CliFunctionResult("", xmlEntity, regionPath));
      }
    }
    context.getResultSender().lastResult(new CliFunctionResult("", false, "FAILURE"));
  } catch (IllegalStateException e) {
    context.getResultSender().lastResult(new CliFunctionResult("", e, null));
  } catch (Exception ex) {
    context.getResultSender()
        .lastResult(new CliFunctionResult("",
            new RuntimeException(CliStrings.format(
                CliStrings.DESTROY_REGION__MSG__ERROR_WHILE_DESTROYING_REGION_0_REASON_1,
                new Object[] {regionPath, ex.getMessage()})),
            null));
  }
}
 
Example 47
Project: monarch   File: JSONFormatterJUnitTest.java   Source Code and License 5 votes vote down vote up
private void verifyJsonToPdxInstanceConversionWithJSONFormatter() {
  TestObjectForJSONFormatter expectedTestObject = new TestObjectForJSONFormatter();
  expectedTestObject.defaultInitialization();
  Cache c = CacheFactory.getAnyInstance();
  Region region = c.getRegion("primitiveKVStore");

  // 1.gets pdxInstance using R.put() and R.get()
  region.put("501", expectedTestObject);
  Object receivedObject = region.get("501");
  assertEquals("receivedObject is expected to be of type PdxInstance", PdxInstanceImpl.class,
      receivedObject.getClass());

  PdxInstance expectedPI = (PdxInstance) receivedObject;

  String json;
  try {
    json = JSONFormatter.toJSON(expectedPI);

    String jsonWithClassType = expectedTestObject.addClassTypeToJson(json);

    // 3. Get PdxInstance from the Json String and Validate pi.getObject() API.
    PdxInstance actualPI = JSONFormatter.fromJSON(jsonWithClassType);
    // Note: expectedPI will contains those fields that are part of toData()
    // expectedPI.className = "org.apache.geode.pdx.TestObjectForJSONFormatter"
    // actualPI will contains all the fields that are member of the class.
    // actualPI..className = __GEMFIRE_JSON
    // and hence actualPI.equals(expectedPI) will returns false.

    Object actualTestObject = actualPI.getObject();

    assertEquals("receivedObject is expected to be of type PdxInstance",
        TestObjectForJSONFormatter.class, actualTestObject.getClass());

    assertEquals("actualTestObject and expectedTestObject should be equal", expectedTestObject,
        actualTestObject);
  } catch (JSONException e) {
    fail("JSONException occurred:" + e.getMessage());
  }
}
 
Example 48
Project: monarch   File: QueryUsingFunctionContextDUnitTest.java   Source Code and License 5 votes vote down vote up
public void createIndex() {
  QueryService qs = CacheFactory.getAnyInstance().getQueryService();
  try {
    qs.createIndex("ID1", "ID", "/" + PartitionedRegionName1);
    qs.createIndex("ID2", "ID", "/" + PartitionedRegionName2);
    qs.createIndex("ID3", "ID", "/" + PartitionedRegionName3);
  } catch (Exception e) {
    fail("Index creation failed " + e);
  }
}
 
Example 49
Project: monarch   File: QueryUsingFunctionContextDUnitTest.java   Source Code and License 5 votes vote down vote up
@Override
public void execute(FunctionContext context) {
  Cache cache = CacheFactory.getAnyInstance();
  QueryService queryService = cache.getQueryService();
  ArrayList allQueryResults = new ArrayList();
  String qstr = (String) context.getArguments();
  try {
    Query query = queryService.newQuery(qstr);
    context.getResultSender().lastResult(
        (ArrayList) ((SelectResults) query.execute((RegionFunctionContext) context)).asList());
  } catch (Exception e) {
    throw new FunctionException(e);
  }
}
 
Example 50
Project: monarch   File: QueryDataInconsistencyDUnitTest.java   Source Code and License 5 votes vote down vote up
private void createProxyRegs() {
  ClientCache cache = (ClientCache) CacheFactory.getAnyInstance();
  cache.createClientRegionFactory(ClientRegionShortcut.PROXY).create(repRegionName);

  /*
   * cache.createClientRegionFactory(ClientRegionShortcut.PROXY).create( PartitionedRegionName1);
   */
}
 
Example 51
Project: monarch   File: InterestListRecoveryDUnitTest.java   Source Code and License 5 votes vote down vote up
private Cache createCache(Properties props) throws Exception {
  DistributedSystem ds = getSystem(props);
  Cache cache = null;
  cache = CacheFactory.create(ds);
  if (cache == null) {
    throw new Exception("CacheFactory.create() returned null ");
  }
  return cache;
}
 
Example 52
Project: monarch   File: MapFunctionalJUnitTest.java   Source Code and License 5 votes vote down vote up
@BeforeClass
public static void caseSetUp() throws Exception {
  Properties properties = new Properties();
  properties.setProperty(MCAST_PORT, "0");
  properties.setProperty(LOCATORS, "");
  distributedSystem = DistributedSystem.connect(properties);
  Cache cache = CacheFactory.create(distributedSystem);
  AttributesFactory factory = new AttributesFactory();
  factory.setScope(Scope.GLOBAL);
  RegionAttributes regionAttributes = factory.create();
  testRegion = cache.createRegion("TestRegion", regionAttributes);
}
 
Example 53
Project: monarch   File: RegionAdminRequest.java   Source Code and License 5 votes vote down vote up
/**
 * @throws org.apache.geode.cache.CacheRuntimeException if no cache created
 */
protected Region getRegion(DistributedSystem sys) {
  Cache cache = CacheFactory.getInstance(sys);
  Region r = cache.getRegion(regionName);
  if (r == null) {
    throw new RegionNotFoundException(
        LocalizedStrings.RegionAdminRequest_REGION_0_NOT_FOUND_IN_REMOTE_CACHE_1
            .toLocalizedString(new Object[] {regionName, cache.getName()}));
  }
  return r;
}
 
Example 54
Project: monarch   File: RegionSnapshotJUnitTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testDSID() throws Exception {
  cache.close();

  CacheFactory cf = new CacheFactory().set(MCAST_PORT, "0").set(LOG_LEVEL, "error")
      .setPdxSerializer(new MyPdxSerializer()).set(DISTRIBUTED_SYSTEM_ID, "1");
  cache = cf.create();

  RegionType rt = RegionType.REPLICATE;
  SerializationType st = SerializationType.PDX_SERIALIZER;

  String name = "test-" + rt.name() + "-" + st.name() + "-dsid";
  Region<Integer, MyObject> region = rgen.createRegion(cache, ds.getName(), rt, name);
  final Map<Integer, MyObject> expected = createExpected(st);

  region.putAll(expected);
  region.getSnapshotService().save(f, SnapshotFormat.GEMFIRE);

  cache.close();

  // change the DSID from 1 -> 100
  CacheFactory cf2 = new CacheFactory().set(MCAST_PORT, "0").set(LOG_LEVEL, "error")
      .setPdxSerializer(new MyPdxSerializer()).set(DISTRIBUTED_SYSTEM_ID, "100");
  cache = cf2.create();

  final Map<Integer, Object> read = new HashMap<Integer, Object>();
  SnapshotIterator<Integer, Object> iter = SnapshotReader.read(f);
  try {
    while (iter.hasNext()) {
      Entry<Integer, Object> entry = iter.next();
      read.put(entry.getKey(), entry.getValue());
    }
    assertEquals("Comparison failure for " + rt.name() + "/" + st.name(), expected, read);
  } finally {
    iter.close();
  }
}
 
Example 55
Project: monarch   File: MigrationClient.java   Source Code and License 5 votes vote down vote up
/**
 * create the cache to be used by this migration server
 * 
 * @throws Exception if there are any problems
 */
private void createCache() throws Exception {
  if (this.distributedSystem == null) {
    this.distributedSystem = InternalDistributedSystem.getConnectedInstance();
  }
  this.cache = CacheFactory.create(this.distributedSystem);
}
 
Example 56
Project: monarch   File: JSONPdxClientServerDUnitTest.java   Source Code and License 5 votes vote down vote up
private int createServerRegionWithPersistence(VM vm, final boolean persistentPdxRegistry) {
  SerializableCallable createRegion = new SerializableCallable() {
    public Object call() throws Exception {
      CacheFactory cf = new CacheFactory();
      if (persistentPdxRegistry) {
        cf.setPdxPersistent(true).setPdxDiskStore("store");
      }
      //
      Cache cache = getCache(cf);
      cache.createDiskStoreFactory().setDiskDirs(getDiskDirs()).create("store");

      AttributesFactory af = new AttributesFactory();
      af.setScope(Scope.DISTRIBUTED_ACK);
      af.setDataPolicy(DataPolicy.PERSISTENT_REPLICATE);
      af.setDiskStoreName("store");
      createRootRegion("testSimplePdx", af.create());

      CacheServer server = getCache().addCacheServer();
      int port = AvailablePortHelper.getRandomAvailableTCPPort();
      server.setPort(port);
      server.start();
      return port;
    }
  };

  return (Integer) vm.invoke(createRegion);
}
 
Example 57
Project: monarch   File: RegionCloseDUnitTest.java   Source Code and License 5 votes vote down vote up
private void createCache(Properties props) throws Exception {
  DistributedSystem ds = getSystem(props);
  assertNotNull(ds);
  ds.disconnect();
  ds = getSystem(props);
  cache = CacheFactory.create(ds);
  assertNotNull(cache);
}
 
Example 58
Project: monarch   File: LocalFunctionExecutionDUnitTest.java   Source Code and License 5 votes vote down vote up
public void createCache() {
  try {
    Properties props = new Properties();
    DistributedSystem ds = getSystem(props);
    assertNotNull(ds);
    ds.disconnect();
    ds = getSystem(props);
    cache = CacheFactory.create(ds);
    assertNotNull(cache);
  } catch (Exception e) {
    Assert.fail("Failed while creating the cache", e);
  }
}
 
Example 59
Project: monarch   File: InternalClientMembership.java   Source Code and License 5 votes vote down vote up
public static Map getClientQueueSizes() {
  Map clientQueueSizes = new HashMap();
  GemFireCacheImpl c = (GemFireCacheImpl) CacheFactory.getAnyInstance();
  if (c == null) // Add a NULL Check
    return clientQueueSizes;

  for (Iterator bsii = c.getCacheServers().iterator(); bsii.hasNext();) {
    CacheServerImpl bsi = (CacheServerImpl) bsii.next();
    AcceptorImpl ai = bsi.getAcceptor();
    if (ai != null && ai.getCacheClientNotifier() != null) {
      clientQueueSizes.putAll(ai.getCacheClientNotifier().getClientQueueSizes());
    }
  } // for
  return clientQueueSizes;
}
 
Example 60
Project: monarch   File: RedundancyLevelTestBase.java   Source Code and License 5 votes vote down vote up
private void createCache(Properties props) throws Exception {
  DistributedSystem ds = getSystem(props);
  assertNotNull(ds);
  ds.disconnect();
  ds = getSystem(props);
  cache = CacheFactory.create(ds);
  assertNotNull(cache);
}