org.apache.shiro.cache.Cache Java Examples

The following examples show how to use org.apache.shiro.cache.Cache. 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: ApiKeyRealmTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Test
public void simpleNowEmpty() {
    Cache<String, RolePermissionSet> cache = _underTest.getAvailableRolesCache();
    assertEquals(cache.size(), 0, "precondition: cache is empty");
    Permission p1 = mock(Permission.class);
    when(p1.toString()).thenReturn("p1");
    when(_permissionManager.getPermissions(PermissionIDs.forRole("role"))).thenReturn(Sets.newHashSet(p1));
    Collection<Permission> resultPerms = _underTest.getRolePermissions("role");
    assertEquals(resultPerms.iterator().next(), p1, "should have the first permission we added");
    assertEquals(cache.size(), 1, "side effect: cache has one element");
    when(_permissionManager.getPermissions(PermissionIDs.forRole("role"))).thenReturn(Sets.<Permission>newHashSet());
    cache.clear();
    resultPerms = _underTest.getRolePermissions("role");
    assertTrue(resultPerms.isEmpty(), "now should have empty");
    assertEquals(cache.size(), 1, "side effect: cache has empty permission");
}
 
Example #2
Source File: RedisCacheManager.java    From mumu with Apache License 2.0 6 votes vote down vote up
@Override
public <K, V> Cache<K, V> getCache(String name) throws CacheException {
    logger.debug("获取名称为: " + name + " 的RedisCache实例");

    Cache c = caches.get(name);

    if (c == null) {

        // create a new cache instance
        c = new RedisCache<K, V>(jedisClient, keyPrefix);

        // add it to the cache collection
        caches.put(name, c);
    }
    return c;
}
 
Example #3
Source File: RealmManagerImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Looks up registered {@link AuthorizingRealm}s, and clears their authz caches if they have it set.
 */
private void clearAuthzRealmCaches() {
  // NOTE: we don't need to iterate all the Sec Managers, they use the same Realms, so one is fine.
  Collection<Realm> realms = realmSecurityManager.getRealms();
  if (realms != null) {
    for (Realm realm : realms) {
      if (realm instanceof AuthorizingRealm) {
        Cache<Object, AuthorizationInfo> cache = ((AuthorizingRealm) realm).getAuthorizationCache();
        if (cache != null) {
          log.debug("Clearing cache: {}", cache);
          cache.clear();
        }
      }
    }
  }
}
 
Example #4
Source File: RealmManagerImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Looks up registered {@link AuthenticatingRealm}s, and clears their authc caches if they have it set.
 */
private void clearAuthcRealmCaches() {
  // NOTE: we don't need to iterate all the Sec Managers, they use the same Realms, so one is fine.
  Collection<Realm> realms = realmSecurityManager.getRealms();
  if (realms != null) {
    for (Realm realm : realms) {
      if (realm instanceof AuthenticatingRealm) {
        Cache<Object, AuthenticationInfo> cache = ((AuthenticatingRealm) realm).getAuthenticationCache();
        if (cache != null) {
          log.debug("Clearing cache: {}", cache);
          cache.clear();
        }
      }
    }
  }
}
 
Example #5
Source File: SpringCacheManager.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Override
public <K, V> Cache<K, V> getCache(String cacheName) throws CacheException {
	SpringCache<K,V> cache = this.CACHES.get(cacheName);
	if (cache != null) {
		return cache;
	}
	else {
		synchronized (this.CACHES) {
			cache = this.CACHES.get(cacheName);
			if (cache == null) {
				org.springframework.cache.Cache springCache = this.delegator.getCache(cacheName);
				cache = new SpringCache(cacheName,springCache);
				this.CACHES.put(cacheName, cache);
			}
			return cache;
		}
	}
}
 
Example #6
Source File: ApiKeyRealmTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Test
public void pseudoConcurrentNewExists() {
    Cache<String, RolePermissionSet> cache = _underTest.getAvailableRolesCache();
    assertEquals(cache.size(), 0, "precondition: cache is empty");
    Permission p1 = mock(Permission.class);
    when(p1.toString()).thenReturn("p1");
    Permission p2 = mock(Permission.class);
    when(p2.toString()).thenReturn("p2");
    when(_permissionManager.getPermissions(PermissionIDs.forRole("role"))).thenReturn(Sets.newHashSet(p1), Sets.newHashSet(p2));
    Collection<Permission> resultPerms = _underTest.getRolePermissions("role");
    assertEquals(resultPerms.iterator().next(), p1, "should have the first permission we added");
    assertEquals(cache.size(), 1, "side effect: cache has one element");
    resultPerms = _underTest.getRolePermissions("role");
    assertEquals(resultPerms.iterator().next(), p2, "should have the last permission we added");
    assertEquals(cache.size(), 1, "side effect: cache has one element");
}
 
Example #7
Source File: ShiroCustomRealm.java    From phone with Apache License 2.0 6 votes vote down vote up
/**
 * 清除所有用户授权信息缓存.
 */
public void clearAllCachedAuthorizationInfo() {
	if (logger.isDebugEnabled()) {
		logger.debug("clearAllCachedAuthorizationInfo() - start"); //$NON-NLS-1$
	}

	Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
	if (cache != null) {
		for (Object key : cache.keys()) {
			cache.remove(key);
		}
	}

	if (logger.isDebugEnabled()) {
		logger.debug("clearAllCachedAuthorizationInfo() - end"); //$NON-NLS-1$
	}
}
 
Example #8
Source File: ApiKeyRealmTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Test
public void pseudoConcurrentNewThenCacheFlush() {
    Cache<String, RolePermissionSet> cache = _underTest.getAvailableRolesCache();
    assertEquals(cache.size(), 0, "precondition: cache is empty");
    Permission p1 = mock(Permission.class);
    when(p1.toString()).thenReturn("p1");
    Permission p2 = mock(Permission.class);
    when(p2.toString()).thenReturn("p2");
    when(_permissionManager.getPermissions(PermissionIDs.forRole("role")))
            .thenReturn(Sets.newHashSet(p1))
            .thenReturn(Sets.newHashSet(p2));
    Collection<Permission> resultPerms = _underTest.getRolePermissions("role");
    assertEquals(resultPerms.iterator().next(), p1, "should have the last permission we added");
    assertEquals(cache.size(), 1, "side effect: cache has one element");
    cache.clear();
    resultPerms = _underTest.getRolePermissions("role");
    assertEquals(resultPerms.iterator().next(), p2, "should again have the last permission we added");
    assertEquals(cache.size(), 1, "side effect: cache again has one element");
}
 
Example #9
Source File: ApiKeyRealm.java    From emodb with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the permissions for a role.  If possible the permissions are cached for efficiency.
 */
protected Collection<Permission> getRolePermissions(String role) {
    if (role == null) {
        return null;
    }
    Cache<String, RolePermissionSet> cache = getAvailableRolesCache();

    if (cache == null) {
        return _permissionReader.getPermissions(PermissionIDs.forRole(role));
    }

    RolePermissionSet rolePermissionSet = cache.get(role);

    if (rolePermissionSet == null) {
        Set<Permission> permissions = _permissionReader.getPermissions(PermissionIDs.forRole(role));
        rolePermissionSet = new SimpleRolePermissionSet(permissions);
        cache.put(role, rolePermissionSet);
    }

    return rolePermissionSet.permissions();
}
 
Example #10
Source File: EhcacheShiroManager.java    From ehcache-shiro with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public <K, V> Cache<K, V> getCache(String name) throws CacheException {
  log.trace("Acquiring EhcacheShiro instance named [{}]", name);

  try {
    org.ehcache.Cache<Object, Object> cache = ensureCacheManager().getCache(name, Object.class, Object.class);

    if (cache == null) {
      log.info("Cache with name {} does not yet exist.  Creating now.", name);
      cache = createCache(name);
      log.info("Added EhcacheShiro named [{}]", name);
    } else {
      log.info("Using existing EhcacheShiro named [{}]", name);
    }

    return new EhcacheShiro<K, V>(cache);
  } catch (MalformedURLException e) {
    throw new CacheException(e);
  }
}
 
Example #11
Source File: ApiKeyRealm.java    From emodb with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the AuthorizationInfo that matches a token.  This method is only called if the info is not already
 * cached by the realm, so this method does not need to perform any further caching.
 */
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

    AuthorizationInfo authorizationInfo = getUncachedAuthorizationInfoFromPrincipals(principals);

    Cache<String, AuthorizationInfo> idAuthorizationCache = getAvailableIdAuthorizationCache();
    if (idAuthorizationCache != null) {
        // Proactively cache any ID authorization info not already in cache
        for (PrincipalWithRoles principal : getPrincipalsFromPrincipalCollection(principals)) {
            if (idAuthorizationCache.get(principal.getId()) == null) {
                cacheAuthorizationInfoById(principal.getId(), authorizationInfo);
            }
        }
    }

    return authorizationInfo;
}
 
Example #12
Source File: ShiroJCacheManagerAdapter.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@VisibleForTesting
<K, V> javax.cache.Cache<K, V> maybeCreateCache(final String name) {
  if (Objects.equals(ACTIVE_SESSION_CACHE_NAME, name)) {
    // shiro's session cache needs to never expire:
    // http://shiro.apache.org/session-management.html#ehcache-session-cache-configuration
    return cacheHelperProvider.get().maybeCreateCache(name, EternalExpiryPolicy.factoryOf());
  }
  else {
    Time timeToLive = Optional.ofNullable(System.getProperty(name + ".timeToLive"))
        .map(Time::parse)
        .orElse(defaultTimeToLive.get());
    return cacheHelperProvider.get().maybeCreateCache(name,
        CreatedExpiryPolicy.factoryOf(new Duration(timeToLive.getUnit(), timeToLive.getValue())));
  }
}
 
Example #13
Source File: ApiKeyRealm.java    From emodb with Apache License 2.0 5 votes vote down vote up
/**
 * If possible, this method caches the authorization info for an API key by its ID.  This may be called
 * either by an explicit call to get the authorization info by ID or as a side effect of loading the
 * authorization info by API key and proactive caching by ID.
 */
private void cacheAuthorizationInfoById(String id, AuthorizationInfo authorizationInfo) {
    Cache<String, AuthorizationInfo> idAuthorizationCache = getAvailableIdAuthorizationCache();

    if (idAuthorizationCache != null) {
        idAuthorizationCache.put(id, authorizationInfo);
    }
}
 
Example #14
Source File: SpringContextHelper.java    From MultimediaDesktop with Apache License 2.0 5 votes vote down vote up
public static <K, V> Cache<K, V> getMemcache(String name) {
	CacheManagerApi cacheManager = getBean("cacheManager",
			CacheManagerApi.class);
	if (cacheManager == null) {
		return null;
	}
	return cacheManager.getCache(name);
}
 
Example #15
Source File: ShiroJdbcRealm.java    From jee-universal-bms with Apache License 2.0 5 votes vote down vote up
/**
 * 清除所有用户授权信息缓存.
 */
public void clearAllCachedAuthorizationInfo() {
    Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
    if (cache != null) {
        for (Object key : cache.keys()) {
            cache.remove(key);
        }
    }
}
 
Example #16
Source File: RedisCacheManagerTest.java    From shiro-redis with MIT License 5 votes vote down vote up
@Test
public void testGetCache() {
    Cache cache = redisCacheManager.getCache("testCache1");
    Cache cache1 = redisCacheManager.getCache("testCache1");
    assertThat(cache,is(cache1));

    redisCacheManager.setKeyPrefix("testRedisManager1:");
    Cache cache2 = redisCacheManager.getCache("testCache2");
    assertThat(cache2.getClass().getName(), is("org.crazycake.shiro.RedisCache"));

    RedisCache redisCache2 = (RedisCache) cache2;
    assertThat(redisCache2.getKeyPrefix(), is("testRedisManager1:testCache2:"));
}
 
Example #17
Source File: RedisCacheManager.java    From hunt-admin with Apache License 2.0 5 votes vote down vote up
@Override
public <K, V> Cache<K, V> getCache(String name) throws CacheException {
    if (!StringUtils.hasText(name)) {
        throw new IllegalArgumentException("Cache name cannot be null or empty.");
    }
    log.debug("redis cache manager get cache name is :{}", name);
    Cache cache = (Cache) redisTemplate.opsForValue().get(name);
    if (cache == null) {
        cache = new RedisCache<>(redisTemplate);
        redisTemplate.opsForValue().set(SystemConstant.shiro_cache_prefix + name, cache);
    }
    return cache;
}
 
Example #18
Source File: shiroDbRealm.java    From PhrackCTF-Platform-Personal with Apache License 2.0 5 votes vote down vote up
/**
 * 清除所有用户授权信息缓存.
 */
public void clearAllCachedAuthorizationInfo() {
	Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
	if (cache != null) {
		for (Object key : cache.keys()) {
			cache.remove(key);
		}
	}
}
 
Example #19
Source File: ApiKeyRealm.java    From emodb with Apache License 2.0 5 votes vote down vote up
protected Cache<String, AuthorizationInfo> getAvailableIdAuthorizationCache() {
    if (getCacheManager() == null) {
        return null;
    }

    if (_idAuthorizationCache == null) {
        String cacheName = getIdAuthorizationCacheName();
        _idAuthorizationCache = getCacheManager().getCache(cacheName);
    }
    return _idAuthorizationCache;
}
 
Example #20
Source File: ApiKeyRealmTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Test
public void pseudoConcurrentNewAndCacheFlush() {
    final Cache<String, RolePermissionSet> cache = _underTest.getAvailableRolesCache();
    assertEquals(cache.size(), 0, "precondition: cache is empty");
    final Permission p1 = mock(Permission.class);
    when(p1.toString()).thenReturn("p1");
    final Permission p2 = mock(Permission.class);
    when(p2.toString()).thenReturn("p2");
    when(_permissionManager.getPermissions(PermissionIDs.forRole("role")))
            .thenReturn(Sets.newHashSet(p1))
            .thenAnswer(new Answer<Set<Permission>>() {
                @Override
                public Set<Permission> answer(InvocationOnMock invocationOnMock) throws Throwable {
                    cache.clear();
                    return Sets.newHashSet(p2);
                }
            })
            .thenReturn(Sets.newHashSet(p2));
    Permission resultPerm = _underTest.getRolePermissions("role").iterator().next();
    assertEquals(resultPerm, p1, "should have permission p1");
    resultPerm = _underTest.getRolePermissions("role").iterator().next();
    assertEquals(resultPerm, p2, "should have permission p2");
    resultPerm = _underTest.getRolePermissions("role").iterator().next();
    assertEquals(resultPerm, p2, "should have permission p2");
    assertNotNull(cache.get("role"), "Cached value for role should have been present");
    assertEquals(cache.get("role").permissions(), ImmutableSet.of(p2), "Cached values incorrect");
}
 
Example #21
Source File: ApiKeyRealm.java    From emodb with Apache License 2.0 5 votes vote down vote up
protected Cache<String, RolePermissionSet> getAvailableRolesCache() {
    if(getCacheManager() == null) {
        return null;
    }

    if (_rolesCache == null) {
        String cacheName = getRolesCacheName();
        _rolesCache = getCacheManager().getCache(cacheName);
    }
    return _rolesCache;
}
 
Example #22
Source File: shiroDbRealm.java    From PhrackCTF-Platform-Team with Apache License 2.0 5 votes vote down vote up
/**
 * 清除所有用户授权信息缓存.
 */
public void clearAllCachedAuthorizationInfo() {
	Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
	if (cache != null) {
		for (Object key : cache.keys()) {
			cache.remove(key);
		}
	}
}
 
Example #23
Source File: MemCacheUtil.java    From MultimediaDesktop with Apache License 2.0 5 votes vote down vote up
public static Object getCacheValueObject(String key) {
	Cache<String, Object> cache = SpringContextHelper
			.getMemcache(SessionKeyConstant.SYSTEM_MEMCACHE_KEY);
	if (cache == null) {
		return null;
	}
	return cache.get(key);
}
 
Example #24
Source File: RedisCacheManager.java    From shiro-redis with MIT License 5 votes vote down vote up
@Override
public <K, V> Cache<K, V> getCache(String name) throws CacheException {
	logger.debug("get cache, name=" + name);

	Cache cache = caches.get(name);

	if (cache == null) {
		cache = new RedisCache<K, V>(redisManager, keySerializer, valueSerializer, keyPrefix + name + ":", expire, principalIdFieldName);
		caches.put(name, cache);
	}
	return cache;
}
 
Example #25
Source File: EhcacheShiro.java    From ehcache-shiro with Apache License 2.0 5 votes vote down vote up
public Collection<V> values() {
  return new EhcacheCollectionWrapper<V>(this, cache) {
    @Override
    public Iterator<V> iterator() {
      return new EhcacheIterator<K, V, V>(cache.iterator()) {
        protected V getNext(Iterator<org.ehcache.Cache.Entry<K, V>> cacheIterator) {
          return cacheIterator.next().getValue();
        }
      };
    }
  };
}
 
Example #26
Source File: EhcacheShiro.java    From ehcache-shiro with Apache License 2.0 5 votes vote down vote up
public EhcacheShiro(org.ehcache.Cache cache) {
  if (cache == null) {
    throw new IllegalArgumentException("Cache argument cannot be null.");
  }

  this.cache = cache;
}
 
Example #27
Source File: EhcacheSetWrapper.java    From ehcache-shiro with Apache License 2.0 5 votes vote down vote up
EhcacheSetWrapper(Cache shiroCache, org.ehcache.Cache ehcacheCache) {
  delegate = new EhcacheCollectionWrapper<E>(shiroCache, ehcacheCache) {
    @Override
    public Iterator<E> iterator() {
      throw new IllegalStateException("Should not use this iterator");
    }
  };
}
 
Example #28
Source File: CacheUtils.java    From easyweb with Apache License 2.0 5 votes vote down vote up
/**
 * 获得一个Cache,没有则显示日志。
 * @param cacheName
 * @return
 */
private static Cache<String, Object> getCache(String cacheName){
	Cache<String, Object> cache = cacheManager.getCache(cacheName);
	if (cache == null){
		throw new RuntimeException("当前系统中没有定义“"+cacheName+"”这个缓存。");
	}
	return cache;
}
 
Example #29
Source File: CacheUtils.java    From easyweb with Apache License 2.0 5 votes vote down vote up
/**
 * 从缓存中移除所有
 * @param cacheName
 */
public static void removeAll(String cacheName) {
	Cache<String, Object> cache = getCache(cacheName);
	Set<String> keys = cache.keys();
	for (Iterator<String> it = keys.iterator(); it.hasNext();){
		cache.remove(it.next());
	}
	logger.info("清理缓存: {} => {}", cacheName, keys);
}
 
Example #30
Source File: EhcacheShiro.java    From ehcache-shiro with Apache License 2.0 5 votes vote down vote up
public Set<K> keys() {
  return new EhcacheSetWrapper<K>(this, cache) {
    @Override
    public Iterator<K> iterator() {
      return new EhcacheIterator<K, V, K>(cache.iterator()) {

        protected K getNext(Iterator<org.ehcache.Cache.Entry<K, V>> cacheIterator) {
          return cacheIterator.next().getKey();
        }
      };
    }
  };
}