org.infinispan.Cache Java Examples

The following examples show how to use org.infinispan.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: ConcurrencyVersioningTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static void endBatch(Cache<String, String> cache) {
    boolean commit = true;
    try {
        if (cache.getAdvancedCache().getTransactionManager().getStatus() == Status.STATUS_ACTIVE) {
            if (commit) {
                cache.getAdvancedCache().getTransactionManager().commit();

            } else {
                cache.getAdvancedCache().getTransactionManager().rollback();

            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #2
Source File: AbstractSessionCacheCommand.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected void doRunCacheCommand(KeycloakSession session, Cache<String, SessionEntityWrapper> cache) {
    String realmName = getArg(1);
    String clientId = getArg(2);
    String username = getArg(3);
    int count = getIntArg(4);
    int batchCount = getIntArg(5);

    BatchTaskRunner.runInBatches(0, count, batchCount, session.getKeycloakSessionFactory(), (KeycloakSession batchSession, int firstInIteration, int countInIteration) -> {
        RealmModel realm = batchSession.realms().getRealmByName(realmName);
        ClientModel client = realm.getClientByClientId(clientId);
        UserModel user = batchSession.users().getUserByUsername(username, realm);

        for (int i=0 ; i<countInIteration ; i++) {
            UserSessionModel userSession = session.sessions().createUserSession(realm, user, username, "127.0.0.1", "form", false, null, null);

            session.sessions().createClientSession(userSession.getRealm(), client, userSession);
        }

        log.infof("Created '%d' sessions started from offset '%d'", countInIteration, firstInIteration);
    });

    log.infof("Created all '%d' sessions", count);
}
 
Example #3
Source File: InfoConsoleCommand.java    From hacep with Apache License 2.0 6 votes vote down vote up
@Override
public boolean execute(UI console, Iterator<String> args) throws IllegalParametersException {
    try {
        String cacheName = args.next();
        Cache<Key, Object> cache = application.getCacheManager().getCache(cacheName, false);

        if (cache != null) {
            console.println(buildInfo(cache));
        } else {
            console.println("Cache " + cacheName + " not existent");
        }

    } catch (NoSuchElementException e) {
        console.println(application.info());
    }
    return true;

}
 
Example #4
Source File: InfinispanSingleUseTokenStoreProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void lazyInit(KeycloakSession session) {
    if (tokenCache == null) {
        synchronized (this) {
            if (tokenCache == null) {
                InfinispanConnectionProvider connections = session.getProvider(InfinispanConnectionProvider.class);
                Cache cache = connections.getCache(InfinispanConnectionProvider.ACTION_TOKEN_CACHE);

                RemoteCache remoteCache = InfinispanUtil.getRemoteCache(cache);

                if (remoteCache != null) {
                    LOG.debugf("Having remote stores. Using remote cache '%s' for single-use cache of token", remoteCache.getName());
                    this.tokenCache = () -> {
                        // Doing this way as flag is per invocation
                        return remoteCache.withFlags(Flag.FORCE_RETURN_VALUE);
                    };
                } else {
                    LOG.debugf("Not having remote stores. Using normal cache '%s' for single-use cache of token", cache.getName());
                    this.tokenCache = () -> {
                        return cache;
                    };
                }
            }
        }
    }
}
 
Example #5
Source File: AbstractSessionCacheCommand.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected void doRunCacheCommand(KeycloakSession session, Cache<String, SessionEntityWrapper> cache) {
    String realmName = getArg(1);
    int count = getIntArg(2);
    int batchCount = getIntArg(3);

    BatchTaskRunner.runInBatches(0, count, batchCount, session.getKeycloakSessionFactory(), (KeycloakSession batchSession, int firstInIteration, int countInIteration) -> {
        for (int i=0 ; i<countInIteration ; i++) {
            UserSessionEntity userSession = new UserSessionEntity();
            String id = KeycloakModelUtils.generateId();

            userSession.setId(id);
            userSession.setRealmId(realmName);

            userSession.setLastSessionRefresh(Time.currentTime());
            cache.put(id, new SessionEntityWrapper(userSession));
        }

        log.infof("Created '%d' sessions started from offset '%d'", countInIteration, firstInIteration);
    });

    log.infof("Created all '%d' sessions", count);
}
 
Example #6
Source File: InfinispanSessionCacheIdMapperUpdater.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private static void addSsoCacheCrossDcListener(Cache<String, String[]> ssoCache, SsoSessionCacheListener listener) {
    if (ssoCache.getCacheConfiguration().persistence() == null) {
        return;
    }

    final Set<RemoteStore> stores = getRemoteStores(ssoCache);
    if (stores == null || stores.isEmpty()) {
        return;
    }

    LOG.infov("Listening for events on remote stores configured for cache {0}", ssoCache.getName());

    for (RemoteStore store : stores) {
        store.getRemoteCache().addClientListener(listener);
    }
}
 
Example #7
Source File: InfinispanListen.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
   // Construct a simple local cache manager with default configuration
   DefaultCacheManager cacheManager = new DefaultCacheManager();
   // Define local cache configuration
   cacheManager.defineConfiguration("local", new ConfigurationBuilder().build());
   // Obtain the local cache
   Cache<String, String> cache = cacheManager.getCache("local");
   // Register a listener
   cache.addListener(new MyListener());
   // Store some values
   cache.put("key1", "value1");
   cache.put("key2", "value2");
   cache.put("key1", "newValue");
   // Stop the cache manager and release all resources
   cacheManager.stop();
}
 
Example #8
Source File: ConcurrencyVersioningTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that if remove executes before put, then put still succeeds.
 *
 * @throws Exception
 */
@Test
public void testGetRemovePutOnNonExisting() throws Exception {
    final DefaultCacheManager cacheManager = getVersionedCacheManager();
    ExecutorService executor = Executors.newSingleThreadExecutor();

    RemoveThread removeThread = new RemoveThread(cacheManager);

    Cache<String, String> cache = cacheManager.getCache(InfinispanConnectionProvider.REALM_CACHE_NAME);
    cache.remove("key");
    startBatch(cache);
    cache.get("key");
    executor.execute(removeThread);
    removeThread.getLatch().await();
    cache.putForExternalRead("key", "value1");
    endBatch(cache);
    Assert.assertEquals(cache.get("key"), "value1");
    Assert.assertTrue(removeThread.isSuccess());
}
 
Example #9
Source File: InfinispanKeycloakTransaction.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public <K, V> void remove(Cache<K, V> cache, K key) {
    log.tracev("Adding cache operation: {0} on {1}", CacheOperation.REMOVE, key);

    Object taskKey = getTaskKey(cache, key);

    // TODO:performance Eventual performance optimization could be to skip "cache.remove" if item was added in this transaction (EG. authenticationSession valid for single request due to automatic SSO login)
    tasks.put(taskKey, new CacheTask() {

        @Override
        public void execute() {
            decorateCache(cache).remove(key);
        }

        @Override
        public String toString() {
            return String.format("CacheTask: Operation 'remove' for key %s", key);
        }

    });
}
 
Example #10
Source File: ConcurrencyJDGRemoveSessionTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private static Thread createWorker(Cache<String, SessionEntityWrapper<UserSessionEntity>> cache, int threadId) {
    System.out.println("Retrieved cache: " + threadId);

    RemoteCache remoteCache = InfinispanUtil.getRemoteCache(cache);

    if (threadId == 1) {
        remoteCache1 = remoteCache;
    } else {
        remoteCache2 = remoteCache;
    }

    AtomicInteger counter = threadId ==1 ? successfulListenerWrites : successfulListenerWrites2;
    HotRodListener listener = new HotRodListener(cache, remoteCache, counter);
    remoteCache.addClientListener(listener);

    return new RemoteCacheWorker(remoteCache, threadId);
    //return new CacheWorker(cache, threadId);
}
 
Example #11
Source File: ConcurrencyJDGRemoteCacheClientListenersTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static void createItems(Cache<String, Integer> cache, int myThreadId) {
    for (Map.Entry<String, EntryInfo> entry : state.entrySet()) {
        String cacheKey = entry.getKey();
        Integer value = entry.getValue().val.get();

        cache.put(cacheKey, value);
    }

    System.out.println("Worker creating finished: " + myThreadId);
}
 
Example #12
Source File: CrossDCLastSessionRefreshStoreFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public CrossDCLastSessionRefreshStore createAndInit(KeycloakSession kcSession, Cache<String, SessionEntityWrapper<UserSessionEntity>> cache,
                                                    long timerIntervalMs, int maxIntervalBetweenMessagesSeconds, int maxCount, boolean offline) {
    String eventKey = offline ? LSR_OFFLINE_PERIODIC_TASK_NAME :  LSR_PERIODIC_TASK_NAME;
    CrossDCLastSessionRefreshStore store = createStoreInstance(maxIntervalBetweenMessagesSeconds, maxCount, eventKey);

    // Register listener
    ClusterProvider cluster = kcSession.getProvider(ClusterProvider.class);
    cluster.registerListener(eventKey, new CrossDCLastSessionRefreshListener(kcSession, cache, offline));

    // Setup periodic timer check
    setupPeriodicTimer(kcSession, store, timerIntervalMs, eventKey);

    return store;
}
 
Example #13
Source File: InfinispanNotificationsManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static InfinispanNotificationsManager create(KeycloakSession session, Cache<String, Serializable> workCache, String myAddress, String mySite, Set<RemoteStore> remoteStores) {
    RemoteCache workRemoteCache = null;

    if (!remoteStores.isEmpty()) {
        RemoteStore remoteStore = remoteStores.iterator().next();
        workRemoteCache = remoteStore.getRemoteCache();

        if (mySite == null) {
            throw new IllegalStateException("Multiple datacenters available, but site name is not configured! Check your configuration");
        }
    }

    ExecutorService listenersExecutor = workRemoteCache==null ? null : session.getProvider(ExecutorsProvider.class).getExecutor("work-cache-event-listener");
    InfinispanNotificationsManager manager = new InfinispanNotificationsManager(workCache, workRemoteCache, myAddress, mySite, listenersExecutor);

    // We need CacheEntryListener for communication within current DC
    workCache.addListener(manager.new CacheEntryListener());
    logger.debugf("Added listener for infinispan cache: %s", workCache.getName());

    // Added listener for remoteCache to notify other DCs
    if (workRemoteCache != null) {
        workRemoteCache.addClientListener(manager.new HotRodListener(workRemoteCache));
        logger.debugf("Added listener for HotRod remoteStore cache: %s", workRemoteCache.getName());
    }

    return manager;
}
 
Example #14
Source File: RootAuthenticationSessionAdapter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public RootAuthenticationSessionAdapter(KeycloakSession session, InfinispanAuthenticationSessionProvider provider,
                                        Cache<String, RootAuthenticationSessionEntity> cache, RealmModel realm,
                                        RootAuthenticationSessionEntity entity) {
    this.session = session;
    this.provider = provider;
    this.cache = cache;
    this.realm = realm;
    this.entity = entity;
}
 
Example #15
Source File: InfinispanKeyGenerator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private <K> KeyAffinityService<K> createKeyAffinityService(Cache<K, ?> cache, KeyGenerator<K> keyGenerator) {
    // SingleThreadExecutor is recommended due it needs the single thread and leave it in the WAITING state
    return KeyAffinityServiceFactory.newLocalKeyAffinityService(
            cache,
            keyGenerator,
            Executors.newSingleThreadExecutor(),
            16);
}
 
Example #16
Source File: InfinispanKeycloakTransaction.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public <K, V> V get(Cache<K, V> cache, K key) {
    Object taskKey = getTaskKey(cache, key);
    CacheTask current = tasks.get(taskKey);
    if (current != null) {
        if (current instanceof CacheTaskWithValue) {
            return ((CacheTaskWithValue<V>) current).getValue();
        }
        return null;
    }

    // Should we have per-transaction cache for lookups?
    return cache.get(key);
}
 
Example #17
Source File: AbstractSessionCacheCommand.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void doRunCacheCommand(KeycloakSession session, Cache<String, SessionEntityWrapper> cache) {
    UserSessionEntity userSession = new UserSessionEntity();
    String id = getArg(1);

    userSession.setId(id);
    userSession.setRealmId(getArg(2));

    userSession.setLastSessionRefresh(Time.currentTime());
    cache.put(id, new SessionEntityWrapper(userSession));
}
 
Example #18
Source File: ReplicatedServer.java    From unitime with Apache License 2.0 5 votes vote down vote up
@Override
public void unload() {
	super.unload();
	removeCache(iCourseForId);
	removeCache(iCourseForName);
	removeCache(iStudentTable);
	removeCache(iOfferingTable);
	removeCache(iOfferingRequests);
	removeCache(iExpectations);
	removeCache(iOfferingLocks);
	removeCache(iInstructedOfferings);
	removeCache((Cache<String, Object>)iProperties);
}
 
Example #19
Source File: InfinispanRegistry.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * @return gets the registry cache
 */
private Cache<Object, Object> getCache() {
    if (cache != null) {
        return cache;
    }
    
    try {
        InitialContext ic = new InitialContext();
        CacheContainer container = (CacheContainer) ic.lookup(cacheContainer);
        cache = container.getCache(cacheName);
        return cache;
    } catch (NamingException e) {
        throw new RuntimeException(e);
    }
}
 
Example #20
Source File: CacheCommands.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void printCache(Cache<Object, Object> cache) {
    int size = cache.size();
    log.infof("Cache %s, size: %d", cache.getName(), size);

    if (size > 50) {
        log.info("Skip printing cache records due to big size");
    } else {
        for (Map.Entry<Object, Object> entry : cache.entrySet()) {
            log.infof("%s=%s", entry.getKey(), entry.getValue());
        }
    }
}
 
Example #21
Source File: AllConsoleCommand.java    From hacep with Apache License 2.0 5 votes vote down vote up
@Override
public boolean execute(UI console, Iterator<String> args) throws IllegalParametersException {

    String cacheName = args.next();
    Cache<Key, Object> cache = application.getCacheManager().getCache(cacheName, false);

    if (cache != null) {
        jdgUtility.valuesFromKeys(cache).forEach(console::println);
        console.println(cacheName + " Cache Size: " + cache.size() + "\n");
    } else {
        console.println("Cache " + cacheName + " not existent");
    }
    return true;
}
 
Example #22
Source File: ConcurrencyJDGRemoteCacheClientListenersTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static Worker createWorker(int threadId) {
    EmbeddedCacheManager manager = new TestCacheManagerFactory().createManager(threadId, InfinispanConnectionProvider.WORK_CACHE_NAME, RemoteStoreConfigurationBuilder.class);
    Cache<String, Integer> cache = manager.getCache(InfinispanConnectionProvider.WORK_CACHE_NAME);

    System.out.println("Retrieved cache: " + threadId);

    RemoteStore remoteStore = cache.getAdvancedCache().getComponentRegistry().getComponent(PersistenceManager.class).getStores(RemoteStore.class).iterator().next();
    HotRodListener listener = new HotRodListener(cache, threadId);
    remoteStore.getRemoteCache().addClientListener(listener);

    return new Worker(cache, threadId);
}
 
Example #23
Source File: InfinispanUserSessionProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void loadPersistentSessions(final KeycloakSessionFactory sessionFactory, final int maxErrors, final int sessionsPerSegment) {
    log.debug("Start pre-loading userSessions from persistent storage");

    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            InfinispanConnectionProvider connections = session.getProvider(InfinispanConnectionProvider.class);
            Cache<String, Serializable> workCache = connections.getCache(InfinispanConnectionProvider.WORK_CACHE_NAME);

            InfinispanCacheInitializer ispnInitializer = new InfinispanCacheInitializer(sessionFactory, workCache,
                    new OfflinePersistentUserSessionLoader(sessionsPerSegment), "offlineUserSessions", sessionsPerSegment, maxErrors);

            // DB-lock to ensure that persistent sessions are loaded from DB just on one DC. The other DCs will load them from remote cache.
            CacheInitializer initializer = new DBLockBasedCacheInitializer(session, ispnInitializer);

            initializer.initCache();
            initializer.loadSessions();

            // Initialize persister for periodically doing bulk DB updates of lastSessionRefresh timestamps of refreshed sessions
            persisterLastSessionRefreshStore = new PersisterLastSessionRefreshStoreFactory().createAndInit(session, true);
        }

    });

    log.debug("Pre-loading userSessions from persistent storage finished");
}
 
Example #24
Source File: SessionsConsoleCommand.java    From hacep with Apache License 2.0 5 votes vote down vote up
@Override
public boolean execute(UI console, Iterator<String> args) throws IllegalParametersException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Start execute command 'sessions'");
    }

    Cache<String, Object> sessionCache = hacep.getSessionCache();
    Map<Address, List<SessionData>> sessions = new HashMap<>();
    hacep.getCacheManager().getMembers().forEach(a -> sessions.put(a, new ArrayList<>()));
    for (Map.Entry<String, List<Address>> entry : jdgUtility.getKeysAddresses(sessionCache).entrySet()) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Key [" + entry.getKey() + "] List{" + entry.getValue() + "}");
        }
        List<Address> addresses = entry.getValue() != null ? entry.getValue() : Collections.emptyList();
        for (int i = 0; i < addresses.size(); i++) {
            boolean isPrimary = (i == 0);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Key [" + entry.getKey() + "] Address{" + addresses.get(i) + "] isPrimary [" + isPrimary + "]");
            }
            sessions.compute(addresses.get(i), (a, l) -> {
                SessionData object = new SessionData(entry.getKey().toString(), isPrimary ? NodeType.PRIMARY : NodeType.REPLICA);
                l.add(object);
                return l;
            });
        }
    }

    console.print(sessions.entrySet().stream()
            .map(e -> new HACEPNode(e.getKey().toString(), e.getValue()))
            .collect(Collectors.toList()));
    return true;
}
 
Example #25
Source File: EmbeddedCacheTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected org.infinispan.commons.api.BasicCache<Object, Object> givenAConnectedCache() {
    @SuppressWarnings("unchecked")
    final Cache<Object, Object> result = mock(Cache.class);
    when(remoteCacheManager.getCache(anyString())).thenReturn(result);
    return result;
}
 
Example #26
Source File: InfinispanActionTokenStoreProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public InfinispanActionTokenStoreProvider(KeycloakSession session, Cache<ActionTokenReducedKey, ActionTokenValueEntity> actionKeyCache) {
    this.session = session;
    this.actionKeyCache = actionKeyCache;
    this.tx = new InfinispanKeycloakTransaction();

    session.getTransactionManager().enlistAfterCompletion(tx);
}
 
Example #27
Source File: InfinispanAuthenticationSessionProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public InfinispanAuthenticationSessionProvider(KeycloakSession session, InfinispanKeyGenerator keyGenerator, Cache<String, RootAuthenticationSessionEntity> cache) {
    this.session = session;
    this.cache = cache;
    this.keyGenerator = keyGenerator;

    this.tx = new InfinispanKeycloakTransaction();
    this.clusterEventsSenderTx = new SessionEventsSenderTransaction(session);

    session.getTransactionManager().enlistAfterCompletion(tx);
    session.getTransactionManager().enlistAfterCompletion(clusterEventsSenderTx);
}
 
Example #28
Source File: CacheFactory.java    From EDDI with Apache License 2.0 5 votes vote down vote up
@Override
public <K, V> ICache<K, V> getCache(String cacheName) {
    Cache<K, V> cache;
    if (cacheName != null) {
        cache = this.cacheManager.getCache(cacheName, true);
    } else {
        cache = this.cacheManager.getCache();
    }

    return new CacheImpl<>(cacheName, cache);
}
 
Example #29
Source File: InfinispanRegistryStorage.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
@Override
protected StorageMap createStorageMap() {
    manager.defineConfiguration(
        STORAGE_CACHE,
        new ConfigurationBuilder()
            .clustering().cacheMode(CacheMode.REPL_SYNC)
            .build()
    );

    Cache<String, Map<Long, Map<String, String>>> cache = manager.getCache(STORAGE_CACHE, true);
    return CacheStorageMap.create(cache);
}
 
Example #30
Source File: AbstractSessionCacheCommand.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void doRunCacheCommand(KeycloakSession session, Cache<String, SessionEntityWrapper> cache) {
    String id = getArg(1);
    cache = ((AdvancedCache) cache).withFlags(Flag.CACHE_MODE_LOCAL);
    UserSessionEntity userSession = (UserSessionEntity) cache.get(id).getEntity();
    printSession(id, userSession);
}