javax.cache.Caching Java Examples

The following examples show how to use javax.cache.Caching. 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: JSRExamplesTest.java    From blazingcache with Apache License 2.0 6 votes vote down vote up
@Test
public void testJSRExample1() {

    CachingProvider cachingProvider = Caching.getCachingProvider();
    Properties p = new Properties();
    try (CacheManager cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), cachingProvider.getDefaultClassLoader(), p)) {
        MutableConfiguration<String, Integer> config
                = new MutableConfiguration<String, Integer>()
                .setTypes(String.class, Integer.class)
                .setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(ONE_HOUR))
                .setStatisticsEnabled(true);

        Cache<String, Integer> cache = cacheManager.createCache("simpleCache", config);

        String key = "key";
        Integer value1 = 1;
        cache.put("key", value1);
        Integer value2 = cache.get(key);
        assertEquals(value1, value2);
        cache.remove(key);
        assertNull(cache.get(key));
    }
}
 
Example #2
Source File: CacheWriterTest.java    From blazingcache with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoWriteThrough() {
    CachingProvider cachingProvider = Caching.getCachingProvider();
    Properties p = new Properties();
    try (CacheManager cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), cachingProvider.getDefaultClassLoader(), p)) {
        MockCacheWriter external = new MockCacheWriter();
        MutableConfiguration<String, String> config
                = new MutableConfiguration<String, String>()
                .setTypes(String.class, String.class)
                .setCacheWriterFactory(new FactoryBuilder.SingletonFactory<>(external))
                .setWriteThrough(false);

        Cache<String, String> cache = cacheManager.createCache("simpleCache", config);
        String key = "key";
        cache.put(key, "some_datum");

        String result = external.database.get(key);
        assertNull(result);
    }
}
 
Example #3
Source File: EntityCacheTest.java    From requery with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerializeGetPut() {
    CachingProvider provider = Caching.getCachingProvider();
    CacheManager cacheManager = provider.getCacheManager();

    EntityCache cache = new EntityCacheBuilder(Models.DEFAULT)
            .useReferenceCache(false)
            .useSerializableCache(true)
            .useCacheManager(cacheManager)
            .build();

    Person p = new Person();
    p.setName("Alice");
    p.setUUID(UUID.randomUUID());
    p.setAddress(new Address());
    p.getAddress().setType(AddressType.HOME);

    int id = 100;
    cache.put(Person.class, id, p);

    Person d = cache.get(Person.class, id);
    Assert.assertNotNull(d);
    Assert.assertNotSame(p, d);
    Assert.assertEquals(p.getName(), d.getName());
    Assert.assertEquals(p.getUUID(), d.getUUID());
}
 
Example #4
Source File: ReactorTest.java    From requery with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws SQLException {
    Platform platform = new HSQL();
    CommonDataSource dataSource = DatabaseType.getDataSource(platform);
    EntityModel model = io.requery.test.model.Models.DEFAULT;

    CachingProvider provider = Caching.getCachingProvider();
    CacheManager cacheManager = provider.getCacheManager();
    Configuration configuration = new ConfigurationBuilder(dataSource, model)
        .useDefaultLogging()
        .setWriteExecutor(Executors.newSingleThreadExecutor())
        .setEntityCache(new EntityCacheBuilder(model)
            .useReferenceCache(true)
            .useSerializableCache(true)
            .useCacheManager(cacheManager)
            .build())
        .build();

    SchemaModifier tables = new SchemaModifier(configuration);
    tables.createTables(TableCreationMode.DROP_CREATE);
    data = new ReactorEntityStore<>(new EntityDataStore<Persistable>(configuration));
}
 
Example #5
Source File: ManagementTest.java    From blazingcache with Apache License 2.0 6 votes vote down vote up
@Test
public void testCacheStatisticsInvokeEntryProcessorRemove() throws Exception {
    CachingProvider cachingProvider = Caching.getCachingProvider();
    Properties p = new Properties();
    try (CacheManager cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(), cachingProvider.getDefaultClassLoader(), p)) {
        MutableConfiguration<Long, String> config
                = new MutableConfiguration<Long, String>()
                .setTypes(Long.class, String.class)
                .setStatisticsEnabled(true)
                .setManagementEnabled(true);
        BlazingCacheCache<Long, String> cache = cacheManager.createCache("simpleCache", config).unwrap(BlazingCacheCache.class);

        cache.put(1l, "Sooty");
        String result = cache.invoke(1l, new RemoveEntryProcessor<Long, String, String>(true));
        assertEquals(result, "Sooty");
        assertEquals((int) 1, (int) cache.getStatisticsMXBean().getCacheHits());
        assertEquals((int) 1, (int) cache.getStatisticsMXBean().getCachePuts());
        assertEquals((int) 1, (int) cache.getStatisticsMXBean().getCacheRemovals());
    }
}
 
Example #6
Source File: JPAModelTest.java    From requery with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws SQLException {
    CommonDataSource dataSource = DatabaseType.getDataSource(new H2());
    EntityModel model = Models.JPA;

    CachingProvider provider = Caching.getCachingProvider();
    CacheManager cacheManager = provider.getCacheManager();
    Configuration configuration = new ConfigurationBuilder(dataSource, model)
        .useDefaultLogging()
        .setEntityCache(new EntityCacheBuilder(model)
            .useReferenceCache(true)
            .useSerializableCache(true)
            .useCacheManager(cacheManager)
            .build())
        .build();
    data = new EntityDataStore<>(configuration);
    SchemaModifier tables = new SchemaModifier(configuration);
    tables.dropTables();
    TableCreationMode mode = TableCreationMode.CREATE;
    System.out.println(tables.createTablesString(mode));
    tables.createTables(mode);
}
 
Example #7
Source File: OpenJPAJCacheDataCacheManager.java    From commons-jcs with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize(final OpenJPAConfiguration conf, final ObjectValue dataCache, final ObjectValue queryCache)
{
    super.initialize(conf, dataCache, queryCache);
    provider = Caching.getCachingProvider();

    final Properties properties = new Properties();
    final Map<String, Object> props = conf.toProperties(false);
    if (props != null)
    {
        for (final Map.Entry<?, ?> entry : props.entrySet())
        {
            if (entry.getKey() != null && entry.getValue() != null)
            {
                properties.setProperty(entry.getKey().toString(), entry.getValue().toString());
            }
        }
    }

    final String uri = properties.getProperty("jcache.uri", provider.getDefaultURI().toString());
    cacheManager = provider.getCacheManager(URI.create(uri), provider.getDefaultClassLoader(), properties);
}
 
Example #8
Source File: SharedMemoryMatchingManager.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
private static Cache<Integer, SharedMemorySubscriptionStorage> getTenantIDInMemorySubscriptionStorageCache() {
    if (cacheInit) {
        return Caching.getCacheManagerFactory()
        		.getCacheManager(SharedMemoryCacheConstants.INMEMORY_EVENT_CACHE_MANAGER)
        		.getCache(SharedMemoryCacheConstants.TENANT_ID_INMEMORY_SUBSCRIPTION_STORAGE_CACHE);
    } else {
        CacheManager cacheManager = Caching.getCacheManagerFactory()
        		.getCacheManager(SharedMemoryCacheConstants.INMEMORY_EVENT_CACHE_MANAGER);
        cacheInit = true;
        log.info("Tenant ID InMemory Subscription Storage Cache Initialized");
        return cacheManager.<Integer, SharedMemorySubscriptionStorage>createCacheBuilder(
        		SharedMemoryCacheConstants.TENANT_ID_INMEMORY_SUBSCRIPTION_STORAGE_CACHE).
                setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
                		SharedMemoryCacheConstants.CACHE_INVALIDATION_TIME)).
                setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
                		SharedMemoryCacheConstants.CACHE_INVALIDATION_TIME)).
                setStoreByValue(false).build();

    }
}
 
Example #9
Source File: SharedMemorySubscriptionStorage.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
public static Cache<String, String> getSubscriptionIDTopicNameCache() {
    if (tenantIDInMemorySubscriptionStorageCacheInit) {
        return Caching.getCacheManagerFactory()
        		.getCacheManager(SharedMemoryCacheConstants.INMEMORY_EVENT_CACHE_MANAGER)
        		.getCache(SharedMemoryCacheConstants.SUBSCRIPTION_ID_TOPIC_NAME_CACHE);
    } else {
        CacheManager cacheManager = Caching.getCacheManagerFactory()
        		.getCacheManager(SharedMemoryCacheConstants.INMEMORY_EVENT_CACHE_MANAGER);
        tenantIDInMemorySubscriptionStorageCacheInit = true;

        return cacheManager.<String, String>createCacheBuilder(SharedMemoryCacheConstants.SUBSCRIPTION_ID_TOPIC_NAME_CACHE).
                setExpiry(CacheConfiguration.ExpiryType.MODIFIED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
                		SharedMemoryCacheConstants.CACHE_INVALIDATION_TIME)).
                setExpiry(CacheConfiguration.ExpiryType.ACCESSED, new CacheConfiguration.Duration(TimeUnit.SECONDS,
                		SharedMemoryCacheConstants.CACHE_INVALIDATION_TIME)).
                setStoreByValue(false).build();

    }
}
 
Example #10
Source File: JCacheTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testJson() throws InterruptedException, IllegalArgumentException, URISyntaxException, IOException {
    RedisProcess runner = new RedisRunner()
            .nosave()
            .randomDir()
            .port(6311)
            .run();
    
    URL configUrl = getClass().getResource("redisson-jcache.json");
    Config cfg = Config.fromJSON(configUrl);
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JavaTimeModule());
    cfg.setCodec(new TypedJsonJacksonCodec(String.class, LocalDateTime.class, objectMapper));
    
    Configuration<String, LocalDateTime> config = RedissonConfiguration.fromConfig(cfg);
    Cache<String, LocalDateTime> cache = Caching.getCachingProvider().getCacheManager()
            .createCache("test", config);
    
    LocalDateTime t = LocalDateTime.now();
    cache.put("1", t);
    Assert.assertEquals(t, cache.get("1"));
    
    cache.close();
    runner.stop();
}
 
Example #11
Source File: CachingProviderClassLoaderTest.java    From cache2k with Apache License 2.0 6 votes vote down vote up
/**
 * The default CacheManager is the same as the CacheManager using the default
 * CachingProvider URI.
 */
@Test
public void getCacheManagerDefaultURI() {
  ClassLoader contextLoader = Thread.currentThread().getContextClassLoader();

  CachingProvider provider = Caching.getCachingProvider(contextLoader);

  CacheManager manager = provider.getCacheManager();
  assertEquals(provider.getDefaultURI(), manager.getURI());

  // using a different ClassLoader
  ClassLoader otherLoader = new MyClassLoader(contextLoader);
  CachingProvider otherProvider = Caching.getCachingProvider(otherLoader);
  assertNotSame(provider, otherProvider);

  CacheManager otherManager = otherProvider.getCacheManager();
  assertNotSame(manager, otherManager);
  assertEquals(otherProvider.getDefaultURI(), otherManager.getURI());
}
 
Example #12
Source File: JCacheTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsync() throws Exception {
    RedisProcess runner = new RedisRunner()
            .nosave()
            .randomDir()
            .port(6311)
            .run();
    
    URL configUrl = getClass().getResource("redisson-jcache.json");
    Config cfg = Config.fromJSON(configUrl);
    
    Configuration<String, String> config = RedissonConfiguration.fromConfig(cfg);
    Cache<String, String> cache = Caching.getCachingProvider().getCacheManager()
            .createCache("test", config);

    CacheAsync<String, String> async = cache.unwrap(CacheAsync.class);
    async.putAsync("1", "2").get();
    assertThat(async.getAsync("1").get()).isEqualTo("2");
    
    cache.close();
    runner.stop();
}
 
Example #13
Source File: WorkflowExecutorFactoryTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Before
public void init() {
    System.setProperty(CARBON_HOME, "");
    carbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    PowerMockito.when(carbonContext.getTenantDomain()).thenReturn(tenantDomain);
    PowerMockito.when(carbonContext.getTenantId()).thenReturn(tenantID);
    cache = Mockito.mock(Cache.class);
    CacheManager cacheManager = Mockito.mock(CacheManager.class);
    PowerMockito.mockStatic(Caching.class);
    Mockito.when(Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER)).thenReturn(cacheManager);
    Mockito.when(cacheManager.getCache(APIConstants.WORKFLOW_CACHE_NAME)).thenReturn(cache);
    tenantWorkflowConfigHolder = Mockito.mock(TenantWorkflowConfigHolder.class);
    workflowExecutorFactory = WorkflowExecutorFactory.getInstance();
}
 
Example #14
Source File: OAuth2Test.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
private void createRedirectedClient(final int httpPort) throws URISyntaxException {
    final CachingProvider provider = Caching.getCachingProvider();
    final CacheManager cacheManager = provider.getCacheManager(
            ClassLoaderUtils.getResource("default-oauth2.jcs", OAuth2Test.class).toURI(),
            Thread.currentThread().getContextClassLoader());
    Cache<String, org.apache.cxf.rs.security.oauth2.common.Client> cache;
    try {
        cache = cacheManager
                .createCache(JCacheCodeDataProvider.CLIENT_CACHE_KEY, new MutableConfiguration<String, org.apache.cxf.rs.security.oauth2.common.Client>()
                        .setTypes(String.class, org.apache.cxf.rs.security.oauth2.common.Client.class)
                        .setStoreByValue(true));
    } catch (final RuntimeException re) {
        cache = cacheManager.getCache(JCacheCodeDataProvider.CLIENT_CACHE_KEY, String.class, org.apache.cxf.rs.security.oauth2.common.Client.class);
    }
    final org.apache.cxf.rs.security.oauth2.common.Client value = new org.apache.cxf.rs.security.oauth2.common.Client("c1", "cpwd", true);
    value.setRedirectUris(singletonList("http://localhost:" + httpPort + "/redirected"));
    cache.put("c1", value);
}
 
Example #15
Source File: SimpleCacheManager.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
private void checkCacheManager() throws InterruptedException {
    mutex.acquire();
    if (cacheManager == null) {
        provider = Caching.getCachingProvider("org.ehcache.jsr107.EhcacheCachingProvider",
                this.getClass().getClassLoader());
        cacheManager = provider.getCacheManager();
    }
    if (repoCacheManager == null && repoProvider != null) {
        repoCacheManager = repoProvider.getCacheManager();
    }
    mutex.release();
}
 
Example #16
Source File: TestCollector.java    From javamelody with Apache License 2.0 5 votes vote down vote up
/** Test.
 * @throws SchedulerException e */
@Test
public void testToString() throws SchedulerException {
	final Collector collector = createCollectorWithOneCounter();
	assertToStringNotEmpty("collector", collector);
	assertToStringNotEmpty("java", new JavaInformations(null, false));
	assertToStringNotEmpty("thread",
			new ThreadInformations(Thread.currentThread(),
					Arrays.asList(Thread.currentThread().getStackTrace()), 100, 1000, false,
					Parameters.getHostAddress()));
	assertToStringNotEmpty("session", new SessionInformations(new SessionTestImpl(true), true));
	assertToStringNotEmpty("memory", new MemoryInformations());
	CacheManager.getInstance().addCache("testToString");
	try {
		assertToStringNotEmpty("cache", new CacheInformations(
				CacheManager.getInstance().getEhcache("testToString"), false));
	} finally {
		CacheManager.getInstance().shutdown();
	}
	final MutableConfiguration<Object, Object> conf = new MutableConfiguration<Object, Object>();
	conf.setManagementEnabled(true);
	conf.setStatisticsEnabled(true);
	Caching.getCachingProvider().getCacheManager().createCache("cache", conf);
	try {
		assertToStringNotEmpty("cache", new JCacheInformations("cache"));
	} finally {
		Caching.getCachingProvider().getCacheManager().close();
	}
	final Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
	final JobDetail job = new JobDetail("job", null, JobTestImpl.class);
	assertToStringNotEmpty("job", new JobInformations(job, null, scheduler));
	assertToStringNotEmpty("connectionInfos", new ConnectionInformations());
}
 
Example #17
Source File: CachingTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void isSupported() {
  CachingProvider provider = Caching.getCachingProvider();

  OptionalFeature[] features = OptionalFeature.values();
  for (OptionalFeature feature : features) {
    boolean value = provider.isSupported(feature);
    Logger.getLogger(getClass().getName()).info("Optional feature " + feature + " supported=" + value);
  }
}
 
Example #18
Source File: JCacheSessionDataStorage.java    From pippo with Apache License 2.0 5 votes vote down vote up
/**
 * Create a cache with name and expiry policy with idle time.
 *
 * @param name name of cache
 * @param idleTime idle time in seconds
 * @return the cache with name and expiry policy with idle time
 */
protected Cache<String, SessionData> create(String name, long idleTime) {
    return Caching
            .getCachingProvider()
            .getCacheManager()
            .createCache(
                    name,
                    new MutableConfiguration<String, SessionData>()
                    .setTypes(String.class, SessionData.class)
                    .setExpiryPolicyFactory(
                            TouchedExpiryPolicy.factoryOf(
                                    new Duration(
                                            TimeUnit.SECONDS,
                                            idleTime))));
}
 
Example #19
Source File: InfinispanJCache.java    From infinispan-simple-tutorials with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
   // Construct a simple local cache manager with default configuration
   CachingProvider jcacheProvider = Caching.getCachingProvider();
   CacheManager cacheManager = jcacheProvider.getCacheManager();
   MutableConfiguration<String, String> configuration = new MutableConfiguration<>();
   configuration.setTypes(String.class, String.class);
   // create a cache using the supplied configuration
   Cache<String, String> cache = cacheManager.createCache("myCache", configuration);
   // Store a value
   cache.put("key", "value");
   // Retrieve the value and print it out
   System.out.printf("key = %s\n", cache.get("key"));
   // Stop the cache manager and release all resources
   cacheManager.close();
}
 
Example #20
Source File: JCacheTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreatedExpiryPolicy() throws Exception {
    RedisProcess runner = new RedisRunner()
            .nosave()
            .randomDir()
            .port(6311)
            .run();

    URL configUrl = getClass().getResource("redisson-jcache.json");
    Config cfg = Config.fromJSON(configUrl);

    MutableConfiguration c = new MutableConfiguration();
    c.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(MILLISECONDS, 500)));
    Configuration<String, String> config = RedissonConfiguration.fromConfig(cfg, c);
    Cache<String, String> cache = Caching.getCachingProvider().getCacheManager()
            .createCache("test", config);

    cache.put("1", "2");
    Thread.sleep(500);
    assertThat(cache.get("1")).isNull();
    cache.put("1", "3");
    assertThat(cache.get("1")).isEqualTo("3");
    Thread.sleep(500);
    assertThat(cache.get("1")).isNull();

    cache.put("1", "4");
    assertThat(cache.get("1")).isEqualTo("4");
    Thread.sleep(100);
    cache.put("1", "5");
    assertThat(cache.get("1")).isEqualTo("5");

    cache.close();
    runner.stop();
}
 
Example #21
Source File: APIConfigMediaTypeHandler.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private void clearConfigCache() {
    Cache workflowCache = Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).
            getCache(APIConstants.WORKFLOW_CACHE_NAME);
    String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    String cacheName = tenantDomain + "_" + APIConstants.WORKFLOW_CACHE_NAME;
    if (workflowCache.containsKey(cacheName)) {
        workflowCache.remove(cacheName);
    }

}
 
Example #22
Source File: StoreByReferenceTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@After
public void teardown() {
  try {
    Caching.getCachingProvider().close();
  } catch (CacheException e) {
    //expected
  }
}
 
Example #23
Source File: CacheUtils.java    From hazelcast-simulator with Apache License 2.0 5 votes vote down vote up
public static CachingProvider getCachingProvider(HazelcastInstance hazelcastInstance) {
    if (isMemberNode(hazelcastInstance)) {
        return Caching.getCachingProvider("com.hazelcast.cache.impl.HazelcastServerCachingProvider");
    } else {
        return Caching.getCachingProvider("com.hazelcast.client.cache.impl.HazelcastClientCachingProvider");
    }
}
 
Example #24
Source File: TCKCacheManagerTest.java    From blazingcache with Apache License 2.0 5 votes vote down vote up
@Test
public void getCacheManager_nonNullProperties() {
    CachingProvider provider = Caching.getCachingProvider();
    Properties properties = new Properties();

    assertSame(provider.getCacheManager(),
            provider.getCacheManager(provider.getDefaultURI(), provider.getDefaultClassLoader(), new Properties()));

    try (CacheManager manager = provider.getCacheManager();) {
        assertEquals(properties, manager.getProperties());
    }
}
 
Example #25
Source File: CacheTest.java    From commons-jcs with Apache License 2.0 5 votes vote down vote up
@Test
public void accessExpiry() throws InterruptedException
{
    final CachingProvider cachingProvider = Caching.getCachingProvider();
    final CacheManager cacheManager = cachingProvider.getCacheManager(cachingProvider.getDefaultURI(),
            Thread.currentThread().getContextClassLoader(),
            cachingProvider.getDefaultProperties());
    final Cache<Integer, Integer> cache = cacheManager.createCache(
            "test",
            new MutableConfiguration<Integer, Integer>()
                    .setStoreByValue(false)
                    .setStatisticsEnabled(true)
                    .setManagementEnabled(true)
                    .setTypes(Integer.class, Integer.class)
                    .setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(new Duration(TimeUnit.MILLISECONDS, 500))));

    try {
        cache.put(1, 2);
        cache.get(1);
        Thread.sleep(650);
        assertFalse(cache.containsKey(1));
        cache.put(1, 2);
        for (int i = 0; i < 3; i++) { // we update the last access to force the idle time and lastaccess to be synced
            Thread.sleep(250);
            assertTrue("iteration: " + Integer.toString(i), cache.containsKey(1));
        }
        assertTrue(cache.containsKey(1));
        Thread.sleep(650);
        assertFalse(cache.containsKey(1));
    } finally {
        cacheManager.close();
        cachingProvider.close();
    }
}
 
Example #26
Source File: DefaultClaimsRetrieverTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws UserStoreException {
    PowerMockito.mockStatic(Caching.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    PowerMockito.when(Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER)).thenReturn(cacheManager);
    Mockito.when(apiManagerConfigurationService.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService())
            .thenReturn(apiManagerConfigurationService);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantUserRealm(TENANT_ID)).thenReturn(userRealm);
    Mockito.when(userRealm.getClaimManager()).thenReturn(claimManager);
    Mockito.when(userRealm.getUserStoreManager()).thenReturn(userStoreManager);
}
 
Example #27
Source File: JCacheStore.java    From enkan with Eclipse Public License 1.0 5 votes vote down vote up
public JCacheStore(Factory<ExpiryPolicy> expiryPolicyFactory) {
    CachingProvider cachingProvider = Caching.getCachingProvider();
    CacheManager cacheManager = cachingProvider.getCacheManager();

    MutableConfiguration<String, Serializable> config = new MutableConfiguration<String, Serializable>()
            .setTypes(String.class, Serializable.class);
    if (expiryPolicyFactory != null) {
        config.setExpiryPolicyFactory(expiryPolicyFactory);
    }
    cache = cacheManager.getCache("session", String.class, Serializable.class);
    if (cache == null)
        cache = cacheManager.createCache("session", config);
}
 
Example #28
Source File: CachingTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void getCacheManager_nullUriParameter() {
  CachingProvider provider = Caching.getCachingProvider();
  final URI NULL_URI = null;
  CacheManager manager = provider.getCacheManager(NULL_URI, provider.getDefaultClassLoader(), null);
  assertNotNull(manager);
  assertEquals(provider.getDefaultURI(), manager.getURI());
}
 
Example #29
Source File: WebsocketUtilTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    System.setProperty("carbon.home", "jhkjn");
    PowerMockito.mockStatic(MultitenantUtils.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn("abc.com");
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    APIManagerConfiguration apiManagerConfiguration = Mockito.mock(APIManagerConfiguration.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfiguration()).thenReturn(apiManagerConfiguration);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.API_KEY_VALIDATOR_URL))
            .thenReturn(apiKeyValidationURL);
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.GATEWAY_TOKEN_CACHE_ENABLED))
            .thenReturn("true");
    Mockito.when(apiManagerConfiguration.getFirstProperty(APIConstants.REMOVE_OAUTH_HEADERS_FROM_MESSAGE))
            .thenReturn("true");
    cacheManager = Mockito.mock(CacheManager.class);
    PowerMockito.mockStatic(Caching.class);
    PowerMockito.when(Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER)).thenReturn(cacheManager);
    gwKeyCache = Mockito.mock(Cache.class);
    gwTokenCache = Mockito.mock(Cache.class);
    Mockito.when(cacheManager.getCache(APIConstants.GATEWAY_KEY_CACHE_NAME)).thenReturn(gwKeyCache);
    Mockito.when(cacheManager.getCache(APIConstants.GATEWAY_TOKEN_CACHE_NAME)).thenReturn(gwTokenCache);
}
 
Example #30
Source File: CachingProviderTest.java    From cache2k with Apache License 2.0 5 votes vote down vote up
@Test
public void getCacheManagerUsingDefaultURI() {
  CachingProvider provider = Caching.getCachingProvider();

  CacheManager manager1 = provider.getCacheManager();
  assertNotNull(manager1);
  assertEquals(provider.getDefaultURI(), manager1.getURI());

  CacheManager manager2 = provider.getCacheManager();
  assertSame(manager1, manager2);
}