/** * Version-dependent support for configuring a cache factory from the the given cache * configuration and distributed system. */ protected static Cache configureAndCreateCache( String cacheConfig, CacheDescription cd, DistributedSystem ds) { // configure the cache factory CacheFactory f = new CacheFactory(); Log.getLogWriter().info("Configuring cache factory from config: " + cacheConfig); cd.configure(f); // create the cache Log.getLogWriter().info("Creating cache"); return f.create(); }
public static Integer createCacheServerFromXml(URL url) { CacheFactory ccf = new CacheFactory(); try { File cacheXmlFile = new File(url.toURI().getPath()); ccf.set("cache-xml-file", cacheXmlFile.toURI().getPath()); ccf.set("mcast-port", "0"); ccf.set("locators", "localhost[" + DistributedTestCase.getDUnitLocatorPort() + "]"); } catch (URISyntaxException e) { throw new ExceptionInInitializerError(e); } cache = ccf.create(); return new Integer(cache.getCacheServers().get(0).getPort()); }
/** * Version-dependent support for {@link CacheHelper#getCache}. * * <p>Returns the cache if it exists and is open, or null if no cache exists. */ protected static synchronized Cache getCache() { try { return CacheFactory.getAnyInstance(); } catch (CancelException e) { return null; } }
@Override public ArrayList<HashMap> doExecute(Map<String, Object> args) { Cache cache = CacheFactory.getAnyInstance(); String regionPath = (String) args.get(ApiConstant.REGIONPATH); Region region = cache.getRegion(regionPath); ArrayList<HashMap> list = new ArrayList<HashMap>(); if (region != null && region instanceof PartitionedRegion) { DistributedMember member = cache.getDistributedSystem().getDistributedMember(); PartitionedRegion pr = (PartitionedRegion) region; if (pr.getDataStore() != null) { Set<BucketRegion> set2 = pr.getDataStore().getAllLocalBucketRegions(); for (BucketRegion br : set2) { HashMap map = new HashMap(); map.put("BucketId", br.getId()); map.put("Size", br.size()); map.put("Bytes", br.getTotalBytes()); map.put("host", getHost()); map.put("node", System.getProperty("NODE_NAME")); InternalDistributedMember m = pr.getBucketPrimary(br.getId()); if (m != null && member.getId().equals(m.getId())) { map.put("type", "primary"); } else { map.put("type", "redundant"); } map.put("TotalNumBuckets", pr.getPartitionAttributes().getTotalNumBuckets()); list.add(map); } } } return list; }
@Override public void execute(FunctionContext context) { StringBuilder str1 = new StringBuilder(); Map<String, String> resultMap = null; try { Cache cache = CacheFactory.getAnyInstance(); DistributedMember member = cache.getDistributedSystem().getDistributedMember(); long freeMemoeryBeforeGC = Runtime.getRuntime().freeMemory(); long totalMemoryBeforeGC = Runtime.getRuntime().totalMemory(); long timeBeforeGC = System.currentTimeMillis(); Runtime.getRuntime().gc(); long freeMemoeryAfterGC = Runtime.getRuntime().freeMemory(); long totalMemoryAfterGC = Runtime.getRuntime().totalMemory(); long timeAfterGC = System.currentTimeMillis(); long megaBytes = 131072; resultMap = new HashMap<String, String>(); resultMap.put("MemberId", member.getId()); resultMap.put( "HeapSizeBeforeGC", String.valueOf((totalMemoryBeforeGC - freeMemoeryBeforeGC) / megaBytes)); resultMap.put( "HeapSizeAfterGC", String.valueOf((totalMemoryAfterGC - freeMemoeryAfterGC) / megaBytes)); resultMap.put("TimeSpentInGC", String.valueOf(timeAfterGC - timeBeforeGC)); } catch (Exception ex) { str1.append( "Exception in GC:" + ex.getMessage() + CliUtil.stackTraceAsString((Throwable) ex)); context.getResultSender().lastResult(str1.toString()); } context.getResultSender().lastResult(resultMap); }
public static void init() throws Exception { Properties props = new Properties(); int pid = OSProcess.getId(); String path = File.createTempFile("dunit-cachejta_", ".xml").getAbsolutePath(); /** * Return file as string and then modify the string accordingly ** */ String file_as_str = readFile(TestUtil.getResourcePath(CacheUtils.class, "cachejta.xml")); file_as_str = file_as_str.replaceAll("newDB", "newDB_" + pid); String modified_file_str = modifyFile(file_as_str); FileOutputStream fos = new FileOutputStream(path); BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(fos)); wr.write(modified_file_str); wr.flush(); wr.close(); props.setProperty("cache-xml-file", path); // String tableName = ""; // props.setProperty("mcast-port", "10339"); try { // ds = DistributedSystem.connect(props); ds = (new ExceptionsDUnitTest("temp")).getSystem(props); cache = CacheFactory.create(ds); } catch (Exception e) { e.printStackTrace(System.err); throw new Exception("" + e); } }
private void createCache(Properties props) throws Exception { DistributedSystem ds = getSystem(props); assertNotNull(ds); ds.disconnect(); ds = getSystem(props); cache = CacheFactory.create(ds); assertNotNull(cache); }
/** * creates the cache * * @param props * @return Cache * @throws Exception */ 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; }
public static void startCache() { try { if (cache == null || cache.isClosed()) { cache = CacheFactory.create(ds); } } catch (Exception e) { e.printStackTrace(); } }
private void init() throws SystemException { this.cache = (GemFireCacheImpl) CacheFactory.getAnyInstance(); LogWriter logger = this.cache.getLogger(); if (logger.fineEnabled()) { logger.fine("JCAManagedConnection:init. Inside init"); } gfTxMgr = cache.getTxManager(); this.initDone = true; }
/** * Use the CacheXmlGenerator to create XML from the entity associated with the current cache. * * @return XML string representation of the entity. */ private final String loadXmlDefinition() { final Cache cache = CacheFactory.getAnyInstance(); final StringWriter stringWriter = new StringWriter(); final PrintWriter printWriter = new PrintWriter(stringWriter); CacheXmlGenerator.generate(cache, printWriter, true, false, false); printWriter.close(); return loadXmlDefinition(stringWriter.toString()); }
@Before public void setUp() throws Exception { Properties p = new Properties(); p.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); p.setProperty(DistributionConfig.OFF_HEAP_MEMORY_SIZE_NAME, "1m"); this.ds = DistributedSystem.connect(p); this.cache = (GemFireCacheImpl) CacheFactory.create(this.ds); logger.info(addExpectedAbove); logger.info(addExpectedBelow); }
private static LogWriter getLogWriter() { try { Cache cache = CacheFactory.getAnyInstance(); if (cache == null) { return null; } return cache.getLogger(); } catch (Exception ex) { return null; } }
@Override public void execute(FunctionContext context) { final IndexInfo indexInfo = (IndexInfo) context.getArguments(); String memberId = null; try { Cache cache = CacheFactory.getAnyInstance(); memberId = cache.getDistributedSystem().getDistributedMember().getId(); QueryService queryService = cache.getQueryService(); String indexName = indexInfo.getIndexName(); String indexedExpression = indexInfo.getIndexedExpression(); String regionPath = indexInfo.getRegionPath(); switch (indexInfo.getIndexType()) { case IndexInfo.RANGE_INDEX: queryService.createIndex(indexName, indexedExpression, regionPath); break; case IndexInfo.KEY_INDEX: queryService.createKeyIndex(indexName, indexedExpression, regionPath); break; case IndexInfo.HASH_INDEX: queryService.createHashIndex(indexName, indexedExpression, regionPath); break; default: queryService.createIndex(indexName, indexedExpression, regionPath); } XmlEntity xmlEntity = new XmlEntity(CacheXml.REGION, "name", cache.getRegion(regionPath).getName()); context.getResultSender().lastResult(new CliFunctionResult(memberId, xmlEntity)); } catch (IndexExistsException e) { String message = CliStrings.format(CliStrings.CREATE_INDEX__INDEX__EXISTS, indexInfo.getIndexName()); context.getResultSender().lastResult(new CliFunctionResult(memberId, false, message)); } catch (IndexNameConflictException e) { String message = CliStrings.format(CliStrings.CREATE_INDEX__NAME__CONFLICT, indexInfo.getIndexName()); context.getResultSender().lastResult(new CliFunctionResult(memberId, false, message)); } catch (RegionNotFoundException e) { String message = CliStrings.format( CliStrings.CREATE_INDEX__INVALID__REGIONPATH, indexInfo.getRegionPath()); context.getResultSender().lastResult(new CliFunctionResult(memberId, false, message)); } catch (IndexInvalidException e) { context.getResultSender().lastResult(new CliFunctionResult(memberId, e, e.getMessage())); } catch (Exception e) { String exceptionMessage = CliStrings.format( CliStrings.EXCEPTION_CLASS_AND_MESSAGE, e.getClass().getName(), e.getMessage()); context.getResultSender().lastResult(new CliFunctionResult(memberId, e, exceptionMessage)); } }
/** * Used supplied xmlDocument to extract the XML for the defined {@link XmlEntity}. * * @param xmlDocument to extract XML from. * @return XML for {@link XmlEntity} if found, otherwise <code>null</code>. * @since 8.1 */ private final String loadXmlDefinition(final String xmlDocument) { final Cache cache = CacheFactory.getAnyInstance(); try { InputSource inputSource = new InputSource(new StringReader(xmlDocument)); return loadXmlDefinition(XmlUtils.getDocumentBuilder().parse(inputSource)); } catch (IOException | SAXException | ParserConfigurationException | XPathExpressionException | TransformerFactoryConfigurationError | TransformerException e) { throw new InternalGemFireError("Could not parse XML when creating XMLEntity", e); } }
@Override public void init(final Properties parameters) { String regionName = parameters.getProperty(REGION_PARAMETER_NAME); String dataPolicyName = parameters.getProperty(DATA_POLICY_PARAMETER_NAME); Cache gemfireCache = CacheFactory.getAnyInstance(); assertThat(gemfireCache, is(notNullValue())); Region<K, V> region = gemfireCache.getRegion(toRegionPath(regionName)); assertRegion(region, regionName, resolveDataPolicy(dataPolicyName)); region.putAll(getRegionData()); }
/** * Tests that we are in {@link GemFireHealth#OKAY_HEALTH okay} health if the hit ratio dips below * the threshold. */ public void testCheckHitRatio() throws CacheException { Cache cache = CacheFactory.create(this.system); // CachePerfStats stats = ((GemFireCache) cache).getCachePerfStats(); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); factory.setCacheLoader( new CacheLoader() { public Object load(LoaderHelper helper) throws CacheLoaderException { return "Loaded"; } public void close() {} }); RegionAttributes attrs = factory.create(); Region region = cache.createRegion(this.getName(), attrs); GemFireHealthConfig config = new GemFireHealthConfigImpl(null); config.setMinHitRatio(0.5); CacheHealthEvaluator eval = new CacheHealthEvaluator(config, this.system.getDistributionManager()); List status = new ArrayList(); eval.evaluate(status); assertEquals(0, status.size()); region.get("One"); region.get("One"); region.get("One"); status = new ArrayList(); eval.evaluate(status); assertEquals(0, status.size()); for (int i = 0; i < 50; i++) { region.get("Miss " + i); } status = new ArrayList(); eval.evaluate(status); AbstractHealthEvaluator.HealthStatus ill = (AbstractHealthEvaluator.HealthStatus) status.get(0); assertEquals(GemFireHealth.OKAY_HEALTH, ill.getHealthCode()); String s = "The hit ratio of this Cache"; assertTrue(ill.getDiagnosis().indexOf(s) != -1); }
@Override public RemoteResult remoteExecute(Object userArgs, Set<Object> filters) { Cache c = CacheFactory.getAnyInstance(); Region r = c.getRegion(regionName); Map<String, Object> map = new HashMap<>(); // class com.gemstone.gemfire.internal.cache.execute.PartitionedRegionFunctionExecutor Execution ex = FunctionService.onRegion(r); ex = ex.withFilter(filters); map.put(PARAM_MODULE_NAME, moduleName); map.put(PARAM_BEAN_NAME, beanName); map.put(PARAM_URSER_ARGS, userArgs); ex = ex.withArgs(map); RemoteResult rr = new RemoteResult(ex); return rr; }
private DistributedRegion getRegion(DistributionManager dm) { if (region != null) { return region; } // set the init level requirement so that we don't hang in CacheFactory.getInstance() (bug // 36175) int oldLevel = LocalRegion.setThreadInitLevelRequirement(LocalRegion.BEFORE_INITIAL_IMAGE); try { GemFireCacheImpl gfc = (GemFireCacheImpl) CacheFactory.getInstance(dm.getSystem()); Region r = gfc.getRegionByPathForProcessing(this.regionPath); if (r instanceof DistributedRegion) { region = (DistributedRegion) r; } } finally { LocalRegion.setThreadInitLevelRequirement(oldLevel); } return region; }
/** returns a set of all DistributedRegions for allRegions processing */ private Set<DistributedRegion> getAllRegions(DistributionManager dm) { // set the init level requirement so that we don't hang in CacheFactory.getInstance() (bug // 36175) int oldLevel = LocalRegion.setThreadInitLevelRequirement(LocalRegion.BEFORE_INITIAL_IMAGE); try { GemFireCacheImpl gfc = (GemFireCacheImpl) CacheFactory.getInstance(dm.getSystem()); Set<DistributedRegion> result = new HashSet(); for (LocalRegion r : gfc.getAllRegions()) { // it's important not to check if the cache is closing, so access // the isDestroyed boolean directly if (r instanceof DistributedRegion && !r.isDestroyed) { result.add((DistributedRegion) r); } } return result; } finally { LocalRegion.setThreadInitLevelRequirement(oldLevel); } }
/** Creates and starts the server instance */ private int createServer() { CacheServer server = null; try { 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.setMaximumTimeBetweenPings(TIME_BETWEEN_PINGS); server.setMaxThreads(getMaxThreads()); server.setPort(port); server.start(); } catch (Exception e) { e.printStackTrace(); fail("Failed to create server"); } return server.getPort(); }
/** * Used supplied XML {@link Document} to extract the XML for the defined {@link XmlEntity}. * * @param document to extract XML from. * @return XML for {@link XmlEntity} if found, otherwise <code>null</code>. * @throws XPathExpressionException * @throws TransformerException * @throws TransformerFactoryConfigurationError * @since 8.1 */ private final String loadXmlDefinition(final Document document) throws XPathExpressionException, TransformerFactoryConfigurationError, TransformerException { final Cache cache = CacheFactory.getAnyInstance(); this.searchString = createQueryString(prefix, type, attributes); logger.info("XmlEntity:searchString: {}", this.searchString); if (document != null) { XPathContext xpathContext = new XPathContext(); xpathContext.addNamespace(prefix, namespace); // Create an XPathContext here Node element = XmlUtils.querySingleElement(document, this.searchString, xpathContext); // Must copy to preserve namespaces. if (null != element) { return XmlUtils.elementToString(element); } } logger.warn( "No XML definition could be found with name={} and attributes={}", type, attributes); return null; }
public static void main(String[] args) throws Exception { Properties props = new Properties(); props.setProperty("name", "CqServer"); props.setProperty("log-level", "warning"); System.out.println("\nConnecting to the distributed system and creating the cache."); DistributedSystem ds = DistributedSystem.connect(props); Cache cache = CacheFactory.create(ds); // Create region. AttributesFactory factory = new AttributesFactory(); factory.setDataPolicy(DataPolicy.REPLICATE); factory.setScope(Scope.DISTRIBUTED_ACK); Region testRegion = cache.createRegion("test-cq", factory.create()); System.out.println("Test region, " + testRegion.getFullPath() + ", created in cache."); // Start Cache Server. CacheServer server = cache.addCacheServer(); server.setPort(40404); server.setNotifyBySubscription(true); server.start(); System.out.println("Waiting for signal"); // wait for signal BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); bufferedReader.readLine(); System.out.println("Received signal"); testRegion.put("one", 1); testRegion.put("two", 2); testRegion.put("three", 3); System.out.println("Waiting for shutdown"); bufferedReader.readLine(); }
@BeforeClass public static void setUp() throws Exception { CacheSingleton.getCache(); regionFactory = CacheFactory.getAnyInstance().createRegionFactory(); }
/** * Upon receipt of the message, both process the message and send an acknowledgement, not * necessarily in that order. Note: Any hang in this message may cause a distributed deadlock for * those threads waiting for an acknowledgement. * * @throws PartitionedRegionException if the region does not exist (typically, if it has been * destroyed) */ @Override public void process(final DistributionManager dm) { Throwable thr = null; boolean sendReply = true; LocalRegion r = null; long startTime = 0; try { if (checkCacheClosing(dm) || checkDSClosing(dm)) { thr = new CacheClosedException( LocalizedStrings.PartitionMessage_REMOTE_CACHE_IS_CLOSED_0.toLocalizedString( dm.getId())); return; } GemFireCacheImpl gfc = (GemFireCacheImpl) CacheFactory.getInstance(dm.getSystem()); r = gfc.getRegionByPathForProcessing(this.regionPath); if (r == null && failIfRegionMissing()) { // if the distributed system is disconnecting, don't send a reply saying // the partitioned region can't be found (bug 36585) thr = new RegionDestroyedException( LocalizedStrings.RemoteOperationMessage_0_COULD_NOT_FIND_REGION_1.toLocalizedString( new Object[] {dm.getDistributionManagerId(), regionPath}), regionPath); return; // reply sent in finally block below } thr = UNHANDLED_EXCEPTION; // [bruce] r might be null here, so we have to go to the cache instance to get the txmgr TXManagerImpl txMgr = GemFireCacheImpl.getInstance().getTxManager(); TXStateProxy tx = null; try { tx = txMgr.masqueradeAs(this); sendReply = operateOnRegion(dm, r, startTime); } finally { txMgr.unmasquerade(tx); } thr = null; } catch (RemoteOperationException fre) { thr = fre; } catch (DistributedSystemDisconnectedException se) { // bug 37026: this is too noisy... // throw new CacheClosedException("remote system shutting down"); // thr = se; cache is closed, no point trying to send a reply thr = null; sendReply = false; if (logger.isDebugEnabled()) { logger.debug("shutdown caught, abandoning message: {}", se.getMessage(), se); } } catch (RegionDestroyedException rde) { // [bruce] RDE does not always mean that the sender's region is also // destroyed, so we must send back an exception. If the sender's // region is also destroyed, who cares if we send it an exception // if (pr != null && pr.isClosed) { thr = new ForceReattemptException( LocalizedStrings.PartitionMessage_REGION_IS_DESTROYED_IN_0.toLocalizedString( dm.getDistributionManagerId()), rde); // } } catch (VirtualMachineError err) { SystemFailure.initiateFailure(err); // If this ever returns, rethrow the error. We're poisoned // now, so don't let this thread continue. throw err; } catch (Throwable t) { // Whenever you catch Error or Throwable, you must also // catch VirtualMachineError (see above). However, there is // _still_ a possibility that you are dealing with a cascading // error condition, so you also need to check to see if the JVM // is still usable: SystemFailure.checkFailure(); // log the exception at fine level if there is no reply to the message thr = null; if (sendReply) { if (!checkDSClosing(dm)) { thr = t; } else { // don't pass arbitrary runtime exceptions and errors back if this // cache/vm is closing thr = new ForceReattemptException( LocalizedStrings.PartitionMessage_DISTRIBUTED_SYSTEM_IS_DISCONNECTING .toLocalizedString()); } } if (logger.isTraceEnabled(LogMarker.DM) && (t instanceof RuntimeException)) { logger.trace(LogMarker.DM, "Exception caught while processing message", t); } } finally { if (sendReply) { ReplyException rex = null; if (thr != null) { // don't transmit the exception if this message was to a listener // and this listener is shutting down rex = new ReplyException(thr); } // Send the reply if the operateOnPartitionedRegion returned true sendReply(getSender(), this.processorId, dm, rex, r, startTime); } } }
/** * Tests that we are in {@link GemFireHealth#OKAY_HEALTH okay} health if cache loads take too * long. * * @see CacheHealthEvaluator#checkLoadTime */ public void testCheckLoadTime() throws CacheException { Cache cache = CacheFactory.create(this.system); CachePerfStats stats = ((GemFireCacheImpl) cache).getCachePerfStats(); AttributesFactory factory = new AttributesFactory(); factory.setScope(Scope.LOCAL); factory.setCacheLoader( new CacheLoader() { public Object load(LoaderHelper helper) throws CacheLoaderException { return "Loaded"; } public void close() {} }); RegionAttributes attrs = factory.create(); Region region = cache.createRegion(this.getName(), attrs); GemFireHealthConfig config = new GemFireHealthConfigImpl(null); config.setMaxLoadTime(100); CacheHealthEvaluator eval = new CacheHealthEvaluator(config, this.system.getDistributionManager()); for (int i = 0; i < 10; i++) { region.get("Test1 " + i); } long firstLoadTime = stats.getLoadTime(); long firstLoadsCompleted = stats.getLoadsCompleted(); assertTrue(firstLoadTime >= 0); assertTrue(firstLoadsCompleted > 0); // First time should always be empty List status = new ArrayList(); eval.evaluate(status); assertEquals(0, status.size()); config = new GemFireHealthConfigImpl(null); config.setMaxLoadTime(10); eval = new CacheHealthEvaluator(config, this.system.getDistributionManager()); eval.evaluate(status); long start = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { region.get("Test2 " + i); } assertTrue(System.currentTimeMillis() - start < 1000); long secondLoadTime = stats.getLoadTime(); long secondLoadsCompleted = stats.getLoadsCompleted(); assertTrue( "firstLoadTime=" + firstLoadTime + ", secondLoadTime=" + secondLoadTime, secondLoadTime >= firstLoadTime); assertTrue(secondLoadsCompleted > firstLoadsCompleted); // Averge should be less than 10 milliseconds status = new ArrayList(); eval.evaluate(status); assertEquals(0, status.size()); region .getAttributesMutator() .setCacheLoader( new CacheLoader() { public Object load(LoaderHelper helper) throws CacheLoaderException { try { Thread.sleep(20); } catch (InterruptedException ex) { fail("Why was I interrupted?"); } return "Loaded"; } public void close() {} }); for (int i = 0; i < 50; i++) { region.get("Test3 " + i); } long thirdLoadTime = stats.getLoadTime(); long thirdLoadsCompleted = stats.getLoadsCompleted(); assertTrue(thirdLoadTime > secondLoadTime); assertTrue(thirdLoadsCompleted > secondLoadsCompleted); status = new ArrayList(); eval.evaluate(status); assertEquals(1, status.size()); AbstractHealthEvaluator.HealthStatus ill = (AbstractHealthEvaluator.HealthStatus) status.get(0); assertEquals(GemFireHealth.OKAY_HEALTH, ill.getHealthCode()); String s = "The average duration of a Cache load"; assertTrue(ill.getDiagnosis().indexOf(s) != -1); }
/** * Initializes without children. * * @param region The region from which RegionInfo is extracted. */ @SuppressWarnings({"unchecked", "rawtypes"}) private void init(Region region) { if (region == null) { return; } DistributedMember member = CacheFactory.getAnyInstance().getDistributedSystem().getDistributedMember(); setName(region.getName()); setFullPath(region.getFullPath()); GemfireRegionAttributeInfo attrInfo = new GemfireRegionAttributeInfo(); RegionAttributes<?, ?> attr = region.getAttributes(); attrInfo.setAttribute(GemfireRegionAttributeInfo.DATA_POLICY, attr.getDataPolicy().toString()); attrInfo.setAttribute(GemfireRegionAttributeInfo.SCOPE, attr.getScope().toString()); if (region instanceof PartitionedRegion) { PartitionedRegion pr = (PartitionedRegion) region; PartitionAttributes pattr = pr.getPartitionAttributes(); attrInfo.setAttribute( GemfireRegionAttributeInfo.LOCAL_MAX_MEMORY, pattr.getLocalMaxMemory() + ""); attrInfo.setAttribute( GemfireRegionAttributeInfo.REDUNDANT_COPIES, pattr.getRedundantCopies() + ""); attrInfo.setAttribute( GemfireRegionAttributeInfo.TOTAL_MAX_MEMORY, pattr.getTotalMaxMemory() + ""); attrInfo.setAttribute( GemfireRegionAttributeInfo.TOTAL_NUM_BUCKETS, pattr.getTotalNumBuckets() + ""); // data store is null if it's a proxy, i.e., LOCAL_MAX_MEMORY=0 if (pr.getDataStore() != null) { Set<BucketRegion> localtBuketSet = pr.getDataStore().getAllLocalBucketRegions(); List<BucketInfo> primaryList = new ArrayList<BucketInfo>(); List<BucketInfo> redundantList = new ArrayList<BucketInfo>(); this.size = 0; for (BucketRegion br : localtBuketSet) { BucketInfo bucketInfo = new GemfireBucketInfo( br.getId(), br.getBucketAdvisor().isPrimary(), br.size(), br.getTotalBytes()); // InternalDistributedMember m = pr.getBucketPrimary(br.getId()); // if (m.getId().equals(member.getId())) { if (bucketInfo.isPrimary()) { primaryList.add(bucketInfo); this.size += bucketInfo.getSize(); } else { redundantList.add(bucketInfo); } } Collections.sort(primaryList); Collections.sort(redundantList); setPrimaryBucketInfoList(primaryList); setRedundantBucketInfoList(redundantList); } } else { this.size = region.size(); } setAttrInfo(attrInfo); temporalType = GemfireTemporalManager.getTemporalType(region); if (region.isDestroyed() == false && region.isEmpty() == false) { Set<Map.Entry> regionEntrySet = region.entrySet(); for (Map.Entry entry : regionEntrySet) { Object key = entry.getKey(); Object value = entry.getValue(); keyTypeName = key.getClass().getName(); valueTypeName = value.getClass().getName(); break; } } }
protected Cache createCache() { CacheFactory cf = new CacheFactory().set("mcast-port", "0").set("log-level", "info"); cache = cf.create(); return cache; }
/** Creates a <code>BridgeServerResponse</code> in response to the given request. */ static BridgeServerResponse create(DistributionManager dm, BridgeServerRequest request) { BridgeServerResponse m = new BridgeServerResponse(); m.setRecipient(request.getSender()); try { GemFireCacheImpl cache = (GemFireCacheImpl) CacheFactory.getInstanceCloseOk(dm.getSystem()); if (request.getCacheId() != System.identityHashCode(cache)) { m.bridgeInfo = null; } else { int operation = request.getOperation(); switch (operation) { case BridgeServerRequest.ADD_OPERATION: { BridgeServerImpl bridge = (BridgeServerImpl) cache.addBridgeServer(); m.bridgeInfo = new RemoteBridgeServer(bridge); break; } case BridgeServerRequest.INFO_OPERATION: { int id = request.getBridgeId(); // Note that since this is only an informational request // it is not necessary to synchronize on allBridgeServersLock for (Iterator iter = cache.getBridgeServers().iterator(); iter.hasNext(); ) { BridgeServerImpl bridge = (BridgeServerImpl) iter.next(); if (System.identityHashCode(bridge) == id) { m.bridgeInfo = new RemoteBridgeServer(bridge); break; } else { m.bridgeInfo = null; } } break; } case BridgeServerRequest.START_OPERATION: { RemoteBridgeServer config = request.getBridgeInfo(); for (Iterator iter = cache.getBridgeServers().iterator(); iter.hasNext(); ) { BridgeServerImpl bridge = (BridgeServerImpl) iter.next(); if (System.identityHashCode(bridge) == config.getId()) { bridge.configureFrom(config); bridge.start(); m.bridgeInfo = new RemoteBridgeServer(bridge); break; } else { m.bridgeInfo = null; } } break; } case BridgeServerRequest.STOP_OPERATION: { RemoteBridgeServer config = request.getBridgeInfo(); for (Iterator iter = cache.getBridgeServers().iterator(); iter.hasNext(); ) { BridgeServerImpl bridge = (BridgeServerImpl) iter.next(); if (System.identityHashCode(bridge) == config.getId()) { bridge.stop(); m.bridgeInfo = new RemoteBridgeServer(bridge); break; } else { m.bridgeInfo = null; } } break; } default: Assert.assertTrue(false, "Unknown bridge server operation: " + operation); } } } catch (CancelException ex) { m.bridgeInfo = null; } catch (Exception ex) { m.exception = ex; m.bridgeInfo = null; } return m; }