@Test
  public void testTemplateOverridingStoreByValue() throws Exception {
    cacheManager =
        cachingProvider.getCacheManager(
            getClass()
                .getResource("/org/ehcache/docs/ehcache-jsr107-template-override.xml")
                .toURI(),
            getClass().getClassLoader());

    MutableConfiguration<Long, String> mutableConfiguration =
        new MutableConfiguration<Long, String>();
    mutableConfiguration.setTypes(Long.class, String.class);

    Cache<Long, String> myCache = null;
    myCache = cacheManager.createCache("anyCache", mutableConfiguration);
    myCache.put(1L, "foo");
    assertNotSame("foo", myCache.get(1L));
    assertTrue(myCache.getConfiguration(Configuration.class).isStoreByValue());

    myCache = cacheManager.createCache("byRefCache", mutableConfiguration);
    myCache.put(1L, "foo");
    assertSame("foo", myCache.get(1L));
    assertFalse(myCache.getConfiguration(Configuration.class).isStoreByValue());

    myCache = cacheManager.createCache("weirdCache1", mutableConfiguration);
    myCache.put(1L, "foo");
    assertNotSame("foo", myCache.get(1L));
    assertTrue(myCache.getConfiguration(Configuration.class).isStoreByValue());

    myCache = cacheManager.createCache("weirdCache2", mutableConfiguration);
    myCache.put(1L, "foo");
    assertSame("foo", myCache.get(1L));
    assertFalse(myCache.getConfiguration(Configuration.class).isStoreByValue());
  }
  @Test
  public void testMultiClusterMultipleClients() throws MalformedURLException, URISyntaxException {
    final String cacheName = "test";
    final String key1 = "key1";
    final String valuecm1 = "Value-is-cm1";
    final String valuecm2 = "Value-is-cm2";

    final HazelcastClientCachingProvider cachingProvider = new HazelcastClientCachingProvider();
    final CacheManager cm1 = cachingProvider.getCacheManager(uri1, null);
    final CacheManager cm2 = cachingProvider.getCacheManager(uri2, null);
    final CacheConfig<String, String> cacheConfig = new CacheConfig<String, String>();
    final Cache<String, String> cache1 = cm1.createCache(cacheName, cacheConfig);
    final Cache<String, String> cache2 = cm2.createCache(cacheName, cacheConfig);

    cache1.put(key1, valuecm1);
    cache2.put(key1, valuecm2);

    assertEquals(valuecm1, cache1.get(key1));
    assertEquals(valuecm2, cache2.get(key1));

    cachingProvider.close(uri1, null);
    cachingProvider.close(uri2, null);
    //        cm1.close();
    //        cm2.close();

    final CacheManager cm11 = cachingProvider.getCacheManager(uri1, null);

    final Cache<String, String> cache11 = cm11.getCache(cacheName);

    assertEquals(valuecm1, cache11.get(key1));

    cm11.close();
  }
  @Test
  public void testLatestAccessCacheMergePolicy() {
    String cacheName = randomMapName();
    Config config = newConfig();
    HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
    HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);

    TestMemberShipListener memberShipListener = new TestMemberShipListener(1);
    h2.getCluster().addMembershipListener(memberShipListener);
    TestLifeCycleListener lifeCycleListener = new TestLifeCycleListener(1);
    h2.getLifecycleService().addLifecycleListener(lifeCycleListener);

    closeConnectionBetween(h1, h2);

    assertOpenEventually(memberShipListener.latch);
    assertClusterSizeEventually(1, h1);
    assertClusterSizeEventually(1, h2);

    CachingProvider cachingProvider1 = HazelcastServerCachingProvider.createCachingProvider(h1);
    CachingProvider cachingProvider2 = HazelcastServerCachingProvider.createCachingProvider(h2);

    CacheManager cacheManager1 = cachingProvider1.getCacheManager();
    CacheManager cacheManager2 = cachingProvider2.getCacheManager();

    CacheConfig cacheConfig =
        newCacheConfig(cacheName, LatestAccessCacheMergePolicy.class.getName());

    Cache cache1 = cacheManager1.createCache(cacheName, cacheConfig);
    Cache cache2 = cacheManager2.createCache(cacheName, cacheConfig);

    // TODO We assume that until here and also while doing get/put, cluster is still splitted.
    // This assumptions seems fragile due to time sensitivity.

    cache1.put("key1", "value");
    assertEquals("value", cache1.get("key1")); // Access to record

    // Prevent updating at the same time
    sleepAtLeastMillis(1);

    cache2.put("key1", "LatestUpdatedValue");
    assertEquals("LatestUpdatedValue", cache2.get("key1")); // Access to record

    cache2.put("key2", "value2");
    assertEquals("value2", cache2.get("key2")); // Access to record

    // Prevent updating at the same time
    sleepAtLeastMillis(1);

    cache1.put("key2", "LatestUpdatedValue2");
    assertEquals("LatestUpdatedValue2", cache1.get("key2")); // Access to record

    assertOpenEventually(lifeCycleListener.latch);
    assertClusterSizeEventually(2, h1);
    assertClusterSizeEventually(2, h2);

    Cache cacheTest = cacheManager1.getCache(cacheName);
    assertEquals("LatestUpdatedValue", cacheTest.get("key1"));
    assertEquals("LatestUpdatedValue2", cacheTest.get("key2"));
  }
  // Issue https://github.com/hazelcast/hazelcast/issues/5865
  @Test
  public void testCompletionTestByPuttingAndRemovingFromDifferentNodes()
      throws InterruptedException {
    String cacheName = "simpleCache";

    CacheManager cacheManager1 = cachingProvider1.getCacheManager();
    CacheManager cacheManager2 = cachingProvider2.getCacheManager();

    CacheConfig<Integer, String> config = new CacheConfig<Integer, String>();
    final SimpleEntryListener<Integer, String> listener =
        new SimpleEntryListener<Integer, String>();
    MutableCacheEntryListenerConfiguration<Integer, String> listenerConfiguration =
        new MutableCacheEntryListenerConfiguration<Integer, String>(
            FactoryBuilder.factoryOf(listener), null, true, true);

    config.addCacheEntryListenerConfiguration(listenerConfiguration);

    Cache<Integer, String> cache1 = cacheManager1.createCache(cacheName, config);
    Cache<Integer, String> cache2 = cacheManager2.getCache(cacheName);

    assertNotNull(cache1);
    assertNotNull(cache2);

    Integer key1 = 1;
    String value1 = "value1";
    cache1.put(key1, value1);
    assertTrueEventually(
        new AssertTask() {
          @Override
          public void run() throws Exception {
            assertEquals(1, listener.created.get());
          }
        });

    Integer key2 = 2;
    String value2 = "value2";
    cache1.put(key2, value2);
    assertTrueEventually(
        new AssertTask() {
          @Override
          public void run() throws Exception {
            assertEquals(2, listener.created.get());
          }
        });

    Set<Integer> keys = new HashSet<Integer>();
    keys.add(key1);
    keys.add(key2);
    cache2.removeAll(keys);
    assertTrueEventually(
        new AssertTask() {
          @Override
          public void run() throws Exception {
            assertEquals(2, listener.removed.get());
          }
        });
  }
  @Test
  public void test_CacheReplicationOperation_serialization() throws Exception {
    TestHazelcastInstanceFactory factory = new TestHazelcastInstanceFactory(1);
    HazelcastInstance hazelcastInstance = factory.newHazelcastInstance();

    try {
      CachingProvider provider =
          HazelcastServerCachingProvider.createCachingProvider(hazelcastInstance);
      CacheManager manager = provider.getCacheManager();

      CompleteConfiguration configuration = new MutableConfiguration();
      Cache cache1 = manager.createCache("cache1", configuration);
      Cache cache2 = manager.createCache("cache2", configuration);
      Cache cache3 = manager.createCache("cache3", configuration);

      for (int i = 0; i < 1000; i++) {
        cache1.put("key" + i, i);
        cache2.put("key" + i, i);
        cache3.put("key" + i, i);
      }

      HazelcastInstanceProxy proxy = (HazelcastInstanceProxy) hazelcastInstance;

      Field original = HazelcastInstanceProxy.class.getDeclaredField("original");
      original.setAccessible(true);

      HazelcastInstanceImpl impl = (HazelcastInstanceImpl) original.get(proxy);
      NodeEngineImpl nodeEngine = impl.node.nodeEngine;
      CacheService cacheService = nodeEngine.getService(CacheService.SERVICE_NAME);

      int partitionCount = nodeEngine.getPartitionService().getPartitionCount();

      for (int partitionId = 0; partitionId < partitionCount; partitionId++) {
        CachePartitionSegment segment = cacheService.getSegment(partitionId);

        CacheReplicationOperation operation = new CacheReplicationOperation(segment, 1);
        Data serialized = service.toData(operation);
        try {
          service.toObject(serialized);
        } catch (Exception e) {
          throw new Exception("Partition: " + partitionId, e);
        }
      }

    } finally {
      factory.shutdownAll();
    }
  }
  @Test
  public void testJSRExample1() throws InterruptedException {
    final String cacheName = randomString();

    CacheManager cacheManager = cachingProvider1.getCacheManager();
    assertNotNull(cacheManager);

    assertNull(cacheManager.getCache(cacheName));

    CacheConfig<Integer, String> config = new CacheConfig<Integer, String>();
    Cache<Integer, String> cache = cacheManager.createCache(cacheName, config);
    assertNotNull(cache);

    assertTrueEventually(
        new AssertTask() {
          @Override
          public void run() throws Exception {
            CacheManager cm2 = cachingProvider2.getCacheManager();
            assertNotNull(cm2.getCache(cacheName));
          }
        });

    Integer key = 1;
    String value1 = "value";
    cache.put(key, value1);

    String value2 = cache.get(key);
    assertEquals(value1, value2);
    cache.remove(key);
    assertNull(cache.get(key));

    Cache<Integer, String> cache2 = cacheManager.getCache(cacheName);
    assertNotNull(cache2);

    key = 1;
    value1 = "value";
    cache.put(key, value1);

    value2 = cache.get(key);
    assertEquals(value1, value2);
    cache.remove(key);
    assertNull(cache.get(key));

    cacheManager.destroyCache(cacheName);
    cacheManager.close();
  }
  @Test
  public void testCustomCacheMergePolicy() {
    String cacheName = randomMapName();
    Config config = newConfig();
    HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
    HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);

    TestMemberShipListener memberShipListener = new TestMemberShipListener(1);
    h2.getCluster().addMembershipListener(memberShipListener);
    TestLifeCycleListener lifeCycleListener = new TestLifeCycleListener(1);
    h2.getLifecycleService().addLifecycleListener(lifeCycleListener);

    closeConnectionBetween(h1, h2);

    assertOpenEventually(memberShipListener.latch);
    assertClusterSizeEventually(1, h1);
    assertClusterSizeEventually(1, h2);

    CachingProvider cachingProvider1 = HazelcastServerCachingProvider.createCachingProvider(h1);
    CachingProvider cachingProvider2 = HazelcastServerCachingProvider.createCachingProvider(h2);

    CacheManager cacheManager1 = cachingProvider1.getCacheManager();
    CacheManager cacheManager2 = cachingProvider2.getCacheManager();

    CacheConfig cacheConfig = newCacheConfig(cacheName, CustomCacheMergePolicy.class.getName());

    Cache cache1 = cacheManager1.createCache(cacheName, cacheConfig);
    Cache cache2 = cacheManager2.createCache(cacheName, cacheConfig);

    // TODO We assume that until here and also while doing get/put, cluster is still splitted.
    // This assumptions seems fragile due to time sensitivity.

    String key = generateKeyOwnedBy(h1);
    cache1.put(key, "value");

    cache2.put(key, Integer.valueOf(1));

    assertOpenEventually(lifeCycleListener.latch);
    assertClusterSizeEventually(2, h1);
    assertClusterSizeEventually(2, h2);

    Cache cacheTest = cacheManager2.getCache(cacheName);
    assertNotNull(cacheTest.get(key));
    assertTrue(cacheTest.get(key) instanceof Integer);
  }
 public static void updateCacheValue(String jsonCacheName, String ckey, String results) {
   Cache cache = CacheController.getCache();
   Map<String, String> thisCache = (HashMap<String, String>) cache.get(jsonCacheName);
   if (thisCache == null) {
     thisCache = new HashMap<String, String>();
   }
   thisCache.put(ckey, results);
   cache.put(jsonCacheName, thisCache);
 }
 @Test
 public void testCachesDestroyFromOtherManagers() {
   CacheManager cacheManager = cachingProvider1.getCacheManager();
   CacheManager cacheManager2 = cachingProvider2.getCacheManager();
   MutableConfiguration configuration = new MutableConfiguration();
   final Cache c1 = cacheManager.createCache("c1", configuration);
   final Cache c2 = cacheManager2.createCache("c2", configuration);
   c1.put("key", "value");
   c2.put("key", "value");
   cacheManager.close();
   assertTrueAllTheTime(
       new AssertTask() {
         @Override
         public void run() throws Exception {
           c2.get("key");
         }
       },
       10);
 }
  /**
   * Populate cache with {@code 'facts'}, which in our case are {@link FactPurchase} objects.
   *
   * @param factCache Cache to populate.
   * @throws IgniteException If failed.
   */
  private static void populateFacts(Cache<Integer, FactPurchase> factCache) throws IgniteException {
    for (int i = 0; i < 100; i++) {
      int id = idGen++;

      DimStore store = rand(dataStore.values());
      DimProduct prod = rand(dataProduct.values());

      factCache.put(id, new FactPurchase(id, prod.getId(), store.getId(), (i + 1)));
    }
  }
 public static void invalidateCacheValue(String jsonCacheName, String ckey) {
   Cache cache = CacheController.getCache();
   Map<String, String> thisCache = (HashMap<String, String>) cache.get(jsonCacheName);
   if (thisCache != null) {
     thisCache.remove(ckey);
   } else {
     thisCache = new HashMap<String, String>();
   }
   cache.put(jsonCacheName, thisCache);
 }
Example #12
0
 @SuppressWarnings("unchecked")
 private void doPut(PayaraCacheKeyInvocationContext<CachePut> pctx) throws Throwable {
   CacheKeyGenerator generator = pctx.getGenerator();
   CacheResolverFactory resolverF = pctx.getFactory();
   CacheResolver cacheResolver = resolverF.getCacheResolver(pctx);
   Cache cache = cacheResolver.resolveCache(pctx);
   GeneratedCacheKey key = generator.generateCacheKey(pctx);
   Object value = pctx.getValueParameter().getValue();
   cache.put(key, value);
 }
 @Override
 protected void initApplicationContext() {
   super.initApplicationContext();
   if (jsonCacheName != null) {
     Cache cache = CacheController.getCache();
     Map<String, String> thisCache = new HashMap<String, String>();
     cache.put(jsonCacheName, thisCache);
     logcache.log(Level.FINE, "Recreating cache: {0}", jsonCacheName);
   }
 }
  @Test
  public void testPassThroughCacheMergePolicy() {
    String cacheName = randomMapName();
    Config config = newConfig();
    HazelcastInstance h1 = Hazelcast.newHazelcastInstance(config);
    HazelcastInstance h2 = Hazelcast.newHazelcastInstance(config);

    TestMemberShipListener memberShipListener = new TestMemberShipListener(1);
    h2.getCluster().addMembershipListener(memberShipListener);
    TestLifeCycleListener lifeCycleListener = new TestLifeCycleListener(1);
    h2.getLifecycleService().addLifecycleListener(lifeCycleListener);

    closeConnectionBetween(h1, h2);

    assertOpenEventually(memberShipListener.latch);
    assertClusterSizeEventually(1, h1);
    assertClusterSizeEventually(1, h2);

    CachingProvider cachingProvider1 = HazelcastServerCachingProvider.createCachingProvider(h1);
    CachingProvider cachingProvider2 = HazelcastServerCachingProvider.createCachingProvider(h2);

    CacheManager cacheManager1 = cachingProvider1.getCacheManager();
    CacheManager cacheManager2 = cachingProvider2.getCacheManager();

    CacheConfig cacheConfig =
        newCacheConfig(cacheName, PassThroughCacheMergePolicy.class.getName());

    Cache cache1 = cacheManager1.createCache(cacheName, cacheConfig);
    Cache cache2 = cacheManager2.createCache(cacheName, cacheConfig);

    String key = generateKeyOwnedBy(h1);
    cache1.put(key, "value");

    cache2.put(key, "passThroughValue");

    assertOpenEventually(lifeCycleListener.latch);
    assertClusterSizeEventually(2, h1);
    assertClusterSizeEventually(2, h2);

    Cache cacheTest = cacheManager2.getCache(cacheName);
    assertEquals("passThroughValue", cacheTest.get(key));
  }
  public void saveSession(Env env, SessionArrayValue session) {
    SessionArrayValue copy = (SessionArrayValue) session.copy(env);

    _sessions.put(session.getId(), copy);

    session.finish();

    if (_persistentStore != null) {
      _persistentStore.put(session.getId(), copy.encode(env));
    }
  }
Example #16
0
 @SuppressWarnings("unchecked")
 public Object put(Object arg0, Object arg1) {
   localCache.put((String) arg0, arg1);
   Object o = null;
   try {
     o = cache.put(arg0, arg1);
   } catch (Exception e) {
     LOGGER.error(e);
   }
   return o;
 }
  /**
   * Populate cache with {@code 'dimensions'} which in our case are {@link DimStore} and {@link
   * DimProduct} instances.
   *
   * @param dimCache Cache to populate.
   * @throws IgniteException If failed.
   */
  private static void populateDimensions(Cache<Integer, Object> dimCache) throws IgniteException {
    DimStore store1 = new DimStore(idGen++, "Store1", "12345", "321 Chilly Dr, NY");
    DimStore store2 = new DimStore(idGen++, "Store2", "54321", "123 Windy Dr, San Francisco");

    // Populate stores.
    dimCache.put(store1.getId(), store1);
    dimCache.put(store2.getId(), store2);

    dataStore.put(store1.getId(), store1);
    dataStore.put(store2.getId(), store2);

    // Populate products
    for (int i = 0; i < 20; i++) {
      int id = idGen++;

      DimProduct product = new DimProduct(id, "Product" + i, i + 1, (i + 1) * 10);

      dimCache.put(id, product);

      dataProduct.put(id, product);
    }
  }
  @Test
  public void testJCacheGettingStarted() {
    try (CachingProvider provider = Caching.getCachingProvider();
        CacheManager manager = provider.getCacheManager();
        Cache<String, String> cache =
            manager.createCache("testCache", new MutableConfiguration<>())) {
      cache.put("key", "value");
      assertThat(cache.get("key")).isEqualTo("value");

      cache.remove("key");
      assertThat(cache.get("key")).isNull();
    }
  }
 @SuppressWarnings("unchecked")
 @Override
 public Job find(Long scheduleId, Long id) {
   Object entityCacheKey = getEntityCacheKey(Job.class, getJobWideUniqueData(scheduleId, id));
   Job result = (Job) cache.get(entityCacheKey);
   if (result != null) {
     return result;
   }
   result = super.find(scheduleId, id);
   if (result != null) {
     cache.put(entityCacheKey, result);
   }
   return result;
 }
 @SuppressWarnings("unchecked")
 @Override
 public List<Key> getJobsByCronString(String cronString) {
   Object entityCacheKey = getEntityCacheKey(Job.class, cronString);
   List<Key> result = (List<Key>) cache.get(entityCacheKey);
   if (result != null) {
     return result;
   }
   result = super.getJobsByCronString(cronString);
   if (result != null) {
     ArrayList<Key> serializableList = new ArrayList<Key>(result.subList(0, result.size()));
     cache.put(entityCacheKey, serializableList);
   }
   return result;
 }
  @SuppressWarnings("unchecked")
  private void updateJobInScheduleCache(Job job) {
    Long scheduleId = job.getKey().getParent().getId();

    Object entityCacheKey = getEntityCacheKey(Schedule.class, scheduleId);

    Schedule schedule = (Schedule) cache.get(entityCacheKey);

    if (schedule == null) {
      return; //  Nothing to update
    }

    schedule.updateJob(job);

    cache.put(entityCacheKey, schedule);
  }
  @SuppressWarnings("unchecked")
  @Override
  public Object put(Object key, Object value) {
    map.put(key, value);
    try {
      return cache.put(key, value);
    } catch (MemcacheServiceException e) {
      //  TODO Split the value into smaller pieces and store them separately?
      logger.warn("Error putting value into cache", e);

      //  A value may be already in cache. We should remove it to avoid
      //  not synchronous duplicates there and here in local map.
      cache.remove(key);

      return null;
    }
  }
  protected void updateOptimisationsCache(
      DsLookupParameters parameters,
      IDataSet dataSet,
      List<ValueEval> fetchedValues,
      OperationEvaluationContext ec) {
    if (fetchedValues == null || parameters == null) {
      return;
    }

    DataSetOptimisationsCache caches =
        (DataSetOptimisationsCache)
            ec.getCustomEvaluationContext().get(DataSetOptimisationsCache.class);
    if (caches == null) {
      caches = this.external.getDataSetOptimisationsCache();
    }

    Cache<DsLookupParameters, List> cache = caches.getDataSetToDsLookupParameters();

    cache.put(parameters, fetchedValues);
  }
Example #24
0
  /**
   * Get the API key validated against the specified API
   *
   * @param context API context
   * @param apiKey API key to be validated
   * @param apiVersion API version number
   * @return An APIKeyValidationInfoDTO object
   * @throws APISecurityException If an error occurs while accessing backend services
   */
  public APIKeyValidationInfoDTO getKeyValidationInfo(
      String context,
      String apiKey,
      String apiVersion,
      String authenticationScheme,
      String clientDomain)
      throws APISecurityException {
    String cacheKey = apiKey + ":" + context + ":" + apiVersion + ":" + authenticationScheme;
    if (isGatewayAPIKeyValidationEnabled) {
      APIKeyValidationInfoDTO info = (APIKeyValidationInfoDTO) infoCache.get(cacheKey);
      if (info != null) {
        return info;
      }
    }

    // synchronized (apiKey.intern()) {
    // We synchronize on the API key here to allow concurrent processing
    // of different API keys - However when a burst of requests with the
    // same key is encountered, only one will be allowed to execute the logic,
    // and the rest will pick the value from the cache.
    //   info = (APIKeyValidationInfoDTO) infoCache.get(cacheKey);
    // if (info != null) {
    //   return info;
    // }
    APIKeyValidationInfoDTO info =
        doGetKeyValidationInfo(context, apiVersion, apiKey, authenticationScheme, clientDomain);
    if (info != null) {
      if (isGatewayAPIKeyValidationEnabled
          && clientDomain
              == null) { // save into cache only if, validation is correct and api is allowed for
                         // all domains
        infoCache.put(cacheKey, info);
      }
      return info;
    } else {
      throw new APISecurityException(
          APISecurityConstants.API_AUTH_GENERAL_ERROR, "API key validator returned null");
    }
    // }
  }
  @SuppressWarnings("unchecked")
  @Override
  public void update(Job job, boolean commitAfter) {
    super.update(job, commitAfter);
    Object entityCacheKey = getEntityCacheKey(Job.class, getJobWideUniqueData(job.getKey()));

    Job cachedJob = (Job) cache.get(entityCacheKey);

    if (cachedJob != null) {

      if (!cachedJob.getCronString().equals(job.getCronString())) {
        abandonJobsByCronStringCache(cachedJob.getCronString());
        abandonJobsByCronStringCache(job.getCronString());
      }

      cache.put(entityCacheKey, job);
    } else {
      abandonJobsByCronStringCache();
    }

    updateJobInScheduleCache(job);
  }
 @Test
 public void testCachesDestroy() {
   CacheManager cacheManager = cachingProvider1.getCacheManager();
   CacheManager cacheManager2 = cachingProvider2.getCacheManager();
   MutableConfiguration configuration = new MutableConfiguration();
   final Cache c1 = cacheManager.createCache("c1", configuration);
   final Cache c2 = cacheManager2.getCache("c1");
   c1.put("key", "value");
   cacheManager.destroyCache("c1");
   assertTrueEventually(
       new AssertTask() {
         @Override
         public void run() throws Exception {
           try {
             c2.get("key");
             throw new AssertionError("get should throw IllegalStateException");
           } catch (IllegalStateException e) {
             // ignored as expected
           }
         }
       });
 }
  @Test
  public void testCacheExpired() throws Exception {
    Configuration<String, String> configuration =
        new MutableConfiguration<String, String>()
            .setExpiryPolicyFactory(
                AccessedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 3)));

    try (CachingProvider provider = Caching.getCachingProvider();
        CacheManager manager = provider.getCacheManager();
        Cache<String, String> cache = manager.createCache("testCache", configuration)) {
      cache.put("key1", "value1");
      cache.put("key2", "value2");

      TimeUnit.SECONDS.sleep(1);

      cache.get("key2");

      TimeUnit.SECONDS.sleep(2);

      assertThat(cache.get("key1")).isNull();
      assertThat(cache.get("key2")).isEqualTo("value2");
    }
  }
  @Ignore
  @Test
  public void testWithHazelcastConfiguration() throws Exception {
    // wrong use!!

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    URI uri = classLoader.getResource("hazelcast-jcache.xml").toURI();

    try (CachingProvider provider = Caching.getCachingProvider();
        CacheManager manager = provider.getCacheManager(uri, classLoader);
        Cache<String, String> cache = manager.getCache("testCache")) {
      cache.put("key1", "value1");
      cache.put("key2", "value2");

      TimeUnit.SECONDS.sleep(1);

      cache.get("key2");

      TimeUnit.SECONDS.sleep(2);

      assertThat(cache.get("key1")).isNull();
      assertThat(cache.get("key2")).isEqualTo("value2");
    }
  }
Example #29
0
  public String getResourceAuthenticationScheme(
      String context, String apiVersion, String requestPath, String httpMethod) {

    String cacheKey = context + ":" + apiVersion;
    APIInfoDTO apiInfoDTO = null;
    if (isGatewayAPIKeyValidationEnabled) {
      apiInfoDTO = (APIInfoDTO) resourceCache.get(cacheKey);
    }

    if (apiInfoDTO == null) {
      apiInfoDTO = doGetAPIInfo(context, apiVersion);
      resourceCache.put(cacheKey, apiInfoDTO);
    }

    // Match the case where the direct api context is matched
    if ("/".equals(requestPath)) {
      String requestCacheKey = context + "/" + apiVersion + requestPath + ":" + httpMethod;

      // Get decision from cache.
      VerbInfoDTO matchingVerb = null;
      if (isGatewayAPIKeyValidationEnabled) {
        matchingVerb = (VerbInfoDTO) resourceCache.get(requestCacheKey);
      }
      // On a cache hit
      if (matchingVerb != null) {
        return matchingVerb.getAuthType();
      } else {
        for (ResourceInfoDTO resourceInfoDTO : apiInfoDTO.getResources()) {
          String urlPattern = resourceInfoDTO.getUrlPattern();

          // If the request patch is '/', it can only be matched with a resource whose url-context
          // is '/*'
          if ("/*".equals(urlPattern)) {
            for (VerbInfoDTO verbDTO : resourceInfoDTO.getHttpVerbs()) {
              if (verbDTO.getHttpVerb().equals(httpMethod)) {
                // Store verb in cache
                resourceCache.put(requestCacheKey, verbDTO);
                return verbDTO.getAuthType();
              }
            }
          }
        }
      }
    }

    // Remove the ending '/' from request
    requestPath = RESTUtils.trimTrailingSlashes(requestPath);

    while (requestPath.length() > 1) {

      String requestCacheKey = context + "/" + apiVersion + requestPath + ":" + httpMethod;

      // Get decision from cache.
      VerbInfoDTO matchingVerb = null;
      if (isGatewayAPIKeyValidationEnabled) {
        matchingVerb = (VerbInfoDTO) resourceCache.get(requestCacheKey);
      }

      // On a cache hit
      if (matchingVerb != null) {
        return matchingVerb.getAuthType();
      }
      // On a cache miss
      else {
        for (ResourceInfoDTO resourceInfoDTO : apiInfoDTO.getResources()) {
          String urlPattern = resourceInfoDTO.getUrlPattern();
          if (urlPattern.endsWith("/*")) {
            // Remove the ending '/*'
            urlPattern = urlPattern.substring(0, urlPattern.length() - 2);
          }
          // If the urlPattern ends with a '/', remove that as well.
          urlPattern = RESTUtils.trimTrailingSlashes(urlPattern);

          if (requestPath.endsWith(urlPattern)) {

            for (VerbInfoDTO verbDTO : resourceInfoDTO.getHttpVerbs()) {
              if (verbDTO.getHttpVerb().equals(httpMethod)) {
                // Store verb in cache
                resourceCache.put(requestCacheKey, verbDTO);
                return verbDTO.getAuthType();
              }
            }
          }
        }
      }

      // Remove the section after the last occurrence of the '/' character
      int index = requestPath.lastIndexOf("/");
      requestPath = requestPath.substring(0, index <= 0 ? 0 : index);
    }
    // nothing found. return the highest level of security
    return APIConstants.NO_MATCHING_AUTH_SCHEME;
  }
  @Test(timeout = 5000L)
  public void testCacheLoaderAsyncLoadAll() throws InterruptedException {
    final AtomicInteger loads = new AtomicInteger();

    final CacheLoader<String, Integer> cacheLoader =
        new CacheLoader<String, Integer>() {
          @Override
          public Integer load(String key) throws CacheLoaderException {
            loads.incrementAndGet();

            return Integer.valueOf(key);
          }

          @Override
          public Map<String, Integer> loadAll(Iterable<? extends String> keys)
              throws CacheLoaderException {
            throw new UnsupportedOperationException("Not supported yet.");
          }
        };

    final AtomicBoolean completed = new AtomicBoolean(false);

    final CompletionListener completionListener =
        new CompletionListener() {
          @Override
          public void onCompletion() {
            completed.set(true);
          }

          @Override
          public void onException(Exception e) {
            System.err.println(e);
          }
        };

    try (CachingProvider cachingProvider =
        Caching.getCachingProvider(GuavaCachingProvider.class.getName())) {
      CacheManager cacheManager = cachingProvider.getCacheManager();

      MutableConfiguration<String, Integer> custom = new MutableConfiguration<>();

      custom.setStoreByValue(false);
      custom.setTypes(String.class, Integer.class);
      custom.setReadThrough(true);
      custom.setCacheLoaderFactory(
          new Factory<CacheLoader<String, Integer>>() {
            @Override
            public CacheLoader<String, Integer> create() {
              return cacheLoader;
            }
          });

      Cache<String, Integer> loadingCache = cacheManager.createCache("loadingCache", custom);

      loadingCache.put("1", 1);
      loadingCache.put("2", 2);
      loadingCache.put("3", 3);

      Set<String> keys = Sets.newHashSet("1", "2", "3", "4", "5", "6");

      loadingCache.loadAll(keys, false, completionListener);

      while (!completed.get()) {
        Thread.sleep(250);
      }

      assertEquals(3, loads.getAndSet(0));

      completed.set(false);

      loadingCache.loadAll(keys, true, completionListener);

      while (!completed.get()) {
        Thread.sleep(250);
      }

      assertEquals(6, loads.get());
      assertEquals(Integer.valueOf(1), loadingCache.getAndRemove("1"));
      assertEquals(Integer.valueOf(2), loadingCache.getAndRemove("2"));
      assertEquals(Integer.valueOf(3), loadingCache.getAndRemove("3"));
      assertEquals(Integer.valueOf(4), loadingCache.getAndRemove("4"));
      assertEquals(Integer.valueOf(5), loadingCache.getAndRemove("5"));
      assertEquals(Integer.valueOf(6), loadingCache.getAndRemove("6"));
    }
  }