LATEST VERSION: 8.0.0 - CHANGELOG
Pivotal GemFire® v8.0

Sample REST Applications

Sample REST Applications

This section provides examples that illustrate how multiple clients, both REST and native, can access the same GemFire region data.

The following example demonstrates the following:

  1. A Java REST client creates a Person object on key 1.
  2. A GemFire cache client (also Java) performs a get on key1 and updates the Person objectA.
  3. Ruby REST client also gets data for key 1 and updates it.
  4. A Python REST Client performs a get on key 1 and executes the function and query data.
Note: An additional Python REST client reference application is available here: https://github.com/gemfire/py-gemfire-rest.

#1: REST Java Client (RestClient.java)

package com.gemstone.gemfire.restclient;

import java.net.URI;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.gopivotal.app.domain.Person;
import org.gopivotal.app.domain.RestClientUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.util.UriComponentsBuilder;

import com.gemstone.gemfire.util.DateTimeUtils;

@SuppressWarnings("unused")
public class RestClientApp  {
  private static final String PEOPLE_REGION = "/People";
  
  private static final String PERSON1_AS_JSON = "{"
	      + "\"@type\": \"org.gopivotal.app.domain.Person\"," + "\"id\": 1,"
	      + " \"firstName\": \"Jane\"," + " \"middleName\": \"H\","
	      + " \"lastName\": \"Doe1\"," + " \"birthDate\": \"04/12/1983\","
	      + "\"gender\": \"MALE\"" + "}";

  public static void main(final String... args) throws Exception {
    doCreate(PEOPLE_REGION, "1");
    System.out.println("Programme has run successfully...!");    
  }
  
  private static  HttpHeaders setAcceptAndContentTypeHeaders(){
    List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
    acceptableMediaTypes.add(MediaType.APPLICATION_JSON);
	    
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(acceptableMediaTypes);
    headers.setContentType(MediaType.APPLICATION_JSON);
    return headers;
  }
  
  private static void doCreate(final String regionNamePath, final String key) {
    HttpHeaders headers =  setAcceptAndContentTypeHeaders();
    HttpEntity<String> entity = new HttpEntity<String>(PERSON1_AS_JSON, headers);
    try { 
      ResponseEntity<String> result = RestClientUtils.getRestTemplate().exchange(
            "http://localhost:8080/gemfire-api/v1/People?key=1", HttpMethod.POST,
            entity, String.class);
        
      System.out.println("STATUS_CODE = " + result.getStatusCode().value());
      System.out.println("HAS_BODY = " + result.hasBody());
      System.out.println("LOCATION_HEADER = " + result.getHeaders().getLocation().toString());
    } catch (HttpClientErrorException e) {
      System.out.println("Http Client encountered error, msg:: " + e.getMessage());
    } catch(HttpServerErrorException se) {
      System.out.println("Server encountered error, msg::" + se.getMessage);
    } catch (Exception e) {
      System.out.println("Unexpected ERROR...!!");
    }
  }
}

#2: GemFire Cache Java Client (MyJavaClient.java)

public class MyJavaClient {

  public static void main(String[] args) {
    ClientCacheFactory cf = new ClientCacheFactory().addPoolServer("localhost", 40405);
    //ClientCache cache = cf.setPdxReadSerialized(true).create();
    ClientCache cache = cf.create();
    ClientRegionFactory rf = cache.createClientRegionFactory(ClientRegionShortcut.PROXY);
                
    Region region = rf.create("People");
                
    //Get data on key "1", update it and put it again in cache
    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("Jane_updated");
      actualObj.setLastName("Doe_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);
    
    //putAll all person 			    
    region.putAll(userMap);
                
    System.out.println("successfully Put set of Person objects into the cache");
  }

}

#3: Ruby REST Client (restClient.rb)

#!/usr/bin/ruby -w

puts "Hello, Ruby!";

# !/usr/bin/env ruby

require 'json'
require 'net/http'

class JsonSerializable

  def to_json
    hash = {}
    hash["@type"] = "com.gemstone.gemfire.web.rest.domain.Person"
    self.instance_variables.each do |var|
      if !var.to_s.end_with?("links")
        hash[var.to_s[1..-1]] = self.instance_variable_get var
      end
    end
    hash.to_json
  end

  def from_json! jsonString
    JSON.load(jsonString).each do |var, val|
      if !var.end_with?("type")
        self.instance_variable_set "@".concat(var), val
      end
    end
  end

end

class Person < JsonSerializable

  attr_accessor :id, :firstName, :middleName, :lastName, :birthDate, :gender

  def initialize(id = nil, firstName = nil, middleName = nil, lastName = nil )
    @id = id
    @firstName = firstName
    @middleName = middleName
    @lastName = lastName
    @birthDate = nil
    @gender = nil
  end

  def to_s
    s = "{ type = Person, id = #{@id}"
    s += ", firstName = #{@firstName}"
    s += ", middleName = #{@middleName}"
    s += ", lastName = #{@lastName}"
    s += ", birthDate = #{@birthDate}"
    s += ", gender = #{@gender}"
    s += "}"
  end

end

if __FILE__ == $0
  #p = Person.new(1, "Jon", "T", "Doe")
  #puts p
  #puts p.inspect
  #puts p.to_json

  uri = URI("http://localhost:8080/gemfire-api/v1/People/1");

  personJson = Net::HTTP::get(uri);

  # JSON from server
  puts "JSON read from Server for Person with ID 1...\n #{personJson}"

  p = Person.new
  p.from_json! personJson

  # print the Person to standard out
  puts "Person is...\n #{p}"

  p.id = 1
  p.firstName = "Jack"
  p.lastName = "Handy"
  p.gender = "MALE"

  # prints modified Person to standard out
  puts "Person modified is...\n #{p}"

  puts "JSON sent to Server for Person with ID 1...\n #{p.to_json}"
  
  Net::HTTP.start(uri.hostname, uri.port) do |http|
    putRequest = Net::HTTP::Put.new uri.path, { "Content-Type" => "application/json" }
    putRequest.body = p.to_json
    http.request(putRequest)
  end

end
Output from running the Ruby client:
prompt# ruby restClient.rb
Hello, Ruby!
JSON read from Server for Person with ID 1...
 {
  "@type" : "org.gopivotal.app.domain.Person",
  "id" : 1,
  "firstName" : "Jane_updated",
  "middleName" : "H",
  "lastName" : "Doe_updated",
  "gender" : "MALE",
  "birthDate" : "04/12/1983"
}
Person is...
 { type = Person, id = 1, firstName = Jane_updated, middleName = H, lastName = Doe_updated, birthDate = 04/12/1983, gender = MALE}
Person modified is...
 { type = Person, id = 1, firstName = Jack, middleName = H, lastName = Handy, birthDate = 04/12/1983, gender = MALE}
JSON sent to Server for Person with ID 1...
 {"@type":"com.gemstone.gemfire.web.rest.domain.Person","id":1,"firstName":"Jack","middleName":"H","lastName":"Handy","birthDate":"04/12/1983","gender":"MALE"}

#4: Python REST Client (restClient.py)

print "Sample Python REST Client Program"
import urllib2
url = 'http: //localhost:8080/gemfire-api/v1/People/1'
response = urllib2.urlopen(url)
body = response.read()
statusCode = response.getcode()

print 'Response payload'
print body
print 'status code'
print statusCode
Output from running the Python client:
prompt# python restClient.py

Sample Python REST Client Program
Response payload
{
  "@type" : "com.gemstone.gemfire.web.rest.domain.Person",
  "id" : 1,
  "firstName" : "Jack",
  "middleName" : "H",
  "lastName" : "Handy",
  "birthDate" : "04/12/1983",
  "gender" : "MALE"
}
status code
200