@Test public void get() { String key = getKey(getUser("imaPigg")); assertThat(usersTemplate.get(key)).isEqualTo(users.get(key)); assertNullEquals(users.get("mrT"), usersTemplate.get("mrT")); }
public static void assertGotAllValues() { Region region = cache.getRegion(Region.SEPARATOR + REGION_NAME); assertNotNull(region); assertTrue(region.get(PUTALL_KEY1).equals(PUTALL_VALUE1)); assertTrue(region.get(PUTALL_KEY2).equals(PUTALL_VALUE2)); assertTrue(region.get(PUTALL_KEY3).equals(PUTALL_VALUE3)); assertTrue(region.get(PUTALL_KEY4).equals(PUTALL_VALUE4)); assertTrue(region.get(PUTALL_KEY5).equals(PUTALL_VALUE5)); }
@Test public void replaceOldValueWithNewValue() { User jackHandy = getUser("jackHandy"); User imaPigg = getUser("imaPigg"); assertThat(users.containsValue(jackHandy)).isTrue(); assertThat(usersTemplate.replace(getKey(jackHandy), null, imaPigg)).isFalse(); assertThat(users.containsValue(jackHandy)).isTrue(); assertThat(users.get(getKey(jackHandy))).isEqualTo(jackHandy); assertThat(usersTemplate.replace(getKey(jackHandy), jackHandy, imaPigg)).isTrue(); assertThat(users.containsValue(jackHandy)).isFalse(); assertThat(users.get(getKey(jackHandy))).isEqualTo(imaPigg); }
@Test public void replace() { User randyHandy = users.get(getKey(getUser("randyHandy"))); User lukeFluke = newUser("lukeFluke"); User chrisGriffon = newUser("chrisGriffon"); assertThat(randyHandy).isNotNull(); assertThat(usersTemplate.replace(getKey(randyHandy), lukeFluke)).isEqualTo(randyHandy); assertThat(users.get(getKey(randyHandy))).isEqualTo(lukeFluke); assertThat(users.containsValue(randyHandy)).isFalse(); assertThat(users.containsValue(chrisGriffon)).isFalse(); assertThat(usersTemplate.replace(getKey(chrisGriffon), chrisGriffon)).isNull(); assertThat(users.containsValue(chrisGriffon)).isFalse(); }
public static void verifyDispatchedMessagesRemoved() { try { Region region = hrq.getRegion(); if (region.get(new Long(0)) != null) { fail("Expected message to have been deleted but it is not deleted"); } if (region.get(new Long(1)) == null) { fail("Expected message not to have been deleted but it is deleted"); } } catch (Exception e) { fail("test failed due to an exception : " + e); } }
/** * 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); }
@Test public void put() { User peterGriffon = newUser("peterGriffon"); assertThat(usersTemplate.put(getKey(peterGriffon), peterGriffon)).isNull(); assertThat(users.get(getKey(peterGriffon))).isEqualTo(peterGriffon); }
private ByteBuffer processAsciiCommand(ByteBuffer buffer, Cache cache) { CharBuffer flb = getFirstLineBuffer(); getAsciiDecoder().reset(); getAsciiDecoder().decode(buffer, flb, false); flb.flip(); String firstLine = getFirstLine(); String[] firstLineElements = firstLine.split(" "); assert "decr".equals(firstLineElements[0]); String key = firstLineElements[1]; String decrByStr = stripNewline(firstLineElements[2]); Long decrBy = Long.parseLong(decrByStr); boolean noReply = firstLineElements.length > 3; Region<Object, ValueWrapper> r = getMemcachedRegion(cache); String reply = Reply.NOT_FOUND.toString(); ByteBuffer newVal = ByteBuffer.allocate(8); while (true) { ValueWrapper oldValWrapper = r.get(key); if (oldValWrapper == null) { break; } newVal.clear(); byte[] oldVal = oldValWrapper.getValue(); long oldLong = getLongFromByteArray(oldVal); long newLong = oldLong - decrBy; newVal.putLong(newLong); ValueWrapper newValWrapper = ValueWrapper.getWrappedValue(newVal.array(), 0 /*flags*/); if (r.replace(key, oldValWrapper, newValWrapper)) { reply = newLong + "\r\n"; break; } } return noReply ? null : asciiCharset.encode(reply); }
@Test public void testFailedIndexUpdateOnCommitForPut() throws Exception { Person.THROW_ON_INDEX = true; AttributesFactory af = new AttributesFactory(); af.setDataPolicy(DataPolicy.REPLICATE); SimpleListener sl = new SimpleListener(); af.setCacheListener(sl); Region region = cache.createRegion("sample", af.create()); qs.createIndex("foo", IndexType.FUNCTIONAL, "index", "/sample"); Context ctx = cache.getJNDIContext(); Integer x = new Integer(0); region.getCache().getCacheTransactionManager().begin(); region.create(x, new Person("xyz", 45)); try { region.getCache().getCacheTransactionManager().commit(); fail("commit should have thrown an exception because the index maintenance threw"); } catch (com.gemstone.gemfire.cache.query.IndexMaintenanceException ie) { // this is the desired case } Person p = (Person) region.get(x); assertEquals("object shouldn't have made it into region", null, p); assertEquals(0, sl.creates); assertEquals(0, sl.updates); }
/** * Update an existing key in region REGION_NAME. The keys to update are specified in keyIntervals. * * @return true if all keys to be updated have been completed. */ protected boolean updateExistingKey() { long nextKey = CQUtilBB.getBB().getSharedCounters().incrementAndRead(CQUtilBB.LASTKEY_UPDATE_EXISTING_KEY); if (!keyIntervals.keyInRange(KeyIntervals.UPDATE_EXISTING_KEY, nextKey)) { Log.getLogWriter().info("All existing keys updated; returning from updateExistingKey"); return true; } Object key = NameFactory.getObjectNameForCounter(nextKey); QueryObject existingValue = (QueryObject) aRegion.get(key); if (existingValue == null) throw new TestException("Get of key " + key + " returned unexpected " + existingValue); QueryObject newValue = existingValue.modifyWithNewInstance(QueryObject.NEGATE, 0, true); newValue.extra = key; // encode the key in the object for later validation if (existingValue.aPrimitiveLong < 0) throw new TestException( "Trying to update a key which was already updated: " + existingValue.toStringFull()); Log.getLogWriter() .info("Updating existing key " + key + " with value " + TestHelper.toString(newValue)); aRegion.put(key, newValue); Log.getLogWriter() .info( "Done updating existing key " + key + " with value " + TestHelper.toString(newValue) + ", num remaining: " + (keyIntervals.getLastKey(KeyIntervals.UPDATE_EXISTING_KEY) - nextKey)); return (nextKey >= keyIntervals.getLastKey(KeyIntervals.UPDATE_EXISTING_KEY)); }
/** * Do a get on a key in region REGION_NAME. Keys to get are specified in keyIntervals. * * @return true if all keys to have get performaed have been completed. */ protected boolean get() { SharedCounters sc = CQUtilBB.getBB().getSharedCounters(); long nextKey = sc.incrementAndRead(CQUtilBB.LASTKEY_GET); if (!keyIntervals.keyInRange(KeyIntervals.GET, nextKey)) { Log.getLogWriter().info("All gets completed; returning from get"); return true; } Object key = NameFactory.getObjectNameForCounter(nextKey); Log.getLogWriter().info("Getting " + key); try { Object existingValue = aRegion.get(key); Log.getLogWriter() .info( "Done getting " + key + ", num remaining: " + (keyIntervals.getLastKey(KeyIntervals.GET) - nextKey)); if (existingValue == null) throw new TestException("Get of key " + key + " returned unexpected " + existingValue); } catch (TimeoutException e) { throw new TestException(TestHelper.getStackTrace(e)); } catch (CacheLoaderException e) { throw new TestException(TestHelper.getStackTrace(e)); } return (nextKey >= keyIntervals.getLastKey(KeyIntervals.GET)); }
public void getRESTClientObject(Region region) { Object value1 = region.get("1"); if (value1 instanceof PdxInstance) { System.out.println("InstanceOf PdxInstance " + value1.toString()); } else System.out.println("NOt InstanceOf PdxInstance"); /* Person value1 = (Person) region.get("1"); System.out.println("Person Received on String type key =1 : " + value1.toString()); */ /* Person value = (Person) region.get(1); if(value != null) System.out.println("Person Received on INT type key =1 : " + value.toString()); else System.out.println("Value got on INT key 1 is null"); Person value2 = (Person) region.get(2); System.out.println("Person Received on int type key = 2 : " + value2.toString()); Person value3 = (Person) region.get("2"); if(value3 != null){ System.out.println("Person Received on String type key = 2 : " + value3.toString()); }else System.out.println("Value got on String key --> 2 is NULL VALUE ....!!"); */ }
@Test public void create() { User bartSimpson = newUser("bartSimpson"); usersTemplate.create(getKey(bartSimpson), bartSimpson); assertThat(users.containsKey(getKey(bartSimpson))).isTrue(); assertThat(users.containsValueForKey(getKey(bartSimpson))).isTrue(); assertThat(users.containsValue(bartSimpson)).isTrue(); assertThat(users.get(getKey(bartSimpson))).isEqualTo(bartSimpson); }
@Test public void putIfAbsent() { User stewieGriffon = newUser("stewieGriffon"); assertThat(users.containsValue(stewieGriffon)).isFalse(); assertThat(usersTemplate.putIfAbsent(getKey(stewieGriffon), stewieGriffon)).isNull(); assertThat(users.containsValue(stewieGriffon)).isTrue(); assertThat(usersTemplate.putIfAbsent(getKey(stewieGriffon), newUser("megGriffon"))) .isEqualTo(stewieGriffon); assertThat(users.get(getKey(stewieGriffon))).isEqualTo(stewieGriffon); }
@Test public void remove() { User mandyHandy = users.get(getKey(getUser("mandyHandy"))); assertThat(mandyHandy).isNotNull(); assertThat(usersTemplate.remove(getKey(mandyHandy))).isEqualTo(mandyHandy); assertThat(users.containsKey(getKey(mandyHandy))).isFalse(); assertThat(users.containsValue(mandyHandy)).isFalse(); assertThat(users.containsKey("loisGriffon")).isFalse(); assertThat(usersTemplate.remove("loisGriffon")).isNull(); assertThat(users.containsKey("loisGriffon")).isFalse(); }
/** do a get on region1 */ public static void getValue2() { try { Region r = cache.getRegion(Region.SEPARATOR + REGION_NAME); if (!(r.get("key-1").equals("value-2"))) { fail("expected value to be value-2 but it is not so"); } } catch (Exception ex) { ex.printStackTrace(); fail("failed while region.get()", ex); } }
@Test public void testIndexOnCommitForDestroy() throws Exception { AttributesFactory af = new AttributesFactory(); af.setDataPolicy(DataPolicy.REPLICATE); Region region = cache.createRegion("sample", af.create()); qs.createIndex("foo", IndexType.FUNCTIONAL, "age", "/sample"); Context ctx = cache.getJNDIContext(); UserTransaction utx = (UserTransaction) ctx.lookup("java:/UserTransaction"); Integer x = new Integer(0); utx.begin(); region.create(x, new Person("xyz", 45)); utx.commit(); Query q = qs.newQuery("select * from /sample where age < 50"); assertEquals(1, ((SelectResults) q.execute()).size()); Person dsample = (Person) CopyHelper.copy(region.get(x)); dsample.setAge(55); utx.begin(); region.destroy(x); utx.commit(); CacheUtils.log(((Person) region.get(x))); assertEquals(0, ((SelectResults) q.execute()).size()); }
/** * Tests that a local writer receives a modified version of the callback argument on an update. */ public void testLocalUpdateModifiedCallbackArgument() throws CacheException { final String name = this.getUniqueName(); final Object key = "KEY"; final Object value = "VALUE"; final Object one = "ONE"; final Object two = "TWO"; TestCacheLoader loader = new TestCacheLoader() { public Object load2(LoaderHelper helper) throws CacheLoaderException { Object[] array = (Object[]) helper.getArgument(); assertEquals(one, array[0]); array[0] = two; return value; } }; TestCacheWriter writer = new TestCacheWriter() { public void beforeCreate2(EntryEvent event) throws CacheWriterException {} public void beforeUpdate2(EntryEvent event) throws CacheWriterException { Object[] array = (Object[]) event.getCallbackArgument(); assertEquals(two, array[0]); } }; AttributesFactory factory = new AttributesFactory(getRegionAttributes()); factory.setCacheLoader(loader); factory.setCacheWriter(writer); Region region = createRegion(name, factory.create()); region.create(key, null); assertFalse(loader.wasInvoked()); assertTrue(writer.wasInvoked()); Object[] array = new Object[] {one}; assertEquals(value, region.get(key, array)); assertTrue(loader.wasInvoked()); assertTrue(writer.wasInvoked()); }
@Test public void computeFactorials() { assertThat(factorials.get(0L), is(equalTo(1L))); assertThat(factorials.get(1L), is(equalTo(1L))); assertThat(factorials.get(2L), is(equalTo(2L))); assertThat(factorials.get(3L), is(equalTo(6L))); assertThat(factorials.get(4L), is(equalTo(24L))); assertThat(factorials.get(5L), is(equalTo(120L))); assertThat(factorials.get(6L), is(equalTo(720L))); assertThat(factorials.get(7L), is(equalTo(5040L))); assertThat(factorials.get(8L), is(equalTo(40320L))); assertThat(factorials.get(9L), is(equalTo(362880L))); assertThat(factorials.get(10L), is(equalTo(3628800L))); }
public static int printEntries(Region region, Map keyMap, List keyList) throws Exception { if (region == null) { PadoShell.printlnError("Path is null"); return 0; } HashSet keyNameSet = new HashSet(); HashSet valueNameSet = new HashSet(); ArrayList indexList = new ArrayList(keyMap.keySet()); Collections.sort(indexList); Object key = null; Object value = null; // Print keys and values int row = 1; int rowCount = keyMap.size(); for (Iterator iterator = indexList.iterator(); iterator.hasNext(); ) { Object index = iterator.next(); key = keyMap.get(index); value = region.get(key); keyNameSet.add(key.getClass().getName()); if (value != null) { valueNameSet.add(value.getClass().getName()); } printObject(row, "Key", key, true); printObject(row, "Value", value, false); PadoShell.println(""); row++; } PadoShell.println(""); for (Object keyName : keyNameSet) { PadoShell.println("Key Class : " + keyName); } for (Object valueName : valueNameSet) { PadoShell.println("Value Class: " + valueName); } return rowCount; }
/** * Tests that if a <code>CacheLoader</code> for a local region invokes {@link * LoaderHelper#netSearch}, a {@link CacheLoaderException} is thrown. */ public void testLocalLoaderNetSearch() throws CacheException { assertEquals(Scope.LOCAL, getRegionAttributes().getScope()); final String name = this.getUniqueName(); final Object key = this.getUniqueName(); TestCacheLoader loader = new TestCacheLoader() { public Object load2(LoaderHelper helper) throws CacheLoaderException { try { helper.netSearch(true); } catch (TimeoutException ex) { fail("Why did I timeout?", ex); } return null; } }; AttributesFactory factory = new AttributesFactory(getRegionAttributes()); factory.setCacheLoader(loader); Region region = createRegion(name, factory.create()); assertEquals(Scope.LOCAL, region.getAttributes().getScope()); try { region.get(key); fail("Should have thrown a CacheLoaderException"); } catch (CacheLoaderException ex) { String expected = com.gemstone.gemfire.internal.cache.LoaderHelperImpl.NET_SEARCH_LOCAL.toLocalizedString(); String message = ex.getMessage(); assertTrue("Unexpected message \"" + message + "\"", message.indexOf(expected) != -1); } }
/** * 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); }
/** * *********** private static String verifyPdxInstanceToJSONConversion(Region region) { * System.out.println("START Execute REST-APIs testcases..."); System.out.println("Step:1 * PdxInstance ---------> JSON conversion"); Cache c = CacheFactory.getAnyInstance(); region = * c.getRegion("primitiveKVStore"); * * <p>//PUT TestObjectForPdxFormatter testObject = new TestObjectForPdxFormatter(); * testObject.defaultInitialization(); * * <p>// ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new * SimpleDateFormat("MM/dd/yyyy")); * mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String jsonString = * null; try { jsonString = mapper.writeValueAsString(testObject); } catch * (JsonProcessingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } * * <p>//CollectionType mapCollectionType = mapper.getTypeFactory().defaultInstance() * constructCollectionType(List.class, Map.class); //TestObjectForPdxFormatter newObj = * mapper.readValue(jsonStr, clazz); //Object newObj = clazz.newInstance(); //String jsonStr = * JSONFormatter.toJSON(this); * * <p>System.out.println("PdxInstance converted to JSON is :: " + jsonString); //JavaType type = * mapper.getTypeFactory().constructType(newObj.getClass()); * * <p>try { TestObjectForPdxFormatter newObj = mapper.readValue(jsonString, * TestObjectForPdxFormatter.class); * * <p>System.out.println("JSON to Object Conversion successful"); } catch (JsonParseException e1) * { // TODO Auto-generated catch block e1.printStackTrace(); } catch (JsonMappingException e1) { * // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO * Auto-generated catch block e1.printStackTrace(); } * * <p>System.out.println("TEST END"); // * * <p>System.out.println("-----------------------------------JAVA CLIENT PUT-14 START * -----------------------------------------------------"); region.put("14", testObject); * System.out.println("-----------------------------------JAVA CLIENT PUT-14 END * ------------------------------------------------------"); System.out.println(); * * <p>System.out.println("-----------------------------------JAVA CLIENT GET('13'), this was put * by peer cache - START -----------------------------------------------------"); Object clientObj * = (Object)region.get("13"); if (clientObj instanceof PdxInstance) { PdxInstance pi = * (PdxInstance)clientObj; String clazzName = pi.getClassName(); System.out.println("CLAZZ_1 : " + * clazzName); }else { System.out.println("clientObj is not PdxInstance, * clientObj.getClass().getName() : " + clientObj.getClass().getName()); } * System.out.println("-----------------------------------JAVA CLIENT GET('13') - END * ------------------------------------------------------"); System.out.println(); * * <p>System.out.println("-----------------------------------JAVA CLIENT GET('14'), this was put * by Java client - START -----------------------------------------------------"); Object * clientObj2 = (Object)region.get("14"); if (clientObj2 instanceof PdxInstance) { PdxInstance pi * = (PdxInstance)clientObj2; String clazzName = pi.getClassName(); System.out.println("CLAZZ_2 : * " + clazzName); }else { System.out.println("clientObj2 is not PdxInstance, * clientObj2.getClass().getName() : " + clientObj2.getClass().getName()); } * System.out.println("-----------------------------------JAVA CLIENT GET('14') - END * ------------------------------------------------------"); System.out.println(); * * <p>//Put PdxInstance System.out.println("-----------------------------------JAVA CLIENT * PDXInstance Put('15') - START -----------------------------------------"); //PdxInstanceFactory * pif = PdxInstanceFactoryImpl.newCreator("com.gemstone.gemfire.pdx.TestObjectForPdxFormatter", * true); PdxInstanceFactory pif = * c.createPdxInstanceFactory("com.gemstone.gemfire.pdx.TestObjectForPdxFormatter"); * * <p>pif.writeLong("p_long", 1000000000000L); pif.writeFloat("p_float",100.001f); * pif.writeDouble("p_double", 100000.100000); pif.writeBoolean("p_bool", true); * pif.writeByte("p_byte", (byte)10); pif.writeInt("p_int", 1000); pif.writeShort("p_short", * (short)100); * * <p>PdxInstance pInst = pif.create(); region.put("15", pInst); * System.out.println("-----------------------------------JAVA CLIENT PDXInstance Put('15') - END * -----------------------------------------"); System.out.println(); * * <p>//GET System.out.println("-----------------------------------JAVA CLIENT PDXInstance * Get('15') - START -----------------------------------------"); Object result = * (Object)region.get("15"); if (result instanceof PdxInstance) { //Output: result is instance of * PdxInstance PdxInstance pi = (PdxInstance)result; String clazzName = pi.getClassName(); * System.out.println("CLAZZ_2 : " + clazzName); //1. check for getObject() behaviour try{ Object * obj = pi.getObject(); * * <p>if(obj instanceof TestObjectForPdxFormatter){ //OutPut: piAsObject instanceof * TestObjectForPdxFormatter System.out.println(" piAsObject instanceof TestObjectForPdxFormatter * "); }else System.out.println(" piAsObject NOT TestObjectForPdxFormatter "); * }catch(PdxSerializationException ex){ System.out.println("Error " + ex.getMessage()); * ex.printStackTrace(); } //2. introspectPdxInstanceFields //introspectPdxInstanceFields(pi); * * <p>//3. Verify pi to json conversion String json = JSONFormatter.toJSON(pi); * System.out.println("JSON Result " + json ); return json; } else { try { * System.out.println("Result not a pdxInstance result.getClass().getName():: " + * result.getClass().getName()); }catch(PdxFieldTypeMismatchException e){ * System.out.println("Error PdxFieldTypeMismatchException : " + e.getMessage()); } } * * <p>System.out.println("-----------------------------------JAVA CLIENT PDXInstance Get('15') - * END -----------------------------------------"); System.out.println(); * * <p>//TODO:: REST CLEINT Does PUT on key 16 * * <p>//GET System.out.println("-----------------------------------REST CLIENT PDXInstance * Get('16') - START -----------------------------------------"); Object result2 = * (Object)region.get("16"); if (result2 instanceof PdxInstance) { //Output: result is instance of * PdxInstance PdxInstance pi = (PdxInstance)result2; String clazzName = pi.getClassName(); * System.out.println("CLAZZ_3 : " + clazzName); //1. check for getObject() behaviour try{ Object * obj = pi.getObject(); * * <p>if(obj instanceof TestObjectForPdxFormatter){ //OutPut: piAsObject instanceof * TestObjectForPdxFormatter System.out.println(" piAsObject instanceof TestObjectForPdxFormatter * "); }else System.out.println(" piAsObject NOT TestObjectForPdxFormatter "); * }catch(PdxFieldTypeMismatchException e){ System.out.println("Error * PdxFieldTypeMismatchException : " + e.getMessage()); }catch(PdxSerializationException ex){ * System.out.println("Error " + ex.getMessage()); ex.printStackTrace(); } //2. * introspectPdxInstanceFields //introspectPdxInstanceFields(pi); * * <p>//3. Verify pi to json conversion String json = JSONFormatter.toJSON(pi); * System.out.println("JSON Result " + json ); return json; } else { System.out.println("Result * not a pdxInstance result2.getClass().getName():: " + result2.getClass().getName()); } * * <p>System.out.println("-----------------------------------JAVA CLIENT PDXInstance Get('15') - * END -----------------------------------------"); System.out.println(); return null; } * * <p>private static final String ORDER2_AS_JSON = "{" + "\"@type\": * \"com.gemstone.gemfire.web.rest.domain.Order\"," + "\"purchaseOrderNo\": 112," + * "\"customerId\": 102," + "\"description\": \"Purchase order for company - B\"," + * "\"orderDate\": \"02/10/2014\"," + "\"deliveryDate\": \"02/20/2014\"," + "\"contact\": \"John * Blum\"," + "\"email\": \"[email protected]\"," + "\"phone\": \"01-2048096\"," + * "\"totalPrice\": 225," + "\"items\":" + "[" + "{" + "\"itemNo\": 1," + "\"description\": * \"Product-3\"," + "\"quantity\": 6," + "\"unitPrice\": 20," + "\"totalPrice\": 120" + "}," + * "{" + "\"itemNo\": 2," + "\"description\": \"Product-4\"," + "\"quantity\": 10," + * "\"unitPrice\": 10.5," + "\"totalPrice\": 105" + "}" + "]" + "}"; * * <p>private static HttpHeaders setAcceptAndContentTypeHeaders() { List<MediaType> * acceptableMediaTypes = new ArrayList<MediaType>(); * acceptableMediaTypes.add(MediaType.APPLICATION_JSON); * * <p>HttpHeaders headers = new HttpHeaders(); headers.setAccept(acceptableMediaTypes); * headers.setContentType(MediaType.APPLICATION_JSON); return headers; } * * <p>private static void ValidateTestCase(){ * * <p>Cache c = CacheFactory.getAnyInstance(); Region region = c.getRegion("orders"); * * <p>//Rest put on key:2 HttpHeaders headers = setAcceptAndContentTypeHeaders(); * HttpEntity<Object> entity = new HttpEntity<Object>(ORDER2_AS_JSON, headers); * * <p>ResponseEntity<String> result = RestTestUtils.getRestTemplate().exchange( * RestTestUtils.GEMFIRE_REST_API_WEB_SERVICE_URL + "/orders/2", HttpMethod.PUT, entity, * String.class); * * <p>//PUT Item it = new Item(); it.setItemNo(1L); it.setDescription("Free Item -- testing"); * it.setQuantity(10); it.setTotalPrice(250.10f); it.setUnitPrice(25.01f); * * <p>Object obj = region.get("2"); if(obj instanceof PdxInstance) { PdxInstance pi = * (PdxInstance)obj; Order receivedOrder = (Order)pi.getObject(); * * <p>//System.out.println("Original order size:: " + receivedOrder.getItems().size()); * //receivedOrder.addItem(it); //System.out.println("Updated order size:: " + * receivedOrder.getItems().size()); region.put("3", receivedOrder); } * * <p>//GET Object updResult = region.get("3"); if (updResult instanceof PdxInstance) { * System.out.println("updResult is instance of PdxInstance...!!"); * * <p>System.out.println("Step:1 PdxInstance ---------> JSON conversion"); PdxInstance pi = * (PdxInstance)updResult; * * <p>try{ * * <p>Object piObj = pi.getObject(); if(piObj instanceof Order){ System.out.println("step-1. * piAsObject instanceof Order "); }else System.out.println("step-1: piAsObject NOT Order "); * * <p>}catch(PdxSerializationException ex){ System.out.println("Error " + ex.getMessage()); * ex.printStackTrace(); } } * * <p>System.out.println("successfully Put TestObjectForPdxFormatter into the cache"); * * <p>///System.out.println("Nilkanth : TestCase : Validate Java-->JSON-->PdxInstance --> Java * Mapping"); * * <p>System.out.println("START Execute REST-APIs testcases..."); System.out.println("Step:1 * PdxInstance ---------> JSON conversion"); //Cache c = CacheFactory.getAnyInstance(); region = * c.getRegion("primitiveKVStore"); * * <p>TestObjectForPdxFormatter actualTestObject = new TestObjectForPdxFormatter(); * actualTestObject.defaultInitialization(); ObjectMapper objectMapper = new ObjectMapper(); * objectMapper.setDateFormat(new SimpleDateFormat("MM/dd/yyyy")); * objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); try { //1. * get the json from the object using Jackosn Object Mapper String json = * objectMapper.writeValueAsString(actualTestObject); String jsonWithClassType = * actualTestObject.addClassTypeToJson(json); System.out.println("Nilkanth : jsonWithClassType:: " * + jsonWithClassType); * * <p>//2. convert json into the PdxInstance and put it into the region PdxInstance pi = * JSONFormatter.fromJSON(jsonWithClassType); region.put("201", pi); * * <p>//3. get the value on key "201" and validate PdxInstance.getObject() API. Object * receivedObject = region.get("201"); if (receivedObject instanceof PdxInstance){ PdxInstance * receivedPdxInstance = (PdxInstance)receivedObject; * * <p>//4. get the actual testObject from the pdxInstance and compare it with actualTestObject * Object getObj = receivedPdxInstance.getObject(); if(getObj instanceof * TestObjectForPdxFormatter){ TestObjectForPdxFormatter receivedTestObject = * (TestObjectForPdxFormatter)getObj; * * <p>boolean isEqual = actualTestObject.equals(receivedTestObject); Assert.assertTrue(isEqual, * "actualTestObject and receivedTestObject should be equal"); }else { System.out.println("Error: * getObj is expected to be an instance of TestObjectForPdxFormatter"); } }else { * System.out.println("ERROR:: receivedObject is expected to be of type PdxInstance"); } * * <p>} catch (JsonProcessingException e) { System.out.println("Error:JsonProcessingException: * error encountered while converting JSON from Java object: " + e.getMessage()); * * <p>} catch (JSONException e) { System.out.println("Error:JSONException: error encountered while * adding @type classType into Json: " + e.getMessage()); } } */ public static void main(String[] args) { /*CacheFactory cf = new CacheFactory(); Cache cache = cf.create(); RegionFactory rf = cache.createRegionFactory(); Region region = rf.create("Test1");*/ ClientCacheFactory cf = new ClientCacheFactory() .addPoolServer( "localhost", 40405); /// *.addPoolLocator("10.112.204.2" /*pnq-npatel1*//*"localhost"*/, // 11240)*/; // ClientCache cache = cf.setPdxReadSerialized(true).create(); ClientCache cache = cf.create(); ClientRegionFactory rf = cache.createClientRegionFactory(ClientRegionShortcut.PROXY); Region region = rf.create("People"); // Region region1 = rf.create("orders"); Person actualObj = null; Object obj = region.get("1"); if (obj instanceof PdxInstance) { System.out.println("Obj is PdxInstance"); PdxInstance pi = (PdxInstance) obj; Object obj2 = pi.getObject(); if (obj2 instanceof Person) { actualObj = (Person) obj2; System.out.println("Received Person :" + actualObj.toString()); } else { System.out.println("Error: obj2 is expected to be of type Person"); } } else { System.out.println("Error: obj is expected to be of type PdxInstance"); } // update the received object and put it in cache if (actualObj != null) { actualObj.setFirstName("Nilkanth_updated"); actualObj.setLastName("Patel_updated"); region.put("1", actualObj); } // Add/putAll set of person objects final Person person2 = new Person( 102L, "Sachin", "Ramesh", "Tendulkar", DateTimeUtils.createDate(1975, Calendar.DECEMBER, 14), Gender.MALE); final Person person3 = new Person( 103L, "Saurabh", "Baburav", "Ganguly", DateTimeUtils.createDate(1972, Calendar.AUGUST, 29), Gender.MALE); final Person person4 = new Person( 104L, "Rahul", "subrymanyam", "Dravid", DateTimeUtils.createDate(1979, Calendar.MARCH, 17), Gender.MALE); final Person person5 = new Person( 105L, "Jhulan", "Chidambaram", "Goswami", DateTimeUtils.createDate(1983, Calendar.NOVEMBER, 25), Gender.FEMALE); final Person person6 = new Person( 101L, "Rahul", "Rajiv", "Gndhi", DateTimeUtils.createDate(1970, Calendar.MAY, 14), Gender.MALE); final Person person7 = new Person( 102L, "Narendra", "Damodar", "Modi", DateTimeUtils.createDate(1945, Calendar.DECEMBER, 24), Gender.MALE); final Person person8 = new Person( 103L, "Atal", "Bihari", "Vajpayee", DateTimeUtils.createDate(1920, Calendar.AUGUST, 9), Gender.MALE); final Person person9 = new Person( 104L, "Soniya", "Rajiv", "Gandhi", DateTimeUtils.createDate(1929, Calendar.MARCH, 27), Gender.FEMALE); final Person person10 = new Person( 104L, "Priyanka", "Robert", "Gandhi", DateTimeUtils.createDate(1973, Calendar.APRIL, 15), Gender.FEMALE); final Person person11 = new Person( 104L, "Murali", "Manohar", "Joshi", DateTimeUtils.createDate(1923, Calendar.APRIL, 25), Gender.MALE); final Person person12 = new Person( 104L, "Lalkrishna", "Parmhansh", "Advani", DateTimeUtils.createDate(1910, Calendar.JANUARY, 01), Gender.MALE); final Person person13 = new Person( 104L, "Shushma", "kumari", "Swaraj", DateTimeUtils.createDate(1943, Calendar.AUGUST, 10), Gender.FEMALE); final Person person14 = new Person( 104L, "Arun", "raman", "jetly", DateTimeUtils.createDate(1942, Calendar.OCTOBER, 27), Gender.MALE); final Person person15 = new Person( 104L, "Amit", "kumar", "shah", DateTimeUtils.createDate(1958, Calendar.DECEMBER, 21), Gender.MALE); final Person person16 = new Person( 104L, "Shila", "kumari", "Dixit", DateTimeUtils.createDate(1927, Calendar.FEBRUARY, 15), Gender.FEMALE); Map<String, Object> userMap = new HashMap<String, Object>(); userMap.put("2", person6); userMap.put("3", person6); userMap.put("4", person6); userMap.put("5", person6); userMap.put("6", person6); userMap.put("7", person7); userMap.put("8", person8); userMap.put("9", person9); userMap.put("10", person10); userMap.put("11", person11); userMap.put("12", person12); userMap.put("13", person13); userMap.put("14", person14); userMap.put("15", person15); userMap.put("16", person16); region.putAll(userMap); System.out.println("successfully Put set of Person objects into the cache"); region.invalidate("2"); region.invalidate("3"); region.invalidate("4"); region.invalidate("5"); region.invalidate("6"); region.invalidate("7"); region.invalidate("8"); region.remove("9"); region.remove("10"); /* Object obj = region.get("13"); if(obj instanceof PdxInstance){ System.out.println("Obj is PdxInstance"); }else { System.out.println("Obj isNOT PdxInstance"); } */ // verifyPdxInstanceToJSONConversion(region); // ValidateTestCase(); /* RegionOps regionOps = new RegionOps(); regionOps.getRESTClientObject(region); //2.Test cases with PortfolioPdx of type PdxSerialization //create PortfolioPdx object PortfolioPdx portPdx = new PortfolioPdx(10); System.out.println("portPdx.toString() = " + portPdx.toString()); ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(new SimpleDateFormat("MM/dd/yyyy")); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String jsonString = null; try { jsonString = mapper.writeValueAsString(portPdx); } catch (JsonProcessingException e) { System.out.println("Error: JsonProcessingException caught"); // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Success: cust1 as JSON " + jsonString); //put the object into cache. region.put("11", portPdx); System.out.println("successfully Put PortfolioPdx into the cache"); Boolean b = new Boolean(false); Byte by = new Byte((byte)11); Short sh = new Short((short)101); Integer in = new Integer(1001); Long lo = new Long(987654321234567L); BigInteger bi = new BigInteger("12345678910"); Float fl = new Float(789.456f); BigDecimal bd = new BigDecimal(8866333); Double doub = new Double(123456.9876d); String str = new String("Nilkanth Patel"); */ /* TestObjectForPdxFormatter testObject = new TestObjectForPdxFormatter(true, (byte)10, (short)100, 1000, 1234567898765432L, 123.456f, 98765.12345d, b, by, sh, in, lo, bi ,fl, bd ,doub, str ); */ /* TestObjectForPdxFormatter testObject = new TestObjectForPdxFormatter(); testObject.defaultInitialization(); System.out.println("testObject.toString() = " + testObject.toString()); jsonString = null; try { jsonString = mapper.writeValueAsString(testObject); } catch (JsonProcessingException e) { System.out.println("Error: JsonProcessingException caught"); // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Success: testObject as JSON " + jsonString); //put the object into cache. region.put("13", testObject); */ /* Object result = (Object)region.get("13"); if (result instanceof PdxInstance) { System.out.println("result is instance of PdxInstance...!!"); System.out.println("Step:1 PdxInstance to JSON conversion"); PdxInstance pi = (PdxInstance)result; String json = JSONFormatter.toJSON(pi); System.out.println("JSON Result " + json ); System.out.println("Step:2 JSON to PdxInstance conversion"); PdxInstance pInstance = JSONFormatter.fromJSON(json); Object piAsObject = pInstance.getObject(); if(piAsObject instanceof TestObjectForPdxFormatter){ System.out.println("piAsObject instanceof TestObjectForPdxFormatter "); }else { System.out.println("piAsObject NOT of type TestObjectForPdxFormatter"); } }else { System.out.println("Error: result not PDXInstance type"); } */ // // regionOps.putJavaClientObject(region); /*JSONObject json = new JSONObject(); String key = "key"; Object value = "501"; try { json.put(key, value); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } //String json = "{ " + "\"" + key.toString() + "\"" + ":" + value + "}"; //System.out.println(" JSON :: " + json); System.out.println("JSON :: " + json.toString()); */ // 1.START:: Test cases with Person of type DataSerializable // put and then get Person object /** * ************************************* Person p1 = new Person(10l); p1.setFirstName("Diya"); * p1.setMiddleName("Sandipkumar"); p1.setLastName("Patel"); p1.setGender(Gender.FEMALE); * p1.setBirthDate(DateTimeUtils.createDate(2009, Calendar.OCTOBER, 3)); * * <p>//put region.put("10", p1); System.out.println("person1.toString() = " + p1.toString()); * * <p>//get Person person = (Person)region.get("10"); if(person instanceof Person){ * System.out.println("Instance of Person"); System.out.println("firstname = " + * person.getFirstName() + " Lastname = " + person.getLastName()); }else{ * System.out.println("NOT Instance of Person"); } //END:: Test cases with Person of type * DataSerializable * * <p>//PdxInstance pi = (PdxInstance) cache.createPdxInstanceFactory("").writeString("key1", * "key2").create(); //PPerson person = new PPerson(1, "Sachin", "Tendulkar"); * //PdxInstanceFactory pdxFact = PdxInstanceFactoryImpl.newCreator(name, expectDomainClass) * * <p>//2.Test cases with PortfolioPdx of type PdxSerialization //create PortfolioPdx object * PortfolioPdx portPdx = new PortfolioPdx(10); System.out.println("portPdx.toString() = " + * portPdx.toString()); * * <p>//put the object into cache. region.put("11", portPdx); * *************************************** */ // // put/get code with serialized read behavior // put is done as normal // region.put("11", portPdx); // get checks Object type and handles each appropriately // Object myObject = region.get("11"); /* if (myObject instanceof PdxInstance) { // get returned PdxInstance instead of domain object PdxInstance myPdxInstance = (PdxInstance)myObject; String myJson = JSONFormatter.toJSON(myPdxInstance); System.out.println(" my JSOn :: " + myJson); // PdxInstance.getField deserializes the field, but not the object String fieldValue = (String) myPdxInstance.getField("pkid"); System.out.println("RESULT ---> " + fieldValue); // Update a field and put it back into the cache // without deserializing the entire object //WritablePdxInstance myWritablePdxI = myPdxInstance.createWriter(); //myWritablePdxI.setField("fieldName", fieldValue); //region.put(key, myWritablePdxI); // Deserialize the entire object if needed, from the PdxInstance //DomainClass myPdxObject = (DomainClass); // } else if (myObject instanceof PdxSerializable) { System.out.println("Object is PDXSerializable..."); } else { System.out.println("ERROR ----> Object is not PDXInstance NOR PDXSerializable "); } */ System.out.println("TEST Ended Successfully....!!!!"); /* final Set<Region<?, ?>> regionSet = cache.rootRegions(); System.out.println("Following are the regions found in the Server"); for(Region<?, ?> r : regionSet){ System.out.println(r.getName()); } GetRegions myFunction = new GetRegions(); //PoolImpl p = (PoolImpl) PoolManager.createFactory().addServer("localhost", 12480); FunctionService.registerFunction(myFunction); //Map<String, Function> myMap = FunctionService.getRegisteredFunctions(); //System.out.println("Total size for registered functions ::: " + myMap.size()); Execution exe = FunctionService.onServer(cache.getDefaultPool()); System.out.println("Executing the function"); ResultCollector<?, ?> rc = exe.execute("GetRegions"); ArrayList result = (ArrayList)rc.getResult(); List<String> list = (List<String>)result.get(0); System.out.println(" Region at the index 0 is " + list.get(0)); System.out.println(" Region at the index 1 is " + list.get(1)); System.out.println("Function executed remotelly successfully , Size is = " + result.size()); //ResultCollector rc = exe.execute(new PutKeyFunction() { GemFireCacheImpl.getExisting(null).rootRegions()}); //Set result = (Set) rc.getResult(); //System.out.println("Function executed remotelly successfully , Size is = " + result.size()); */ /*Execution execution = FunctionService.onRegion(exampleRegion).withFilter( keysForGet).withArgs(Boolean.TRUE).withCollector( new MyArrayListResultCollector()); ResultCollector rc = execution.execute(function); */ /* Person p = new Person(); p.setId(101L); p.setFirstName("Nilkanth"); p.setLastName("Patel"); p.setMiddleName("Hirabhai"); p.setBirthDate(DateTimeUtils.createDate(1983, Calendar.JUNE, 1)); p.setGender(Gender.MALE); region.put(1,p); //////////////////////////// p.setId(102L); p.setFirstName("Hemant"); p.setLastName("Bhanavat"); p.setMiddleName("Unknown"); p.setBirthDate(DateTimeUtils.createDate(1980, Calendar.JANUARY, 1)); p.setGender(Gender.MALE); region.put(2,p); ////////////////////////// p.setId(103L); p.setFirstName("TUshar"); p.setLastName("Khairnar"); p.setMiddleName("Unknown"); p.setBirthDate(DateTimeUtils.createDate(1983, Calendar.JUNE, 15)); p.setGender(Gender.MALE); region.put(3,p); region.put(2,2); region.put(3,3); region.put(4,4); region.put(5,5); */ // System.out.println("Hello!!!!!"); /*System.out.println(region.get(1)); System.out.println(region.get(2)); System.out.println(region.get(3)); System.out.println(region.get(4)); System.out.println(region.get(5)); */ }
/** * Verify the contents of the region, taking into account the keys that were destroyed, * invalidated, etc (as specified in keyIntervals) Throw an error of any problems are detected. * This must be called repeatedly by the same thread until StopSchedulingTaskOnClientOrder is * thrown. */ public void verifyRegionContents() { final long LOG_INTERVAL_MILLIS = 10000; // we already completed this check once; we can't do it again without reinitializing the // verify state variables if (verifyRegionContentsCompleted) { throw new TestException( "Test configuration problem; already verified region contents, " + "cannot call this task again without resetting batch variables"); } // iterate keys long lastLogTime = System.currentTimeMillis(); long minTaskGranularitySec = TestConfig.tab().longAt(TestHelperPrms.minTaskGranularitySec); long minTaskGranularityMS = minTaskGranularitySec * TestHelper.SEC_MILLI_FACTOR; long startTime = System.currentTimeMillis(); long size = aRegion.size(); boolean first = true; int numKeysToCheck = keyIntervals.getNumKeys() + numNewKeys; while (verifyRegionContentsIndex < numKeysToCheck) { verifyRegionContentsIndex++; if (first) { Log.getLogWriter() .info( "In verifyRegionContents, region has " + size + " keys; starting verify at verifyRegionContentsIndex " + verifyRegionContentsIndex + "; verifying key names with indexes through (and including) " + numKeysToCheck); first = false; } // check region size the first time through the loop to avoid it being called // multiple times when this is batched if (verifyRegionContentsIndex == 1) { if (totalNumKeys != size) { String tmpStr = "Expected region size to be " + totalNumKeys + ", but it is size " + size; Log.getLogWriter().info(tmpStr); verifyRegionContentsErrStr.append(tmpStr + "\n"); } } Object key = NameFactory.getObjectNameForCounter(verifyRegionContentsIndex); try { if (((verifyRegionContentsIndex >= keyIntervals.getFirstKey(KeyIntervals.NONE)) && (verifyRegionContentsIndex <= keyIntervals.getLastKey(KeyIntervals.NONE))) || ((verifyRegionContentsIndex >= keyIntervals.getFirstKey(KeyIntervals.GET)) && (verifyRegionContentsIndex <= keyIntervals.getLastKey(KeyIntervals.GET)))) { // this key was untouched after its creation checkContainsKey(key, true, "key was untouched"); checkContainsValueForKey(key, true, "key was untouched"); Object value = aRegion.get(key); checkValue(key, value); } else if ((verifyRegionContentsIndex >= keyIntervals.getFirstKey(KeyIntervals.INVALIDATE)) && (verifyRegionContentsIndex <= keyIntervals.getLastKey(KeyIntervals.INVALIDATE))) { checkContainsKey(key, true, "key was invalidated"); checkContainsValueForKey(key, false, "key was invalidated"); } else if ((verifyRegionContentsIndex >= keyIntervals.getFirstKey(KeyIntervals.LOCAL_INVALIDATE)) && (verifyRegionContentsIndex <= keyIntervals.getLastKey(KeyIntervals.LOCAL_INVALIDATE))) { // this key was locally invalidated checkContainsKey(key, true, "key was locally invalidated"); checkContainsValueForKey(key, true, "key was locally invalidated"); Object value = aRegion.get(key); checkValue(key, value); } else if ((verifyRegionContentsIndex >= keyIntervals.getFirstKey(KeyIntervals.DESTROY)) && (verifyRegionContentsIndex <= keyIntervals.getLastKey(KeyIntervals.DESTROY))) { // this key was destroyed checkContainsKey(key, false, "key was destroyed"); checkContainsValueForKey(key, false, "key was destroyed"); } else if ((verifyRegionContentsIndex >= keyIntervals.getFirstKey(KeyIntervals.LOCAL_DESTROY)) && (verifyRegionContentsIndex <= keyIntervals.getLastKey(KeyIntervals.LOCAL_DESTROY))) { // this key was locally destroyed checkContainsKey(key, true, "key was locally destroyed"); checkContainsValueForKey(key, true, "key was locally destroyed"); Object value = aRegion.get(key); checkValue(key, value); } else if ((verifyRegionContentsIndex >= keyIntervals.getFirstKey(KeyIntervals.UPDATE_EXISTING_KEY)) && (verifyRegionContentsIndex <= keyIntervals.getLastKey(KeyIntervals.UPDATE_EXISTING_KEY))) { // this key was updated checkContainsKey(key, true, "key was updated"); checkContainsValueForKey(key, true, "key was updated"); Object value = aRegion.get(key); checkUpdatedValue(key, value); } else if (verifyRegionContentsIndex > keyIntervals.getNumKeys()) { // key was newly added checkContainsKey(key, true, "key was new"); checkContainsValueForKey(key, true, "key was new"); Object value = aRegion.get(key); checkValue(key, value); } } catch (TestException e) { Log.getLogWriter().info(TestHelper.getStackTrace(e)); verifyRegionContentsErrStr.append(e.getMessage() + "\n"); } if (System.currentTimeMillis() - lastLogTime > LOG_INTERVAL_MILLIS) { Log.getLogWriter() .info("Verified key " + verifyRegionContentsIndex + " out of " + totalNumKeys); lastLogTime = System.currentTimeMillis(); } if (System.currentTimeMillis() - startTime >= minTaskGranularityMS) { Log.getLogWriter() .info( "In HydraTask_verifyRegionContents, returning before completing verify " + "because of task granularity (this task must be batched to complete); last key verified is " + key); return; // task is batched; we are done with this batch } } verifyRegionContentsCompleted = true; if (verifyRegionContentsErrStr.length() > 0) { throw new TestException(verifyRegionContentsErrStr.toString()); } String aStr = "In HydraTask_verifyRegionContents, verified " + verifyRegionContentsIndex + " keys/values"; Log.getLogWriter().info(aStr); throw new StopSchedulingTaskOnClientOrder(aStr); }
/** * check distributed ops that originate in a PROXY are correctly distributed to non-proxy regions. */ private void distributedOps(DataPolicy dp, InterestPolicy ip) throws CacheException { initOtherId(); AttributesFactory af = new AttributesFactory(); af.setDataPolicy(dp); af.setSubscriptionAttributes(new SubscriptionAttributes(ip)); af.setScope(Scope.DISTRIBUTED_ACK); Region r = createRootRegion("ProxyDUnitTest", af.create()); doCreateOtherVm(); r.put("putkey", "putvalue1"); getOtherVm() .invoke( new CacheSerializableRunnable("check put") { public void run2() throws CacheException { Region r = getRootRegion("ProxyDUnitTest"); assertEquals(true, r.containsKey("putkey")); assertEquals("putvalue1", r.getEntry("putkey").getValue()); r.put("putkey", "putvalue2"); } }); assertEquals(false, r.containsKey("putkey")); assertEquals("putvalue2", r.get("putkey")); // netsearch r.invalidate("putkey"); getOtherVm() .invoke( new CacheSerializableRunnable("check invalidate") { public void run2() throws CacheException { Region r = getRootRegion("ProxyDUnitTest"); assertEquals(true, r.containsKey("putkey")); assertEquals(null, r.getEntry("putkey").getValue()); } }); assertEquals(null, r.get("putkey")); // invalid so total miss r.destroy("putkey"); getOtherVm() .invoke( new CacheSerializableRunnable("check destroy") { public void run2() throws CacheException { Region r = getRootRegion("ProxyDUnitTest"); assertEquals(false, r.containsKey("putkey")); } }); assertEquals(null, r.get("putkey")); // total miss r.create("createKey", "createValue1"); getOtherVm() .invoke( new CacheSerializableRunnable("check create") { public void run2() throws CacheException { Region r = getRootRegion("ProxyDUnitTest"); assertEquals(true, r.containsKey("createKey")); assertEquals("createValue1", r.getEntry("createKey").getValue()); } }); { Map m = new HashMap(); m.put("putAllKey1", "putAllValue1"); m.put("putAllKey2", "putAllValue2"); r.putAll(m, "putAllCallback"); } getOtherVm() .invoke( new CacheSerializableRunnable("check putAll") { public void run2() throws CacheException { Region r = getRootRegion("ProxyDUnitTest"); assertEquals(true, r.containsKey("putAllKey1")); assertEquals("putAllValue1", r.getEntry("putAllKey1").getValue()); assertEquals(true, r.containsKey("putAllKey2")); assertEquals("putAllValue2", r.getEntry("putAllKey2").getValue()); } }); r.clear(); getOtherVm() .invoke( new CacheSerializableRunnable("check clear") { public void run2() throws CacheException { Region r = getRootRegion("ProxyDUnitTest"); assertEquals(0, r.size()); } }); getOtherVm() .invoke( new CacheSerializableRunnable("install CacheWriter") { public void run2() throws CacheException { Region r = getRootRegion("ProxyDUnitTest"); AttributesMutator am = r.getAttributesMutator(); CacheWriter cw = new CacheWriterAdapter() { public void beforeCreate(EntryEvent event) throws CacheWriterException { throw new CacheWriterException("expected"); } }; am.setCacheWriter(cw); } }); try { r.put("putkey", "putvalue"); fail("expected CacheWriterException"); } catch (CacheWriterException expected) { } getOtherVm() .invoke( new CacheSerializableRunnable("check clear") { public void run2() throws CacheException { Region r = getRootRegion("ProxyDUnitTest"); assertEquals(0, r.size()); } }); assertEquals(null, r.get("loadkey")); // total miss getOtherVm() .invoke( new CacheSerializableRunnable("install CacheLoader") { public void run2() throws CacheException { Region r = getRootRegion("ProxyDUnitTest"); AttributesMutator am = r.getAttributesMutator(); am.setCacheWriter(null); // clear csche writer CacheLoader cl = new CacheLoader() { public Object load(LoaderHelper helper) throws CacheLoaderException { if (helper.getKey().equals("loadkey")) { return "loadvalue"; } else if (helper.getKey().equals("loadexception")) { throw new CacheLoaderException("expected"); } else { return null; } } public void close() {} }; am.setCacheLoader(cl); } }); assertEquals("loadvalue", r.get("loadkey")); // net load assertEquals(null, r.get("foobar")); // total miss try { r.get("loadexception"); fail("expected CacheLoaderException"); } catch (CacheLoaderException expected) { } r.destroyRegion(); getOtherVm() .invoke( new CacheSerializableRunnable("check clear") { public void run2() throws CacheException { Region r = getRootRegion("ProxyDUnitTest"); assertEquals(null, r); } }); }
@SuppressWarnings({"rawtypes", "unchecked"}) private void doRegionTest(final RegionShortcut rs, final String rName, boolean compressed) { boolean isPersistent = rs == RegionShortcut.LOCAL_PERSISTENT || rs == RegionShortcut.REPLICATE_PERSISTENT || rs == RegionShortcut.PARTITION_PERSISTENT; GemFireCacheImpl gfc = createCache(isPersistent); Region r = null; try { gfc.setCopyOnRead(true); final MemoryAllocator ma = gfc.getOffHeapStore(); assertNotNull(ma); assertEquals(0, ma.getUsedMemory()); Compressor compressor = null; if (compressed) { compressor = SnappyCompressor.getDefaultInstance(); } r = gfc.createRegionFactory(rs).setOffHeap(true).setCompressor(compressor).create(rName); assertEquals(true, r.isEmpty()); assertEquals(0, ma.getUsedMemory()); Object data = new Integer(123456789); r.put("key1", data); // System.out.println("After put of Integer value off heap used memory=" + // ma.getUsedMemory()); assertTrue(ma.getUsedMemory() == 0); assertEquals(data, r.get("key1")); r.invalidate("key1"); assertEquals(0, ma.getUsedMemory()); r.put("key1", data); assertTrue(ma.getUsedMemory() == 0); long usedBeforeUpdate = ma.getUsedMemory(); r.put("key1", data); assertEquals(usedBeforeUpdate, ma.getUsedMemory()); assertEquals(data, r.get("key1")); r.destroy("key1"); assertEquals(0, ma.getUsedMemory()); data = new Long(0x007FFFFFL); r.put("key1", data); if (!compressed) { assertTrue(ma.getUsedMemory() == 0); } assertEquals(data, r.get("key1")); data = new Long(0xFF8000000L); r.put("key1", data); if (!compressed) { assertTrue(ma.getUsedMemory() == 0); } assertEquals(data, r.get("key1")); // now lets set data to something that will be stored offheap data = new Long(Long.MAX_VALUE); r.put("key1", data); assertEquals(data, r.get("key1")); // System.out.println("After put of Integer value off heap used memory=" + // ma.getUsedMemory()); assertTrue(ma.getUsedMemory() > 0); data = new Long(Long.MIN_VALUE); r.put("key1", data); assertEquals(data, r.get("key1")); // System.out.println("After put of Integer value off heap used memory=" + // ma.getUsedMemory()); assertTrue(ma.getUsedMemory() > 0); r.invalidate("key1"); assertEquals(0, ma.getUsedMemory()); r.put("key1", data); assertTrue(ma.getUsedMemory() > 0); usedBeforeUpdate = ma.getUsedMemory(); r.put("key1", data); assertEquals(usedBeforeUpdate, ma.getUsedMemory()); assertEquals(data, r.get("key1")); r.destroy("key1"); assertEquals(0, ma.getUsedMemory()); // confirm that byte[] do use off heap { byte[] originalBytes = new byte[1024]; Object oldV = r.put("byteArray", originalBytes); long startUsedMemory = ma.getUsedMemory(); assertEquals(null, oldV); byte[] readBytes = (byte[]) r.get("byteArray"); if (originalBytes == readBytes) { fail("Expected different byte[] identity"); } if (!Arrays.equals(readBytes, originalBytes)) { fail("Expected byte array contents to be equal"); } assertEquals(startUsedMemory, ma.getUsedMemory()); oldV = r.put("byteArray", originalBytes); if (!compressed) { assertEquals(null, oldV); // we default to old value being null for offheap } assertEquals(startUsedMemory, ma.getUsedMemory()); readBytes = (byte[]) r.putIfAbsent("byteArray", originalBytes); if (originalBytes == readBytes) { fail("Expected different byte[] identity"); } if (!Arrays.equals(readBytes, originalBytes)) { fail("Expected byte array contents to be equal"); } assertEquals(startUsedMemory, ma.getUsedMemory()); if (!r.replace("byteArray", readBytes, originalBytes)) { fail("Expected replace to happen"); } assertEquals(startUsedMemory, ma.getUsedMemory()); byte[] otherBytes = new byte[1024]; otherBytes[1023] = 1; if (r.replace("byteArray", otherBytes, originalBytes)) { fail("Expected replace to not happen"); } if (r.replace("byteArray", "bogus string", originalBytes)) { fail("Expected replace to not happen"); } if (r.remove("byteArray", "bogus string")) { fail("Expected remove to not happen"); } assertEquals(startUsedMemory, ma.getUsedMemory()); if (!r.remove("byteArray", originalBytes)) { fail("Expected remove to happen"); } assertEquals(0, ma.getUsedMemory()); oldV = r.putIfAbsent("byteArray", "string value"); assertEquals(null, oldV); assertEquals("string value", r.get("byteArray")); if (r.replace("byteArray", "string valuE", originalBytes)) { fail("Expected replace to not happen"); } if (!r.replace("byteArray", "string value", originalBytes)) { fail("Expected replace to happen"); } oldV = r.destroy("byteArray"); // we default to old value being null for offheap if (!compressed) { assertEquals(null, oldV); } MyCacheListener listener = new MyCacheListener(); r.getAttributesMutator().addCacheListener(listener); try { Object valueToReplace = "string value1"; r.put("byteArray", valueToReplace); assertEquals(null, listener.ohOldValue); if (!compressed) { assertEquals("string value1", listener.ohNewValue.getDeserializedForReading()); valueToReplace = listener.ohNewValue; } if (!r.replace("byteArray", valueToReplace, "string value2")) { fail("expected replace to happen"); } if (!compressed) { assertEquals("string value2", listener.ohNewValue.getDeserializedForReading()); assertEquals("string value1", listener.ohOldValue.getDeserializedForReading()); } // make sure that a custom equals/hashCode are not used when comparing values. } finally { r.getAttributesMutator().removeCacheListener(listener); } } assertTrue(ma.getUsedMemory() > 0); { Object key = "MyValueWithPartialEquals"; MyValueWithPartialEquals v1 = new MyValueWithPartialEquals("s1"); MyValueWithPartialEquals v2 = new MyValueWithPartialEquals("s2"); MyValueWithPartialEquals v3 = new MyValueWithPartialEquals("s1"); r.put(key, v1); try { if (r.replace(key, v2, "should not happen")) { fail("v1 should not be equal to v2 on an offheap region"); } if (!r.replace(key, v3, "should happen")) { fail("v1 should be equal to v3 on an offheap region"); } r.put(key, v1); if (r.remove(key, v2)) { fail("v1 should not be equal to v2 on an offheap region"); } if (!r.remove(key, v3)) { fail("v1 should be equal to v3 on an offheap region"); } } finally { r.remove(key); } } { Object key = "MyPdxWithPartialEquals"; MyPdxWithPartialEquals v1 = new MyPdxWithPartialEquals("s", "1"); MyPdxWithPartialEquals v2 = new MyPdxWithPartialEquals("s", "2"); MyPdxWithPartialEquals v3 = new MyPdxWithPartialEquals("t", "1"); r.put(key, v1); try { if (r.replace(key, v3, "should not happen")) { fail("v1 should not be equal to v3 on an offheap region"); } if (!r.replace(key, v2, "should happen")) { fail("v1 should be equal to v2 on an offheap region"); } r.put(key, v1); if (r.remove(key, v3)) { fail("v1 should not be equal to v3 on an offheap region"); } if (!r.remove(key, v2)) { fail("v1 should be equal to v2 on an offheap region"); } } finally { r.remove(key); } } byte[] value = new byte[1024]; /*while (value != null) */ { r.put("byteArray", value); } r.remove("byteArray"); assertEquals(0, ma.getUsedMemory()); r.put("key1", data); assertTrue(ma.getUsedMemory() > 0); r.invalidateRegion(); assertEquals(0, ma.getUsedMemory()); r.put("key1", data); assertTrue(ma.getUsedMemory() > 0); try { r.clear(); assertEquals(0, ma.getUsedMemory()); } catch (UnsupportedOperationException ok) { } r.put("key1", data); assertTrue(ma.getUsedMemory() > 0); if (r.getAttributes().getDataPolicy().withPersistence()) { r.put("key2", Integer.valueOf(1234567890)); r.put("key3", new Long(0x007FFFFFL)); r.put("key4", new Long(0xFF8000000L)); assertEquals(4, r.size()); r.close(); assertEquals(0, ma.getUsedMemory()); // simple test of recovery r = gfc.createRegionFactory(rs).setOffHeap(true).create(rName); assertEquals(4, r.size()); assertEquals(data, r.get("key1")); assertEquals(Integer.valueOf(1234567890), r.get("key2")); assertEquals(new Long(0x007FFFFFL), r.get("key3")); assertEquals(new Long(0xFF8000000L), r.get("key4")); closeCache(gfc, true); assertEquals(0, ma.getUsedMemory()); gfc = createCache(); if (ma != gfc.getOffHeapStore()) { fail("identity of offHeapStore changed when cache was recreated"); } r = gfc.createRegionFactory(rs).setOffHeap(true).create(rName); assertTrue(ma.getUsedMemory() > 0); assertEquals(4, r.size()); assertEquals(data, r.get("key1")); assertEquals(Integer.valueOf(1234567890), r.get("key2")); assertEquals(new Long(0x007FFFFFL), r.get("key3")); assertEquals(new Long(0xFF8000000L), r.get("key4")); } r.destroyRegion(); assertEquals(0, ma.getUsedMemory()); } finally { if (r != null && !r.isDestroyed()) { r.destroyRegion(); } closeCache(gfc, false); } }
private ByteBuffer processBinaryProtocol(RequestReader request, Cache cache) { ByteBuffer buffer = request.getRequest(); int extrasLength = buffer.get(EXTRAS_LENGTH_INDEX); final KeyWrapper key = getKey(buffer, HEADER_LENGTH + extrasLength); long decrBy = buffer.getLong(HEADER_LENGTH); long initialVal = buffer.getLong(HEADER_LENGTH + LONG_LENGTH); int expiration = buffer.getInt(HEADER_LENGTH + LONG_LENGTH + LONG_LENGTH); final Region<Object, ValueWrapper> r = getMemcachedRegion(cache); ByteBuffer newVal = ByteBuffer.allocate(8); boolean notFound = false; ValueWrapper newValWrapper = null; try { while (true) { ValueWrapper oldValWrapper = r.get(key); if (oldValWrapper == null) { if (expiration == -1) { notFound = true; } else { newVal.putLong(0, initialVal); newValWrapper = ValueWrapper.getWrappedValue(newVal.array(), 0 /*flags*/); r.put(key, newValWrapper); } break; } byte[] oldVal = oldValWrapper.getValue(); long oldLong = getLongFromByteArray(oldVal); long newLong = oldLong - decrBy; if (newLong < 0) { newLong = 0; } newVal.putLong(0, newLong); newValWrapper = ValueWrapper.getWrappedValue(newVal.array(), 0 /*flags*/); if (r.replace(key, oldValWrapper, newValWrapper)) { break; } } } catch (Exception e) { return handleBinaryException(key, request, request.getResponse(), "decrement", e); } if (expiration > 0) { StorageCommand.getExpiryExecutor() .schedule( new Runnable() { @Override public void run() { r.destroy(key); } }, expiration, TimeUnit.SECONDS); } if (getLogger().fineEnabled()) { getLogger() .fine( "decr:key:" + key + " decrBy:" + decrBy + " initVal:" + initialVal + " exp:" + expiration + " notFound:" + notFound); } ByteBuffer response = null; if (notFound) { response = request.getResponse(); response.putShort(POSITION_RESPONSE_STATUS, ResponseStatus.KEY_NOT_FOUND.asShort()); } else { if (isQuiet()) { return null; } response = request.getResponse(HEADER_LENGTH + LONG_LENGTH); response.putInt(TOTAL_BODY_LENGTH_INDEX, LONG_LENGTH); response.putLong(HEADER_LENGTH, newVal.getLong(0)); response.putLong(POSITION_CAS, newValWrapper.getVersion()); } return response; }