Java Code Examples for org.apache.geode.cache.Region#put()

The following examples show how to use org.apache.geode.cache.Region#put() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Example.java    From geode-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  ClientCache cache = new ClientCacheFactory().addPoolLocator("127.0.0.1", 10334)
      .set("log-level", "WARN").create();

  Region<Integer, Customer> customerRegion =
      cache.<Integer, Customer>createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY)
          .create("customer");

  Region<OrderKey, Order> orderRegion =
      cache.<OrderKey, Order>createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY)
          .create("order");

  Map<Integer, Customer> customers = generateCustomers();

  for (int i : customers.keySet()) {
    Customer customer = customers.get(i);
    Order order = new Order(i * 10, customer.getId());
    customerRegion.put(customer.getId(), customer);
    orderRegion.put(order.getKey(), order);
  }
  cache.close();
}
 
Example 2
Source File: RegionPopulator.java    From geode-examples with Apache License 2.0 6 votes vote down vote up
void insertPassengers(int numberOfPassengers, Region<String, Passenger> region) {
  PrimitiveIterator.OfInt firstNameIndexes = random.ints(0, firstNames.length).iterator();
  PrimitiveIterator.OfInt lastNameIndexes = random.ints(0, lastNames.length).iterator();
  PrimitiveIterator.OfInt ages = random.ints(20, 100).iterator();
  PrimitiveIterator.OfInt flightIndexes = random.ints(0, flights.size()).iterator();
  PrimitiveIterator.OfInt milliSeconds = random.ints(0, 7 * 24 * 60 * 60 * 1000).iterator();
  while (region.sizeOnServer() < numberOfPassengers) {
    String name = firstNames[firstNameIndexes.next()] + " " + lastNames[lastNameIndexes.next()];
    if (!region.containsKey(name)) {
      final long departure = System.currentTimeMillis() + milliSeconds.next();
      final long arrival = departure + milliSeconds.next();
      Passenger passenger = new Passenger(name, ages.next(), flights.get(flightIndexes.next()),
          new Date(departure), new Date(arrival));
      region.put(passenger.getName(), passenger);
    }
  }
}
 
Example 3
Source File: Example.java    From geode-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
  ClientCache cache = new ClientCacheFactory().addPoolLocator("127.0.0.1", 10334)
      .set("log-level", "WARN").create();

  Region<Integer, Customer> customerRegion =
      cache.<Integer, Customer>createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY)
          .create("customer");

  Region<OrderKey, Order> orderRegion =
      cache.<OrderKey, Order>createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY)
          .create("order");

  Map<Integer, Customer> customers = generateCustomers();

  for (int i : customers.keySet()) {
    Customer customer = customers.get(i);
    Order order = new Order(i * 10, customer.getId());
    customerRegion.put(customer.getId(), customer);
    orderRegion.put(order.getKey(), order);
  }
  cache.close();
}
 
Example 4
Source File: SpringBootApacheGeodePeerCacheApplicationIntegrationTests.java    From spring-boot-data-geode with Apache License 2.0 6 votes vote down vote up
@Test
public void peerCacheWithPeerLocalRegionAreAvailable() {

	Optional.ofNullable(this.peerCache)
		.map(it -> assertThat(GemfireUtils.isClient(it)).isFalse())
		.orElseThrow(() -> newIllegalStateException("Peer cache was null"));

	Region<Object, Object> example = this.peerCache.getRegion("/Example");

	assertThat(example).isNotNull();
	assertThat(example.getName()).isEqualTo("Example");
	assertThat(example.getFullPath()).isEqualTo(RegionUtils.toRegionPath("Example"));

	example.put(1, "test");

	assertThat(example.get(1)).isEqualTo("test");
}
 
Example 5
Source File: SpringBootApacheGeodeClientCacheApplicationIntegrationTests.java    From spring-boot-data-geode with Apache License 2.0 6 votes vote down vote up
@Test
public void clientCacheAndClientRegionAreAvailable() {

	Optional.ofNullable(this.clientCache)
		.map(it -> assertThat(GemfireUtils.isClient(it)).isTrue())
		.orElseThrow(() -> newIllegalStateException("ClientCache was null"));

	Region<Object, Object> example = this.clientCache.getRegion("Example");

	assertThat(example).isNotNull();
	assertThat(example.getName()).isEqualTo("Example");
	assertThat(example.getFullPath()).isEqualTo(RegionUtils.toRegionPath("Example"));

	example.put(1, "test");

	assertThat(example.get(1)).isEqualTo("test");
}
 
Example 6
Source File: Example.java    From geode-examples with Apache License 2.0 6 votes vote down vote up
public void checkWords(Region<Integer, String> incomingRegion,
    Region<String, String> outgoingRegion, List<String> words) {
  int key = 0;
  for (String word : words) {
    incomingRegion.put(key++, word);
  }

  // Give the process a chance to work.
  while (outgoingRegion.sizeOnServer() < words.size()) {
    try {
      Thread.sleep(500);
    } catch (InterruptedException ie) {
      // NOP
    }
  }

  for (String candidate : outgoingRegion.keySetOnServer()) {
    System.out.println(candidate + " -> " + outgoingRegion.get(candidate));
  }
}
 
Example 7
Source File: Example.java    From geode-examples with Apache License 2.0 5 votes vote down vote up
public Set<Integer> getPrimes(Region<Integer, String> region, Execution execution) {
  Set<Integer> primes = new HashSet<>();

  for (Integer key : (Iterable<Integer>) () -> IntStream.rangeClosed(1, maximum).iterator()) {
    region.put(key, key.toString());
  }

  ResultCollector<Integer, List> results = execution.execute(PrimeNumber.ID);
  primes.addAll(results.getResult());
  System.out.println("The primes in the range from 1 to " + maximum + " are:\n" + primes);
  return primes;
}
 
Example 8
Source File: Example.java    From geode-examples with Apache License 2.0 5 votes vote down vote up
public void putEntries(Region<Integer, String> region) {
  Collection<Integer> integers = generateIntegers();
  Iterator<Integer> iterator = integers.iterator();

  int created = 0;
  while (iterator.hasNext()) {
    Integer integer = iterator.next();
    region.put(integer, integer.toString());
    System.out.println("Added value for " + integer + "; the region now has "
        + region.sizeOnServer() + " entries.");
    ++created;
  }
}
 
Example 9
Source File: Example.java    From geode-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  // connect to the locator using default port 10334
  ClientCache cache =
      new ClientCacheFactory().addPoolLocator("127.0.0.1", 10334)
          .setPdxSerializer(
              new ReflectionBasedAutoSerializer("org.apache.geode_examples.jdbc.Parent"))
          .create();

  // create a local region that connects to the server region
  Region<Long, Parent> region =
      cache.<Long, Parent>createClientRegionFactory(ClientRegionShortcut.PROXY).create("Parent");
  System.out.println("Region=" + region.getFullPath());

  Example example = new Example(region);

  // Put entry in Parent region to verify it propagates to the external RDBMS table
  Long key = Long.valueOf(1);
  Parent value = new Parent(key, "Parent_1", Double.valueOf(123456789.0));
  region.put(key, value);
  System.out.println("Region.put() added an entry into Parent region. The key is " + key
      + ", and the value is " + value + ".");
  System.out.println(
      "If JDBC Connector is configured, the value will be persisted to external data source.");
  // Get an entry from Parent region that will trigger the cache loader to
  // retrieve the entry from the external table
  System.out.println(
      "Calling Region.get(). If JDBC Connector is configured, it will retrieve data from external data source and return a non-null value.");
  key = Long.valueOf(2);
  Parent parent = (Parent) region.get(key);
  System.out.println("The returned value of Region.get(" + key + ") is " + parent + ".");

  // Print the current entries in the region
  System.out.println("All entries currently in Parent region");
  example.printValues(example.getKeys());

  cache.close();
}
 
Example 10
Source File: Example.java    From geode-examples with Apache License 2.0 5 votes vote down vote up
private void addName(Region<String, String> region, String ssn, String name, List<String> names) {
  try {
    region.put(ssn, name);
    names.add(name);
  } catch (CacheWriterException | ServerOperationException e) {
    System.out.println("Invalid SSN: " + ssn);
  }
}
 
Example 11
Source File: Example.java    From geode-examples with Apache License 2.0 5 votes vote down vote up
public Set<Integer> getPrimes(Region<Integer, String> region, Execution execution) {
  Set<Integer> primes = new HashSet<>();

  for (Integer key : (Iterable<Integer>) () -> IntStream.rangeClosed(1, maximum).iterator()) {
    region.put(key, key.toString());
  }

  ResultCollector<Integer, List> results = execution.execute(PrimeNumber.ID);
  primes.addAll(results.getResult());
  System.out.println("The primes in the range from 1 to " + maximum + " are:\n" + primes);
  return primes;
}
 
Example 12
Source File: Example.java    From geode-examples with Apache License 2.0 5 votes vote down vote up
public void putEntries(Region<Integer, String> region) {
  Collection<Integer> integers = generateIntegers();
  Iterator<Integer> iterator = integers.iterator();

  int created = 0;
  while (iterator.hasNext()) {
    Integer integer = iterator.next();
    region.put(integer, integer.toString());
    System.out.println("Added value for " + integer + "; the region now has "
        + region.sizeOnServer() + " entries.");
    ++created;
  }
}
 
Example 13
Source File: Example.java    From geode-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  // connect to the locator using default port 10334
  ClientCache cache =
      new ClientCacheFactory().addPoolLocator("127.0.0.1", 10334)
          .setPdxSerializer(
              new ReflectionBasedAutoSerializer("org.apache.geode_examples.jdbc.Parent"))
          .create();

  // create a local region that connects to the server region
  Region<Long, Parent> region =
      cache.<Long, Parent>createClientRegionFactory(ClientRegionShortcut.PROXY).create("Parent");
  System.out.println("Region=" + region.getFullPath());

  Example example = new Example(region);

  // Put entry in Parent region to verify it propagates to the external RDBMS table
  Long key = Long.valueOf(1);
  Parent value = new Parent(key, "Parent_1", Double.valueOf(123456789.0));
  region.put(key, value);
  System.out.println("Region.put() added an entry into Parent region. The key is " + key
      + ", and the value is " + value + ".");
  System.out.println(
      "If JDBC Connector is configured, the value will be persisted to external data source.");
  // Get an entry from Parent region that will trigger the cache loader to
  // retrieve the entry from the external table
  System.out.println(
      "Calling Region.get(). If JDBC Connector is configured, it will retrieve data from external data source and return a non-null value.");
  key = Long.valueOf(2);
  Parent parent = (Parent) region.get(key);
  System.out.println("The returned value of Region.get(" + key + ") is " + parent + ".");

  // Print the current entries in the region
  System.out.println("All entries currently in Parent region");
  example.printValues(example.getKeys());

  cache.close();
}
 
Example 14
Source File: Example.java    From geode-examples with Apache License 2.0 5 votes vote down vote up
private void addName(Region<String, String> region, String ssn, String name, List<String> names) {
  try {
    region.put(ssn, name);
    names.add(name);
  } catch (CacheWriterException | ServerOperationException e) {
    System.out.println("Invalid SSN: " + ssn);
  }
}
 
Example 15
Source File: Example.java    From geode-examples with Apache License 2.0 4 votes vote down vote up
private void startPuttingData(Region region) throws InterruptedException {

    // Example will run for 20 second

    Stopwatch stopWatch = Stopwatch.createStarted();

    while (stopWatch.elapsed(TimeUnit.SECONDS) < 20) {

      // 500ms delay to make this easier to follow
      Thread.sleep(500);
      int randomKey = ThreadLocalRandom.current().nextInt(0, 99 + 1);
      int randomValue = ThreadLocalRandom.current().nextInt(0, 100 + 1);
      region.put(randomKey, randomValue);
      System.out.println("Key: " + randomKey + "     Value: " + randomValue);

    }

    stopWatch.stop();

  }
 
Example 16
Source File: Example.java    From geode-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
  ClientCache clientCacheOne = createDurableClient();

  final String regionName = "example-region";

  // Create a local caching proxy region that matches the server region
  ClientRegionFactory<Integer, String> clientOneRegionFactory =
      clientCacheOne.createClientRegionFactory(ClientRegionShortcut.PROXY);
  Region<Integer, String> exampleClientRegionOne = clientOneRegionFactory.create(regionName);

  // Register interest to create the durable client message queue
  exampleClientRegionOne.registerInterestForAllKeys(InterestResultPolicy.DEFAULT, true);

  // Close the client cache with keepalive set to true so
  // the durable client messages are preserved
  // for the duration of the configured timeout. In practice,
  // it is more likely the client would disconnect
  // due to a temporary network issue, but for this example the cache is explicitly closed.
  clientCacheOne.close(true);

  // Create a second client to do puts with while the first client is disconnected
  ClientCache clientCacheTwo = new ClientCacheFactory().addPoolLocator("127.0.0.1", 10334)
      .set("log-level", "WARN").create();

  ClientRegionFactory<Integer, String> clientTwoRegionFactory =
      clientCacheTwo.createClientRegionFactory(ClientRegionShortcut.PROXY);
  Region<Integer, String> exampleClientRegionTwo = clientTwoRegionFactory.create(regionName);

  for (int i = 0; i < numEvents; ++i) {
    exampleClientRegionTwo.put(i, "testValue" + i);
  }

  // Close the second client and restart the durable client
  clientCacheTwo.close(false);

  clientCacheOne = createDurableClient();

  // Add an example cache listener so this client can react
  // when the server sends this client's events from the
  // durable message queue. This isn't required but helps
  // illustrate that the events are delivered successfully.
  clientOneRegionFactory = clientCacheOne.createClientRegionFactory(ClientRegionShortcut.PROXY);
  exampleClientRegionOne = clientOneRegionFactory
      .addCacheListener(new ExampleCacheListener<Integer, String>()).create(regionName);

  // Signal to the server that this client is ready to receive events.
  // Events in this client's durable message queue
  // will then be delivered and trigger our example cache listener.
  clientCacheOne.readyForEvents();

  // Use a count down latch to ensure that this client receives all queued events from the server
  waitForEventsLatch.await();
}
 
Example 17
Source File: Example.java    From geode-examples with Apache License 2.0 4 votes vote down vote up
public Example(Region<String, Integer> region) {
  this.region = region;
  if (!region.containsKeyOnServer(KEY)) {
    region.put(KEY, 0);
  }
}
 
Example 18
Source File: Example.java    From geode-examples with Apache License 2.0 4 votes vote down vote up
private void startPuttingData(Region region) throws InterruptedException {

    // Example will run for 20 second

    Stopwatch stopWatch = Stopwatch.createStarted();

    while (stopWatch.elapsed(TimeUnit.SECONDS) < 20) {

      // 500ms delay to make this easier to follow
      Thread.sleep(500);
      int randomKey = ThreadLocalRandom.current().nextInt(0, 99 + 1);
      int randomValue = ThreadLocalRandom.current().nextInt(0, 100 + 1);
      region.put(randomKey, randomValue);
      System.out.println("Key: " + randomKey + "     Value: " + randomValue);

    }

    stopWatch.stop();

  }
 
Example 19
Source File: Example.java    From geode-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
  ClientCache clientCacheOne = createDurableClient();

  final String regionName = "example-region";

  // Create a local caching proxy region that matches the server region
  ClientRegionFactory<Integer, String> clientOneRegionFactory =
      clientCacheOne.createClientRegionFactory(ClientRegionShortcut.PROXY);
  Region<Integer, String> exampleClientRegionOne = clientOneRegionFactory.create(regionName);

  // Register interest to create the durable client message queue
  exampleClientRegionOne.registerInterestForAllKeys(InterestResultPolicy.DEFAULT, true);

  // Close the client cache with keepalive set to true so
  // the durable client messages are preserved
  // for the duration of the configured timeout. In practice,
  // it is more likely the client would disconnect
  // due to a temporary network issue, but for this example the cache is explicitly closed.
  clientCacheOne.close(true);

  // Create a second client to do puts with while the first client is disconnected
  ClientCache clientCacheTwo = new ClientCacheFactory().addPoolLocator("127.0.0.1", 10334)
      .set("log-level", "WARN").create();

  ClientRegionFactory<Integer, String> clientTwoRegionFactory =
      clientCacheTwo.createClientRegionFactory(ClientRegionShortcut.PROXY);
  Region<Integer, String> exampleClientRegionTwo = clientTwoRegionFactory.create(regionName);

  for (int i = 0; i < numEvents; ++i) {
    exampleClientRegionTwo.put(i, "testValue" + i);
  }

  // Close the second client and restart the durable client
  clientCacheTwo.close(false);

  clientCacheOne = createDurableClient();

  // Add an example cache listener so this client can react
  // when the server sends this client's events from the
  // durable message queue. This isn't required but helps
  // illustrate that the events are delivered successfully.
  clientOneRegionFactory = clientCacheOne.createClientRegionFactory(ClientRegionShortcut.PROXY);
  exampleClientRegionOne = clientOneRegionFactory
      .addCacheListener(new ExampleCacheListener<Integer, String>()).create(regionName);

  // Signal to the server that this client is ready to receive events.
  // Events in this client's durable message queue
  // will then be delivered and trigger our example cache listener.
  clientCacheOne.readyForEvents();

  // Use a count down latch to ensure that this client receives all queued events from the server
  waitForEventsLatch.await();
}
 
Example 20
Source File: JsonCacheDataImporterExporterIntegrationTests.java    From spring-boot-data-geode with Apache License 2.0 3 votes vote down vote up
@Test
public void exportFromExampleRegionToJson() {

	try {
		System.setProperty(EXPORT_ENABLED_PROPERTY, Boolean.TRUE.toString());

		StringWriter writer = new StringWriter();

		writerSupplier = () -> writer;

		Region<Long, Customer> example =
			getExampleRegion(newApplicationContext(withResource("data-example.json")));

		assertExampleRegion(example);
		assertThat(example).isEmpty();

		Customer playDoe = Customer.newCustomer(42L, "Play Doe");

		example.put(playDoe.getId(), playDoe);

		assertThat(example).hasSize(1);
		assertThat(example.get(42L)).isEqualTo(playDoe);

		closeApplicationContext();

		String actualJson = StringUtils.trimAllWhitespace(writer.toString());

		String expectedJson = String.format("[{\"@type\":\"%s\",\"id\":42,\"name\":\"PlayDoe\"}]",
			playDoe.getClass().getName());

		assertThat(actualJson).isEqualTo(expectedJson);
	}
	finally {
		System.clearProperty(EXPORT_ENABLED_PROPERTY);
	}
}