Java源码示例:org.apache.geode.cache.Region

示例1
public static void main(String[] args) {
  // connect to the locator in London cluster using port 10332
  ClientCache cache = new ClientCacheFactory().addPoolLocator("127.0.0.1", 10332)
      .set("log-level", "WARN").create();

  // create a local region that matches the server region
  Region<Integer, String> region =
      cache.<Integer, String>createClientRegionFactory(ClientRegionShortcut.PROXY)
          .create("example-region");

  Example example = new Example(region);
  example.insertValues(10);
  example.printValues(example.getValues());

  cache.close();
}
 
示例2
private BiConsumer<Region<?, ?>, Health.Builder> withRegionEvictionPolicyDetails() {

		return (region, builder) -> {

			if (isRegionAttributesPresent(region)) {

				EvictionAttributes evictionAttributes = region.getAttributes().getEvictionAttributes();

				if (evictionAttributes != null) {

					String regionName = region.getName();

					builder.withDetail(cacheRegionEvictionKey(regionName, "action"), String.valueOf(evictionAttributes.getAction()))
						.withDetail(cacheRegionEvictionKey(regionName, "algorithm"), String.valueOf(evictionAttributes.getAlgorithm()));

					EvictionAlgorithm evictionAlgorithm = evictionAttributes.getAlgorithm();

					// NOTE: Eviction Maximum does not apply when Eviction Algorithm is Heap LRU.
					if (evictionAlgorithm != null && !evictionAlgorithm.isLRUHeap()) {
						builder.withDetail(cacheRegionEvictionKey(regionName,"maximum"),
							evictionAttributes.getMaximum());
					}
				}
			}
		};
	}
 
示例3
public static void main(String[] args) {
  // connect to the locator using default port 10334
  ClientCache cache = new ClientCacheFactory().addPoolLocator("127.0.0.1", 10334)
      .set("log-level", "WARN").create();

  // create a local region that matches the server region
  Region<Integer, String> region =
      cache.<Integer, String>createClientRegionFactory(ClientRegionShortcut.PROXY)
          .create("example-region");

  Example example = new Example(region);
  example.insertValues(10);
  example.printValues(example.getValues());

  cache.close();
}
 
示例4
public static void main(String[] args) {
  // connect to the locator using default port 10334
  ClientCache cache = new ClientCacheFactory().addPoolLocator("127.0.0.1", 10334)
      .set("log-level", "WARN").create();

  // create a local region that matches the server region
  Region<Integer, String> region =
      cache.<Integer, String>createClientRegionFactory(ClientRegionShortcut.PROXY)
          .create("example-region");

  Example example = new Example(region);
  example.insertValues(10);
  example.printValues(example.getValues());

  cache.close();
}
 
示例5
private Session(Class<?> entityType, GeodeBackend backend) {
  this.entityType = Objects.requireNonNull(entityType, "entityType");
  GeodeSetup setup = backend.setup;
  @SuppressWarnings("unchecked")
  Region<Object, Object> region = (Region<Object, Object>) setup.regionResolver().resolve(entityType);
  this.region = region;

  KeyExtractor keyExtractor = setup.keyExtractorFactory().create(entityType);
  if (!keyExtractor.metadata().isKeyDefined()) {
    throw new IllegalArgumentException(String.format("Key on %s is required for %s", entityType, GeodeBackend.class.getSimpleName()));
  }

  this.keyExtractor = keyExtractor;
  this.queryService = setup.queryServiceResolver().resolve(region);
  this.pathNaming = backend.pathNaming;
  this.keyLookupAnalyzer = KeyLookupAnalyzer.fromExtractor(keyExtractor);
}
 
示例6
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));
  }
}
 
示例7
/**
 * Obtains a proxy pointing to an existing Region on the server
 *
 * @param cache {@link GemFireCache} instance to interact with the Geode server
 * @param regionName  Name of the region to create proxy for.
 * @return Returns a Region proxy to a remote (on the Server) regions.
 */
public static synchronized Region createRegion(GemFireCache cache, String regionName) {
  Objects.requireNonNull(cache, "cache");
  Objects.requireNonNull(regionName, "regionName");
  Region region = REGION_MAP.get(regionName);
  if (region == null) {
    try {
      region = ((ClientCache) cache)
          .createClientRegionFactory(ClientRegionShortcut.PROXY)
          .create(regionName);
    } catch (IllegalStateException | RegionExistsException e) {
      // means this is a server cache (probably part of embedded testing
      // or clientCache is passed directly)
      region = cache.getRegion(regionName);
    }

    REGION_MAP.put(regionName, region);
  }

  return region;
}
 
示例8
@Test
public void getResourceFromRegionAndResourcePrefix() {

	ApplicationContext mockApplicationContext = mock(ApplicationContext.class);

	Region<?, ?> mockRegion = mock(Region.class);

	Resource mockResource = mock(Resource.class);

	doReturn(mockResource).when(mockApplicationContext).getResource(anyString());
	doReturn("Example").when(mockRegion).getName();
	doReturn(Optional.of(mockApplicationContext)).when(this.importer).getApplicationContext();

	assertThat(this.importer.getResource(mockRegion, "sftp://host/resources/").orElse(null))
		.isEqualTo(mockResource);

	verify(mockApplicationContext, times(1))
		.getResource(eq("sftp://host/resources/data-example.json"));
	verify(mockRegion, times(1)).getName();
}
 
示例9
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);
    }
  }
}
 
示例10
@GemfireFunction(id = "AdministerPetVaccinations", optimizeForWrite = true)
public void administerPetVaccinations(FunctionContext functionContext) {

	Optional.ofNullable(functionContext)
		.filter(RegionFunctionContext.class::isInstance)
		.map(RegionFunctionContext.class::cast)
		.map(RegionFunctionContext::getDataSet)
		.map(Region::values)
		.ifPresent(pets -> pets.forEach(pet -> {

			Pet resolvePet = (Pet) pet;

			resolvePet.vaccinate();

			((RegionFunctionContext) functionContext).getDataSet().put(resolvePet.getName(), resolvePet);
		}));
}
 
示例11
@Bean
JsonCacheDataImporterExporter exampleRegionDataImporter() {

	return new JsonCacheDataImporterExporter() {

		@Override @SuppressWarnings("rawtypes")
		protected Optional<Resource> getResource(@NonNull Region region, String resourcePrefix) {
			return Optional.ofNullable(resourceSupplier.get());
		}

		@NonNull @Override
		Writer newWriter(@NonNull Resource resource) {
			return writerSupplier.get();
		}
	};
}
 
示例12
@Test
public void isClientRegionWithClientRegionDeterminedByPoolName() {

	Region<?, ?> mockRegion = mock(Region.class);

	RegionAttributes<?, ?> mockRegionAttributes = mock(RegionAttributes.class);

	RegionService mockRegionService = mock(RegionService.class);

	doReturn(mockRegionAttributes).when(mockRegion).getAttributes();
	doReturn(mockRegionService).when(mockRegion).getRegionService();
	doReturn("TestPool").when(mockRegionAttributes).getPoolName();

	assertThat(CacheUtils.isClientRegion(mockRegion)).isTrue();
	assertThat(CacheUtils.isPeerRegion(mockRegion)).isFalse();

	verify(mockRegion, times(2)).getRegionService();
	verify(mockRegion, times(2)).getAttributes();
	verify(mockRegionAttributes, times(2)).getPoolName();
	verifyNoMoreInteractions(mockRegion, mockRegionAttributes);
	verifyNoInteractions(mockRegionService);
}
 
示例13
@Test
@SuppressWarnings("unchecked")
public void doImportIntoWithNoPdxInstance() {

	Resource mockResource = mock(Resource.class);

	Region<?, ?> mockRegion = mock(Region.class);

	byte[] json = "[]".getBytes();

	doReturn(Optional.of(mockResource)).when(this.importer).getResource(eq(mockRegion), eq("classpath:"));
	doReturn(true).when(mockResource).exists();
	doReturn(json).when(this.importer).getContent(eq(mockResource));
	doReturn(new PdxInstance[0]).when(this.importer).toPdx(eq(json));

	assertThat(this.importer.doImportInto(mockRegion)).isEqualTo(mockRegion);

	verify(this.importer, times(1)).doImportInto(eq(mockRegion));
	verify(this.importer, times(1)).getResource(eq(mockRegion), eq("classpath:"));
	verify(this.importer, times(1)).getContent(eq(mockResource));
	verify(this.importer, times(1)).toPdx(eq(json));
	verify(mockResource, times(1)).exists();
	verifyNoMoreInteractions(this.importer);
	verifyNoMoreInteractions(mockResource);
	verifyNoInteractions(mockRegion);
}
 
示例14
@Test
public void exampleServerRegionExistsAsClientRegionBean() {

	Region<?, ?> exampleServerRegion = this.applicationContext.getBean("ExampleServerRegion", Region.class);

	assertThat(exampleServerRegion).isNotNull();
	assertThat(exampleServerRegion.getName()).isEqualTo("ExampleServerRegion");
	assertThat(exampleServerRegion.getAttributes()).isNotNull();
	assertThat(exampleServerRegion.getAttributes().getDataPolicy()).isEqualTo(DataPolicy.EMPTY);
}
 
示例15
public static void main(String[] args) {
  // connect to the locator using default port 10334
  ClientCache cache = new ClientCacheFactory().addPoolLocator("127.0.0.1", 10334)
      .set("log-level", "WARN").create();

  // create a local region that matches the server region
  Region<Integer, String> region =
      cache.<Integer, String>createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY)
          .create("example-region");

  Execution execution = FunctionService.onRegion(region);
  new Example().getPrimes(region, execution);
  cache.close();
}
 
示例16
@Test
public void exampleRegionContainsDoeFamily() {

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

	assertThat(example).hasSize(9);

	Set<Customer> customers = example.values().stream()
		.filter(PdxInstance.class::isInstance)
		.map(PdxInstance.class::cast)
		.map(PdxInstance::getObject)
		.filter(Customer.class::isInstance)
		.map(Customer.class::cast)
		.collect(Collectors.toSet());

	assertThat(customers).hasSize(example.size());

	assertThat(customers).containsExactlyInAnyOrder(
		Customer.newCustomer(1L, "Jon Doe"),
		Customer.newCustomer(2L, "Jane Doe"),
		Customer.newCustomer(3L, "Cookie Doe"),
		Customer.newCustomer(4L, "Fro Doe"),
		Customer.newCustomer(5L, "Ginger Doe"),
		Customer.newCustomer(6L, "Hoe Doe"),
		Customer.newCustomer(7L, "Joe Doe"),
		Customer.newCustomer(8L, "Pie Doe"),
		Customer.newCustomer(9L, "Sour Doe")
	);
}
 
示例17
void insertValues(Region<Integer, String> region, Collection<Integer> integers) {
  Map values = new HashMap<Integer, String>();
  for (Integer i : integers) {
    values.put(i, i.toString());
  }
  region.putAll(values);
  System.out.println(
      ISO_8601_TIMESTAMP_FORMAT.format(new Date()) + "\tInserted " + values.size() + " values.");
}
 
示例18
public void monitorEntries(Region<Integer, String> region) {
  while (0 < region.sizeOnServer()) {
    try {
      Thread.sleep(1000);
      System.out.println(ISO_8601_TIMESTAMP_FORMAT.format(new Date()) + "\tThe region now has "
          + region.sizeOnServer() + " entries.");
    } catch (InterruptedException ie) {
      // NOP
    }
  }
}
 
示例19
public void monitorEntries(Region<Integer, String> region) {
  while (0 < region.sizeOnServer()) {
    try {
      Thread.sleep(1000);
      System.out.println(ISO_8601_TIMESTAMP_FORMAT.format(new Date()) + "\tThe region now has "
          + region.sizeOnServer() + " entries.");
    } catch (InterruptedException ie) {
      // NOP
    }
  }
}
 
示例20
private void assertRegion(Region<?, ?> region, String name, DataPolicy dataPolicy, String poolName) {

		assertThat(region).isNotNull();
		assertThat(region.getName()).isEqualTo(name);
		assertThat(region.getAttributes()).isNotNull();
		assertThat(region.getAttributes().getDataPolicy()).isEqualTo(dataPolicy);
		assertThat(region.getAttributes().getPoolName()).isEqualTo(poolName);
	}
 
示例21
/**
 * Resolve region using default {@link ContainerNaming#DEFAULT} naming convention.
 * @see org.apache.geode.cache.RegionService#getRegion(String)
 */
static RegionResolver defaultResolver(GemFireCache cache) {
  Objects.requireNonNull(cache, "cache");
  return ctx -> {
    String name = ContainerNaming.DEFAULT.name(ctx);
    Region<Object, Object> region = cache.getRegion(name);
    if (region == null) {
      throw new IllegalArgumentException(String.format("Failed to find geode region for %s. " +
              "Region %s not found in %s cache", ctx.getName(), name, cache.getName()));
    }
    return region;
  };
}
 
示例22
@Test
public void clientCacheContainsExampleServerRegion() {

	assertThat(this.clientCache).isNotNull();

	assertThat(CollectionUtils.nullSafeSet(this.clientCache.rootRegions()).stream()
		.map(Region::getName)
		.collect(Collectors.toSet())).containsExactly("ExampleServerRegion");
}
 
示例23
private <K, V> Region<K, V> assertExampleRegion(Region<K, V> example) {

		assertThat(example).isNotNull();
		assertThat(example.getName()).isEqualTo("Example");
		assertThat(example.getAttributes()).isNotNull();
		assertThat(example.getAttributes().getDataPolicy()).isEqualTo(DataPolicy.NORMAL);
		assertThat(example.getAttributes().getScope()).isEqualTo(Scope.LOCAL);

		return example;
	}
 
示例24
/**
 * Extract the first entity of each Regions and use it to build a table types.
 *
 * @param region existing region
 * @return derived data type.
 */
public static RelDataType autodetectRelTypeFromRegion(Region<?, ?> region) {
  Objects.requireNonNull(region, "region");

  // try to detect type using value constraints (if they exists)
  final Class<?> constraint = region.getAttributes().getValueConstraint();
  if (constraint != null && !PdxInstance.class.isAssignableFrom(constraint)) {
    return new JavaTypeFactoryExtImpl().createStructType(constraint);
  }

  final Iterator<?> iter;
  if (region.getAttributes().getPoolName() == null) {
    // means current cache is server (not ClientCache)
    iter = region.keySet().iterator();
  } else {
    // for ClientCache
    iter = region.keySetOnServer().iterator();
  }

  if (!iter.hasNext()) {
    String message = String.format(Locale.ROOT, "Region %s is empty, can't "
        + "autodetect type(s)", region.getName());
    throw new IllegalStateException(message);
  }

  final Object entry = region.get(iter.next());
  return createRelDataType(entry);
}
 
示例25
@BeforeAll
public static void setUp() throws Exception {
  Cache cache = POLICY.cache();
  Region<?, ?> bookMaster =  cache.<String, Object>createRegionFactory().create("BookMaster");
  new JsonLoader(bookMaster).loadClasspathResource("/book_master.json");

  Region<?, ?> bookCustomer =  cache.<String, Object>createRegionFactory().create("BookCustomer");
  new JsonLoader(bookCustomer).loadClasspathResource("/book_customer.json");

}
 
示例26
public void assertCustomersRegion(Region<?, ?> customers) {

		assertThat(customers).isNotNull();
		assertThat(customers.getName()).isEqualTo("Customers");
		assertThat(customers.getAttributes()).isNotNull();
		assertThat(customers.getAttributes().getDataPolicy()).isEqualTo(DataPolicy.EMPTY);
		assertThat(customers).hasSize(0);
	}
 
示例27
@Bean
public ApplicationRunner runner(CustomerRepository customerRepository, OrderRepository orderRepository,
		ProductRepository productRepository, @Qualifier("Products") Region<Long, Product> products) {
	return args -> {
		createCustomerData(customerRepository);

		createProducts(productRepository);

		createOrders(productRepository, orderRepository);

		log.info("Completed creating orders ");
	};
}
 
示例28
@Test
public void testExample() throws Exception {
  Example example = new Example();

  Region<String, String> outgoingRegion = mock(Region.class);
  Region<Integer, String> incomingRegion = mock(Region.class);

  final List<String> words = Arrays.asList(new String[] {"that", "teh"});
  when(outgoingRegion.sizeOnServer()).thenReturn(words.size());
  example.checkWords(incomingRegion, outgoingRegion, words);

  verify(incomingRegion).put(eq(0), eq(words.get(0)));
  verify(incomingRegion).put(eq(1), eq(words.get(1)));
}
 
示例29
public static void main(String[] args) throws LuceneQueryException {
  // connect to the locator using default port 10334
  ClientCache cache = new ClientCacheFactory().addPoolLocator("127.0.0.1", 10334)
      .set("log-level", "WARN").create();

  // create a local region that matches the server region
  Region<Integer, EmployeeData> region =
      cache.<Integer, EmployeeData>createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY)
          .create("example-region");

  insertValues(region);
  query(cache);
  queryNestedObject(cache);
  cache.close();
}
 
示例30
public static void main(String[] args) {
  // connect to the locator using default port 10334
  ClientCache cache = new ClientCacheFactory().addPoolLocator("127.0.0.1", 10334)
      .set("log-level", "WARN").create();

  Example example = new Example();

  // create a local region that matches the server region
  ClientRegionFactory<Integer, String> clientRegionFactory =
      cache.createClientRegionFactory(ClientRegionShortcut.PROXY);
  Region<Integer, String> region = clientRegionFactory.create("example-region");

  example.putEntries(region);
  cache.close();
}