Java Code Examples for org.infinispan.Cache

The following examples show how to use org.infinispan.Cache. These examples are extracted from open source projects.
Example 1
Project: keycloak   File: ConcurrencyJDGRemoveSessionTest.java    License: 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 2
Project: keycloak   File: ConcurrencyVersioningTest.java    License: 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 3
Project: hacep   File: InfoConsoleCommand.java    License: 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
Project: keycloak   File: AbstractSessionCacheCommand.java    License: 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 5
Project: keycloak   File: ConcurrencyVersioningTest.java    License: 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 6
Project: keycloak   File: InfinispanSingleUseTokenStoreProviderFactory.java    License: 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 7
Project: keycloak   File: AbstractSessionCacheCommand.java    License: 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 8
Project: keycloak   File: InfinispanSessionCacheIdMapperUpdater.java    License: 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 9
Project: infinispan-simple-tutorials   File: InfinispanListen.java    License: 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 10
Project: keycloak   File: InfinispanKeycloakTransaction.java    License: 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 11
Project: apicurio-registry   File: InfinispanRegistryStorage.java    License: 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 12
Project: keycloak   File: ConcurrencyJDGRemoteCacheClientListenersTest.java    License: 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 13
Project: quarkus   File: TestServlet.java    License: Apache License 2.0 5 votes vote down vote up
@Transactional
@Path("PUT/{cacheName}/{id}/{value}")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String put(@PathParam("cacheName") String cacheName, @PathParam("id") String id, @PathParam("value") String value,
        @QueryParam("shouldFail") String shouldFail) {
    log.info("Putting " + id + " with value: " + value + " into " + cacheName);
    Cache<byte[], byte[]> cache = emc.getCache(cacheName);
    byte[] result = cache.put(id.getBytes(StandardCharsets.UTF_8), value.getBytes(StandardCharsets.UTF_8));
    if (Boolean.parseBoolean(shouldFail)) {
        throw new RuntimeException("Forced Exception!");
    }
    return result == null ? "null" : new String(result, StandardCharsets.UTF_8);
}
 
Example 14
Project: quarkus   File: TestServlet.java    License: Apache License 2.0 5 votes vote down vote up
@Path("REMOVE/{cacheName}/{id}")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String remove(@PathParam("cacheName") String cacheName, @PathParam("id") String id) {
    log.info("Removing " + id + " from " + cacheName);
    Cache<byte[], byte[]> cache = emc.getCache(cacheName);
    byte[] result = cache.remove(id.getBytes(StandardCharsets.UTF_8));
    return result == null ? "null" : new String(result, StandardCharsets.UTF_8);
}
 
Example 15
Project: keycloak   File: TopologyInfo.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get route to be used as the identifier for sticky session. Return null if I am not able to find the appropriate route (or in case of local mode)
 */
public String getRouteName(Cache cache, Object key) {
    if (cache.getCacheConfiguration().clustering().cacheMode().isClustered() && isGeneratedNodeName) {
        logger.warn("Clustered configuration used, but node name is not properly set. Make sure to start server with jboss.node.name property identifying cluster node");
    }

    if (isGeneratedNodeName) {
        return null;
    }

    // Impl based on Wildfly sticky session algorithm for generating routes ( org.wildfly.clustering.web.infinispan.session.InfinispanRouteLocator )
    Address address = getOwnerAddress(cache, key);

    // Local mode
    if (address == null ||  (address == LocalModeAddress.INSTANCE)) {
        return myNodeName;
    }

    org.jgroups.Address jgroupsAddress = toJGroupsAddress(address);
    String name = NameCache.get(jgroupsAddress);

    // If no logical name exists, create one using physical address
    if (name == null) {

        Transport transport = cache.getCacheManager().getTransport();
        JChannel jgroupsChannel = ((JGroupsTransport) transport).getChannel();

        IpAddress ipAddress = (IpAddress) jgroupsChannel.down(new Event(Event.GET_PHYSICAL_ADDRESS, jgroupsAddress));
        // Physical address might be null if node is no longer a member of the cluster
        InetSocketAddress socketAddress = (ipAddress != null) ? new InetSocketAddress(ipAddress.getIpAddress(), ipAddress.getPort()) : new InetSocketAddress(0);
        name = String.format("%s:%s", socketAddress.getHostString(), socketAddress.getPort());

        logger.debugf("Address not found in NameCache. Fallback to %s", name);
    }

    return name;
}
 
Example 16
Project: apiman   File: InfinispanRegistry.java    License: 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 17
Project: keycloak   File: CrossDCLastSessionRefreshStoreFactory.java    License: 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 18
Project: keycloak   File: InfinispanUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static RemoteCache getRemoteCache(Cache ispnCache) {
    Set<RemoteStore> remoteStores = getRemoteStores(ispnCache);
    if (remoteStores.isEmpty()) {
        return null;
    } else {
        return remoteStores.iterator().next().getRemoteCache();
    }
}
 
Example 19
Project: hacep   File: TestPersistence.java    License: Apache License 2.0 5 votes vote down vote up
private void checkKey(String key, Cache<String, Object> cacheDeserialized, Cache<String, Object> cacheDeserialized2, Cache<String, Object> cacheDeserialized3) {

        logger.info("Checking key: "+key);

        long keyLong = Long.parseLong(key);

        Object o = cacheDeserialized.get(key);
        //XXX: needed waiting for https://issues.jboss.org/browse/ISPN-9200
        if( o == null){
            o = cacheDeserialized2.get(key);
        }
        if( o == null){
            o = cacheDeserialized3.get(key);
        }
        ///////////////////////////////////////////////////////////////////

        Assert.assertTrue(o instanceof HAKieSerializedSession);
        HAKieSerializedSession haKieSerializedSession = (HAKieSerializedSession) o;
        HAKieSession sessionRebuilt = haKieSerializedSession.rebuild();

        sessionRebuilt.insert(generateFactTenSecondsAfter(keyLong, 0L));
        cacheDeserialized.put(key, sessionRebuilt);

        sessionRebuilt.insert(generateFactTenSecondsAfter(keyLong, 0L));
        cacheDeserialized.put(key, sessionRebuilt);

        // 30 sec after - lock should be expired
        sessionRebuilt.insert(generateFactTenSecondsAfter(keyLong, 0L));
        cacheDeserialized.put(key, sessionRebuilt);

        // And inserted again by this fact (expires in 25 sec)
        sessionRebuilt.insert(generateFactTenSecondsAfter(keyLong, 10L));
        cacheDeserialized.put(key, sessionRebuilt);
    }
 
Example 20
Project: keycloak   File: AbstractSessionCacheCommand.java    License: 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);
}
 
Example 21
Project: keycloak   File: RootAuthenticationSessionAdapter.java    License: 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 22
Project: keycloak   File: ConcurrencyJDGRemoteCacheClientListenersTest.java    License: 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 23
Project: keycloak   File: CacheCommands.java    License: 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 24
Project: hacep   File: AllConsoleCommand.java    License: 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 25
Project: hacep   File: SessionsConsoleCommand.java    License: 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 26
Project: hono   File: EmbeddedCacheTest.java    License: 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 27
Project: keycloak   File: InfinispanActionTokenStoreProvider.java    License: 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 28
Project: keycloak   File: InfinispanAuthenticationSessionProvider.java    License: 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 29
Project: EDDI   File: CacheFactory.java    License: 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 30
Project: keycloak   File: InfinispanNotificationsManager.java    License: 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 31
Project: keycloak   File: InfinispanKeyGenerator.java    License: 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 32
Project: keycloak   File: InfinispanKeycloakTransaction.java    License: 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 33
Project: keycloak   File: AbstractSessionCacheCommand.java    License: 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 34
Project: keycloak   File: OfflinePersistentUserSessionLoader.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean isFinished(BaseCacheInitializer initializer) {
    Cache<String, Serializable> workCache = initializer.getWorkCache();
    Boolean sessionsLoaded = (Boolean) workCache.get(PERSISTENT_SESSIONS_LOADED);

    if (sessionsLoaded != null && sessionsLoaded) {
        log.debugf("Persistent sessions loaded already.");
        return true;
    } else {
        log.debugf("Persistent sessions not yet loaded.");
        return false;
    }
}
 
Example 35
Project: unitime   File: ReplicatedServer.java    License: 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 36
Project: keycloak   File: ConcurrencyJDGCacheReplaceTest.java    License: Apache License 2.0 5 votes vote down vote up
public HotRodListener(Cache<String, SessionEntityWrapper<UserSessionEntity>> origCache, RemoteCache remoteCache, AtomicInteger listenerCount) {
    this.listenerCount = listenerCount;
    this.remoteCache = remoteCache;
    this.origCache = origCache;
    executor = Executors.newCachedThreadPool();
    executors.add(executor);

}
 
Example 37
Project: keycloak   File: InfinispanUserSessionProviderFactory.java    License: 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 38
Project: keycloak   File: ConcurrencyJDGRemoteCacheClientListenersTest.java    License: Apache License 2.0 4 votes vote down vote up
private Worker(Cache<String, Integer> cache, int myThreadId) {
    this.cache = cache;
    this.myThreadId = myThreadId;
}
 
Example 39
Project: keycloak   File: InfinispanSessionCacheIdMapperUpdater.java    License: Apache License 2.0 4 votes vote down vote up
public static List<RemoteCacheStore> getRemoteStores(Cache ssoCache) {
    return ssoCache.getAdvancedCache().getComponentRegistry().getComponent(CacheLoaderManager.class).getCacheLoaders(RemoteCacheStore.class);
}
 
Example 40
Project: tutorials   File: CacheConfiguration.java    License: MIT License 4 votes vote down vote up
public Cache<String, Integer> transactionalCache(DefaultCacheManager cacheManager, CacheListener listener) {
    return this.buildCache(TRANSACTIONAL_CACHE, cacheManager, listener, transactionalConfiguration());
}