コード例 #1
0
 /**
  * Invalidate a key in region REGION_NAME. The keys to invalidate are specified in keyIntervals.
  *
  * @return true if all keys to be invalidated have been completed.
  */
 protected boolean invalidate() {
   SharedCounters sc = CQUtilBB.getBB().getSharedCounters();
   long nextKey = sc.incrementAndRead(CQUtilBB.LASTKEY_INVALIDATE);
   if (!keyIntervals.keyInRange(KeyIntervals.INVALIDATE, nextKey)) {
     Log.getLogWriter().info("All existing keys invalidated; returning from invalidate");
     return true;
   }
   Object key = NameFactory.getObjectNameForCounter(nextKey);
   Log.getLogWriter().info("Invalidating " + key);
   checkContainsValueForKey(key, true, "before invalidate");
   try {
     aRegion.invalidate(key);
     Log.getLogWriter()
         .info(
             "Done invalidating "
                 + key
                 + ", num remaining: "
                 + (keyIntervals.getLastKey(KeyIntervals.INVALIDATE) - nextKey));
   } catch (TimeoutException e) {
     throw new TestException(TestHelper.getStackTrace(e));
   } catch (EntryNotFoundException e) {
     throw new TestException(TestHelper.getStackTrace(e));
   }
   return (nextKey >= keyIntervals.getLastKey(KeyIntervals.INVALIDATE));
 }
コード例 #2
0
 @Test
 public void testIndexOnCommitForInvalidate() 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.invalidate(x);
   utx.commit();
   CacheUtils.log(((Person) region.get(x)));
   assertEquals(0, ((SelectResults) q.execute()).size());
 }
コード例 #3
0
  /**
   * *********** 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));
    */

  }
コード例 #4
0
  @SuppressWarnings({"rawtypes", "unchecked"})
  private void doRegionTest(final RegionShortcut rs, final String rName, boolean compressed) {
    boolean isPersistent =
        rs == RegionShortcut.LOCAL_PERSISTENT
            || rs == RegionShortcut.REPLICATE_PERSISTENT
            || rs == RegionShortcut.PARTITION_PERSISTENT;
    GemFireCacheImpl gfc = createCache(isPersistent);
    Region r = null;
    try {
      gfc.setCopyOnRead(true);
      final MemoryAllocator ma = gfc.getOffHeapStore();
      assertNotNull(ma);
      assertEquals(0, ma.getUsedMemory());
      Compressor compressor = null;
      if (compressed) {
        compressor = SnappyCompressor.getDefaultInstance();
      }
      r = gfc.createRegionFactory(rs).setOffHeap(true).setCompressor(compressor).create(rName);
      assertEquals(true, r.isEmpty());
      assertEquals(0, ma.getUsedMemory());
      Object data = new Integer(123456789);
      r.put("key1", data);
      // System.out.println("After put of Integer value off heap used memory=" +
      // ma.getUsedMemory());
      assertTrue(ma.getUsedMemory() == 0);
      assertEquals(data, r.get("key1"));
      r.invalidate("key1");
      assertEquals(0, ma.getUsedMemory());
      r.put("key1", data);
      assertTrue(ma.getUsedMemory() == 0);
      long usedBeforeUpdate = ma.getUsedMemory();
      r.put("key1", data);
      assertEquals(usedBeforeUpdate, ma.getUsedMemory());
      assertEquals(data, r.get("key1"));
      r.destroy("key1");
      assertEquals(0, ma.getUsedMemory());

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

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

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

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

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

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

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

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

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

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

    } finally {
      if (r != null && !r.isDestroyed()) {
        r.destroyRegion();
      }
      closeCache(gfc, false);
    }
  }
コード例 #5
0
  /**
   * 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);
              }
            });
  }