diff --git a/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPIdentityStoreRegistry.java b/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPIdentityStoreRegistry.java
index bb00804c6b..d224940605 100644
--- a/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPIdentityStoreRegistry.java
+++ b/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPIdentityStoreRegistry.java
@@ -25,10 +25,8 @@ import org.keycloak.models.RealmModel;
import org.keycloak.storage.ldap.idm.store.ldap.LDAPIdentityStore;
import org.keycloak.storage.ldap.mappers.LDAPConfigDecorator;
-import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
-import java.util.stream.Collectors;
/**
* @author Marek Posolda
@@ -68,12 +66,9 @@ public class LDAPIdentityStoreRegistry {
if (logger.isDebugEnabled()) {
RealmModel realm = session.realms().getRealm(ldapModel.getParentId());
- List mappers = realm.getComponents(ldapModel.getId());
- mappers.stream().forEach((ComponentModel c) -> {
-
- logger.debugf("Mapper for provider: %s, Mapper name: %s, Provider: %s, Mapper configuration: %s", ldapModel.getName(), c.getName(), c.getProviderId(), c.getConfig().toString());
-
- });
+ realm.getComponentsStream(ldapModel.getId()).forEach(c ->
+ logger.debugf("Mapper for provider: %s, Mapper name: %s, Provider: %s, Mapper configuration: %s",
+ ldapModel.getName(), c.getName(), c.getProviderId(), c.getConfig().toString()));
}
}
diff --git a/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPStorageProvider.java b/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPStorageProvider.java
index d50a36d895..0224b0a841 100755
--- a/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPStorageProvider.java
+++ b/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPStorageProvider.java
@@ -25,6 +25,8 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
import javax.naming.AuthenticationException;
@@ -37,7 +39,18 @@ import org.keycloak.credential.CredentialInputUpdater;
import org.keycloak.credential.CredentialInputValidator;
import org.keycloak.federation.kerberos.impl.KerberosUsernamePasswordAuthenticator;
import org.keycloak.federation.kerberos.impl.SPNEGOAuthenticator;
-import org.keycloak.models.*;
+import org.keycloak.models.CredentialValidationOutput;
+import org.keycloak.models.GroupModel;
+import org.keycloak.models.KeycloakSession;
+import org.keycloak.models.LDAPConstants;
+import org.keycloak.models.ModelDuplicateException;
+import org.keycloak.models.ModelException;
+import org.keycloak.models.RealmModel;
+import org.keycloak.models.RequiredActionProviderModel;
+import org.keycloak.models.RoleModel;
+import org.keycloak.models.UserCredentialModel;
+import org.keycloak.models.UserManager;
+import org.keycloak.models.UserModel;
import org.keycloak.models.cache.CachedUserModel;
import org.keycloak.models.credential.PasswordCredentialModel;
import org.keycloak.models.utils.DefaultRoles;
@@ -58,10 +71,11 @@ import org.keycloak.storage.ldap.idm.query.internal.LDAPQuery;
import org.keycloak.storage.ldap.idm.query.internal.LDAPQueryConditionsBuilder;
import org.keycloak.storage.ldap.idm.store.ldap.LDAPIdentityStore;
import org.keycloak.storage.ldap.kerberos.LDAPProviderKerberosConfig;
+import org.keycloak.storage.ldap.mappers.LDAPMappersComparator;
+import org.keycloak.storage.ldap.mappers.LDAPOperationDecorator;
import org.keycloak.storage.ldap.mappers.LDAPStorageMapper;
import org.keycloak.storage.ldap.mappers.LDAPStorageMapperManager;
import org.keycloak.storage.ldap.mappers.PasswordUpdateCallback;
-import org.keycloak.storage.ldap.mappers.LDAPOperationDecorator;
import org.keycloak.storage.user.ImportedUserValidation;
import org.keycloak.storage.user.UserLookupProvider;
import org.keycloak.storage.user.UserQueryProvider;
@@ -91,6 +105,7 @@ public class LDAPStorageProvider implements UserStorageProvider,
protected PasswordUpdateCallback updater;
protected LDAPStorageMapperManager mapperManager;
protected LDAPStorageUserManager userManager;
+ private LDAPMappersComparator ldapMappersComparator;
// these exist to make sure that we only hit ldap once per transaction
//protected Map noImportSessionCache = new HashMap<>();
@@ -112,6 +127,8 @@ public class LDAPStorageProvider implements UserStorageProvider,
if (kerberosConfig.isAllowKerberosAuthentication()) {
supportedCredentialTypes.add(UserCredentialModel.KERBEROS);
}
+
+ ldapMappersComparator = new LDAPMappersComparator(getLdapIdentityStore().getConfig());
}
public void setUpdater(PasswordUpdateCallback updater) {
@@ -192,12 +209,14 @@ public class LDAPStorageProvider implements UserStorageProvider,
break;
}
- List mappers = realm.getComponents(model.getId(), LDAPStorageMapper.class.getName());
- List sortedMappers = mapperManager.sortMappersAsc(mappers);
- for (ComponentModel mapperModel : sortedMappers) {
- LDAPStorageMapper ldapMapper = mapperManager.getMapper(mapperModel);
- proxied = ldapMapper.proxy(ldapObject, proxied, realm);
- }
+ AtomicReference proxy = new AtomicReference<>(proxied);
+ realm.getComponentsStream(model.getId(), LDAPStorageMapper.class.getName())
+ .sorted(ldapMappersComparator.sortAsc())
+ .forEachOrdered(mapperModel -> {
+ LDAPStorageMapper ldapMapper = mapperManager.getMapper(mapperModel);
+ proxy.set(ldapMapper.proxy(ldapObject, proxy.get(), realm));
+ });
+ proxied = proxy.get();
if (!model.isImportEnabled()) {
proxied = new UpdateOnlyChangeUserModelDelegate(proxied);
@@ -241,7 +260,7 @@ public class LDAPStorageProvider implements UserStorageProvider,
return Collections.emptyList();
}
- List searchResults = new LinkedList();
+ List searchResults = new LinkedList<>();
for (LDAPObject ldapUser : ldapObjects) {
String ldapUsername = LDAPUtils.getUsername(ldapUser, this.ldapIdentityStore.getConfig());
@@ -286,11 +305,11 @@ public class LDAPStorageProvider implements UserStorageProvider,
realm.getDefaultGroupsStream().forEach(proxy::joinGroup);
- for (RequiredActionProviderModel r : realm.getRequiredActionProviders()) {
- if (r.isEnabled() && r.isDefaultAction()) {
- proxy.addRequiredAction(r.getAlias());
- }
- }
+ realm.getRequiredActionProvidersStream()
+ .filter(RequiredActionProviderModel::isEnabled)
+ .filter(RequiredActionProviderModel::isDefaultAction)
+ .map(RequiredActionProviderModel::getAlias)
+ .forEachOrdered(proxy::addRequiredAction);
return proxy;
}
@@ -397,8 +416,10 @@ public class LDAPStorageProvider implements UserStorageProvider,
@Override
public List getGroupMembers(RealmModel realm, GroupModel group, int firstResult, int maxResults) {
- List mappers = realm.getComponents(model.getId(), LDAPStorageMapper.class.getName());
- List sortedMappers = mapperManager.sortMappersAsc(mappers);
+ List sortedMappers = realm.getComponentsStream(model.getId(), LDAPStorageMapper.class.getName())
+ .sorted(ldapMappersComparator.sortAsc())
+ .collect(Collectors.toList());
+
for (ComponentModel mapperModel : sortedMappers) {
LDAPStorageMapper ldapMapper = mapperManager.getMapper(mapperModel);
List users = ldapMapper.getGroupMembers(realm, group, firstResult, maxResults);
@@ -418,8 +439,9 @@ public class LDAPStorageProvider implements UserStorageProvider,
@Override
public List getRoleMembers(RealmModel realm, RoleModel role, int firstResult, int maxResults) {
- List mappers = realm.getComponents(model.getId(), LDAPStorageMapper.class.getName());
- List sortedMappers = mapperManager.sortMappersAsc(mappers);
+ List sortedMappers = realm.getComponentsStream(model.getId(), LDAPStorageMapper.class.getName())
+ .sorted(ldapMappersComparator.sortAsc())
+ .collect(Collectors.toList());
for (ComponentModel mapperModel : sortedMappers) {
LDAPStorageMapper ldapMapper = mapperManager.getMapper(mapperModel);
List users = ldapMapper.getRoleMembers(realm, role, firstResult, maxResults);
@@ -544,15 +566,16 @@ public class LDAPStorageProvider implements UserStorageProvider,
}
imported.setEnabled(true);
- List mappers = realm.getComponents(model.getId(), LDAPStorageMapper.class.getName());
- List sortedMappers = mapperManager.sortMappersDesc(mappers);
- for (ComponentModel mapperModel : sortedMappers) {
- if (logger.isTraceEnabled()) {
- logger.tracef("Using mapper %s during import user from LDAP", mapperModel);
- }
- LDAPStorageMapper ldapMapper = mapperManager.getMapper(mapperModel);
- ldapMapper.onImportUserFromLDAP(ldapUser, imported, realm, true);
- }
+ UserModel finalImported = imported;
+ realm.getComponentsStream(model.getId(), LDAPStorageMapper.class.getName())
+ .sorted(ldapMappersComparator.sortDesc())
+ .forEachOrdered(mapperModel -> {
+ if (logger.isTraceEnabled()) {
+ logger.tracef("Using mapper %s during import user from LDAP", mapperModel);
+ }
+ LDAPStorageMapper ldapMapper = mapperManager.getMapper(mapperModel);
+ ldapMapper.onImportUserFromLDAP(ldapUser, finalImported, realm, true);
+ });
String userDN = ldapUser.getDn().toString();
if (model.isImportEnabled()) imported.setFederationLink(model.getId());
@@ -631,17 +654,17 @@ public class LDAPStorageProvider implements UserStorageProvider,
ldapIdentityStore.validatePassword(ldapUser, password);
return true;
} catch (AuthenticationException ae) {
- boolean processed = false;
- List mappers = realm.getComponents(model.getId(), LDAPStorageMapper.class.getName());
- List sortedMappers = mapperManager.sortMappersDesc(mappers);
- for (ComponentModel mapperModel : sortedMappers) {
- if (logger.isTraceEnabled()) {
- logger.tracef("Using mapper %s during import user from LDAP", mapperModel);
- }
- LDAPStorageMapper ldapMapper = mapperManager.getMapper(mapperModel);
- processed = processed || ldapMapper.onAuthenticationFailure(ldapUser, user, ae, realm);
- }
- return processed;
+ AtomicReference processed = new AtomicReference<>(false);
+ realm.getComponentsStream(model.getId(), LDAPStorageMapper.class.getName())
+ .sorted(ldapMappersComparator.sortDesc())
+ .forEachOrdered(mapperModel -> {
+ if (logger.isTraceEnabled()) {
+ logger.tracef("Using mapper %s during import user from LDAP", mapperModel);
+ }
+ LDAPStorageMapper ldapMapper = mapperManager.getMapper(mapperModel);
+ processed.set(processed.get() || ldapMapper.onAuthenticationFailure(ldapUser, user, ae, realm));
+ });
+ return processed.get();
}
}
}
diff --git a/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPStorageProviderFactory.java b/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPStorageProviderFactory.java
index db4e5d41a6..66aef7024c 100755
--- a/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPStorageProviderFactory.java
+++ b/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPStorageProviderFactory.java
@@ -52,8 +52,8 @@ import org.keycloak.storage.ldap.mappers.FullNameLDAPStorageMapperFactory;
import org.keycloak.storage.ldap.mappers.HardcodedLDAPAttributeMapper;
import org.keycloak.storage.ldap.mappers.HardcodedLDAPAttributeMapperFactory;
import org.keycloak.storage.ldap.mappers.LDAPConfigDecorator;
+import org.keycloak.storage.ldap.mappers.LDAPMappersComparator;
import org.keycloak.storage.ldap.mappers.LDAPStorageMapper;
-import org.keycloak.storage.ldap.mappers.LDAPStorageMapperFactory;
import org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapper;
import org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapperFactory;
import org.keycloak.storage.ldap.mappers.msad.MSADUserAccountControlStorageMapperFactory;
@@ -62,9 +62,10 @@ import org.keycloak.storage.user.SynchronizationResult;
import org.keycloak.utils.CredentialHelper;
import java.util.Date;
-import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Collectors;
/**
* @author Marek Posolda
@@ -241,17 +242,12 @@ public class LDAPStorageProviderFactory implements UserStorageProviderFactory getLDAPConfigDecorators(KeycloakSession session, ComponentModel ldapModel) {
RealmModel realm = session.realms().getRealm(ldapModel.getParentId());
- List mapperComponents = realm.getComponents(ldapModel.getId(), LDAPStorageMapper.class.getName());
-
- Map result = new HashMap<>();
- for (ComponentModel mapperModel : mapperComponents) {
- LDAPStorageMapperFactory mapperFactory = (LDAPStorageMapperFactory) session.getKeycloakSessionFactory().getProviderFactory(LDAPStorageMapper.class, mapperModel.getProviderId());
- if (mapperFactory instanceof LDAPConfigDecorator) {
- result.put(mapperModel, (LDAPConfigDecorator) mapperFactory);
- }
- }
-
- return result;
+ return realm.getComponentsStream(ldapModel.getId(), LDAPStorageMapper.class.getName())
+ .filter(mapperModel -> session.getKeycloakSessionFactory()
+ .getProviderFactory(LDAPStorageMapper.class, mapperModel.getProviderId()) instanceof LDAPConfigDecorator)
+ .collect(Collectors.toMap(Function.identity(), mapperModel ->
+ (LDAPConfigDecorator) session.getKeycloakSessionFactory()
+ .getProviderFactory(LDAPStorageMapper.class, mapperModel.getProviderId())));
}
@@ -504,14 +500,15 @@ public class LDAPStorageProviderFactory implements UserStorageProviderFactory mappers = realm.getComponents(model.getId(), LDAPStorageMapper.class.getName());
- for (ComponentModel mapperModel : mappers) {
- LDAPStorageMapper ldapMapper = session.getProvider(LDAPStorageMapper.class, mapperModel);
- SynchronizationResult syncResult = ldapMapper.syncDataFromFederationProviderToKeycloak(realm);
- if (syncResult.getAdded() > 0 || syncResult.getUpdated() > 0 || syncResult.getRemoved() > 0 || syncResult.getFailed() > 0) {
- logger.infof("Sync of federation mapper '%s' finished. Status: %s", mapperModel.getName(), syncResult.toString());
- }
- }
+ realm.getComponentsStream(model.getId(), LDAPStorageMapper.class.getName())
+ .forEach(mapperModel -> {
+ SynchronizationResult syncResult = session.getProvider(LDAPStorageMapper.class, mapperModel)
+ .syncDataFromFederationProviderToKeycloak(realm);
+ if (syncResult.getAdded() > 0 || syncResult.getUpdated() > 0 || syncResult.getRemoved() > 0
+ || syncResult.getFailed() > 0) {
+ logger.infof("Sync of federation mapper '%s' finished. Status: %s", mapperModel.getName(), syncResult.toString());
+ }
+ });
}
});
@@ -609,12 +606,14 @@ public class LDAPStorageProviderFactory implements UserStorageProviderFactory federationMappers = currentRealm.getComponents(fedModel.getId(), LDAPStorageMapper.class.getName());
- List sortedMappers = ldapFedProvider.getMapperManager().sortMappersDesc(federationMappers);
- for (ComponentModel mapperModel : sortedMappers) {
- LDAPStorageMapper ldapMapper = ldapFedProvider.getMapperManager().getMapper(mapperModel);
- ldapMapper.onImportUserFromLDAP(ldapUser, currentUser, currentRealm, false);
- }
+ LDAPMappersComparator ldapMappersComparator = new LDAPMappersComparator(ldapFedProvider.getLdapIdentityStore().getConfig());
+ currentRealm.getComponentsStream(fedModel.getId(), LDAPStorageMapper.class.getName())
+ .sorted(ldapMappersComparator.sortDesc())
+ .forEachOrdered(mapperModel -> {
+ LDAPStorageMapper ldapMapper = ldapFedProvider.getMapperManager().getMapper(mapperModel);
+ ldapMapper.onImportUserFromLDAP(ldapUser, currentUser, currentRealm, false);
+ });
+
UserCache userCache = session.userCache();
if (userCache != null) {
userCache.evict(currentRealm, currentUser);
diff --git a/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPUtils.java b/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPUtils.java
index 252887f79e..9a1ce30aa6 100755
--- a/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPUtils.java
+++ b/federation/ldap/src/main/java/org/keycloak/storage/ldap/LDAPUtils.java
@@ -25,6 +25,7 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.stream.Collectors;
import javax.naming.directory.SearchControls;
@@ -43,6 +44,7 @@ import org.keycloak.storage.ldap.idm.query.Condition;
import org.keycloak.storage.ldap.idm.query.internal.LDAPQuery;
import org.keycloak.storage.ldap.idm.query.internal.LDAPQueryConditionsBuilder;
import org.keycloak.storage.ldap.idm.store.ldap.LDAPIdentityStore;
+import org.keycloak.storage.ldap.mappers.LDAPMappersComparator;
import org.keycloak.storage.ldap.mappers.LDAPStorageMapper;
import org.keycloak.storage.ldap.mappers.membership.MembershipType;
@@ -67,12 +69,13 @@ public class LDAPUtils {
ldapUser.setRdnAttributeName(ldapConfig.getRdnLdapAttribute());
ldapUser.setObjectClasses(ldapConfig.getUserObjectClasses());
- List federationMappers = realm.getComponents(ldapProvider.getModel().getId(), LDAPStorageMapper.class.getName());
- List sortedMappers = ldapProvider.getMapperManager().sortMappersAsc(federationMappers);
- for (ComponentModel mapperModel : sortedMappers) {
- LDAPStorageMapper ldapMapper = ldapProvider.getMapperManager().getMapper(mapperModel);
- ldapMapper.onRegisterUserToLDAP(ldapUser, user, realm);
- }
+ LDAPMappersComparator ldapMappersComparator = new LDAPMappersComparator(ldapConfig);
+ realm.getComponentsStream(ldapProvider.getModel().getId(), LDAPStorageMapper.class.getName())
+ .sorted(ldapMappersComparator.sortAsc())
+ .forEachOrdered(mapperModel -> {
+ LDAPStorageMapper ldapMapper = ldapProvider.getMapperManager().getMapper(mapperModel);
+ ldapMapper.onRegisterUserToLDAP(ldapUser, user, realm);
+ });
LDAPUtils.computeAndSetDn(ldapConfig, ldapUser);
ldapStore.add(ldapUser);
@@ -92,7 +95,9 @@ public class LDAPUtils {
ldapQuery.addWhereCondition(customFilterCondition);
}
- List mapperModels = realm.getComponents(ldapProvider.getModel().getId(), LDAPStorageMapper.class.getName());
+ List mapperModels = realm
+ .getComponentsStream(ldapProvider.getModel().getId(), LDAPStorageMapper.class.getName())
+ .collect(Collectors.toList());
ldapQuery.addMappers(mapperModels);
return ldapQuery;
diff --git a/federation/ldap/src/main/java/org/keycloak/storage/ldap/idm/query/internal/LDAPQuery.java b/federation/ldap/src/main/java/org/keycloak/storage/ldap/idm/query/internal/LDAPQuery.java
index b5cbaeb6b1..8eb0bc5f47 100644
--- a/federation/ldap/src/main/java/org/keycloak/storage/ldap/idm/query/internal/LDAPQuery.java
+++ b/federation/ldap/src/main/java/org/keycloak/storage/ldap/idm/query/internal/LDAPQuery.java
@@ -26,18 +26,14 @@ import org.keycloak.storage.ldap.idm.model.LDAPObject;
import org.keycloak.storage.ldap.idm.query.Condition;
import org.keycloak.storage.ldap.idm.query.Sort;
import org.keycloak.storage.ldap.idm.store.ldap.LDAPContextManager;
+import org.keycloak.storage.ldap.mappers.LDAPMappersComparator;
import org.keycloak.storage.ldap.mappers.LDAPStorageMapper;
import javax.naming.NamingException;
import javax.naming.directory.SearchControls;
import javax.naming.ldap.LdapContext;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Set;
+import java.util.*;
import static java.util.Collections.unmodifiableSet;
@@ -162,8 +158,10 @@ public class LDAPQuery implements AutoCloseable {
public List getResultList() {
// Apply mappers now
- List sortedMappers = ldapFedProvider.getMapperManager().sortMappersAsc(mappers);
- for (ComponentModel mapperModel : sortedMappers) {
+ LDAPMappersComparator ldapMappersComparator = new LDAPMappersComparator(ldapFedProvider.getLdapIdentityStore().getConfig());
+ Collections.sort(mappers, ldapMappersComparator.sortAsc());
+
+ for (ComponentModel mapperModel : mappers) {
LDAPStorageMapper fedMapper = ldapFedProvider.getMapperManager().getMapper(mapperModel);
fedMapper.beforeLDAPQuery(this);
}
diff --git a/federation/ldap/src/main/java/org/keycloak/storage/ldap/mappers/LDAPMappersComparator.java b/federation/ldap/src/main/java/org/keycloak/storage/ldap/mappers/LDAPMappersComparator.java
index f659c2b3a9..dc9e3a66ed 100644
--- a/federation/ldap/src/main/java/org/keycloak/storage/ldap/mappers/LDAPMappersComparator.java
+++ b/federation/ldap/src/main/java/org/keycloak/storage/ldap/mappers/LDAPMappersComparator.java
@@ -18,6 +18,7 @@
package org.keycloak.storage.ldap.mappers;
import org.keycloak.component.ComponentModel;
+import org.keycloak.models.AuthenticationExecutionModel;
import org.keycloak.models.UserModel;
import org.keycloak.storage.ldap.LDAPConfig;
@@ -34,20 +35,18 @@ import java.util.List;
*/
public class LDAPMappersComparator {
- public static List sortAsc(LDAPConfig ldapConfig, Collection mappers) {
- Comparator comparator = new ImportantFirstComparator(ldapConfig);
+ private LDAPConfig ldapConfig;
- List result = new ArrayList<>(mappers);
- Collections.sort(result, comparator);
- return result;
+ public LDAPMappersComparator(LDAPConfig ldapConfig) {
+ this.ldapConfig = ldapConfig;
}
- public static List sortDesc(LDAPConfig ldapConfig, Collection mappers) {
- Comparator comparator = new ImportantFirstComparator(ldapConfig).reversed();
+ public Comparator sortAsc() {
+ return new ImportantFirstComparator(ldapConfig);
+ }
- List result = new ArrayList<>(mappers);
- Collections.sort(result, comparator);
- return result;
+ public Comparator sortDesc() {
+ return new ImportantFirstComparator(ldapConfig).reversed();
}
diff --git a/federation/ldap/src/main/java/org/keycloak/storage/ldap/mappers/LDAPStorageMapperManager.java b/federation/ldap/src/main/java/org/keycloak/storage/ldap/mappers/LDAPStorageMapperManager.java
index b8e9dc46e4..daf087376d 100644
--- a/federation/ldap/src/main/java/org/keycloak/storage/ldap/mappers/LDAPStorageMapperManager.java
+++ b/federation/ldap/src/main/java/org/keycloak/storage/ldap/mappers/LDAPStorageMapperManager.java
@@ -17,9 +17,6 @@
package org.keycloak.storage.ldap.mappers;
-import java.util.Collection;
-import java.util.List;
-
import org.keycloak.component.ComponentModel;
import org.keycloak.models.ModelException;
import org.keycloak.storage.ldap.LDAPStorageProvider;
@@ -45,15 +42,4 @@ public class LDAPStorageMapperManager {
return ldapMapper;
}
-
-
- public List sortMappersAsc(Collection mappers) {
- return LDAPMappersComparator.sortAsc(ldapProvider.getLdapIdentityStore().getConfig(), mappers);
- }
-
- public List sortMappersDesc(Collection mappers) {
- return LDAPMappersComparator.sortDesc(ldapProvider.getLdapIdentityStore().getConfig(), mappers);
- }
-
-
}
diff --git a/federation/ldap/src/test/java/org/keycloak/storage/ldap/idm/model/LDAPMappersComparatorTest.java b/federation/ldap/src/test/java/org/keycloak/storage/ldap/idm/model/LDAPMappersComparatorTest.java
index 41bf3ec9b0..4862c832b3 100644
--- a/federation/ldap/src/test/java/org/keycloak/storage/ldap/idm/model/LDAPMappersComparatorTest.java
+++ b/federation/ldap/src/test/java/org/keycloak/storage/ldap/idm/model/LDAPMappersComparatorTest.java
@@ -32,6 +32,7 @@ import org.keycloak.storage.ldap.mappers.LDAPStorageMapper;
import org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapper;
import org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapperFactory;
+import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
@@ -46,26 +47,30 @@ public class LDAPMappersComparatorTest {
public void testCompareWithCNUsername() {
MultivaluedHashMap cfg = new MultivaluedHashMap<>();
cfg.add(LDAPConstants.USERNAME_LDAP_ATTRIBUTE, LDAPConstants.CN);
- LDAPConfig config = new LDAPConfig(cfg);
+ LDAPMappersComparator ldapMappersComparator = new LDAPMappersComparator(new LDAPConfig(cfg));
- List sorted = LDAPMappersComparator.sortAsc(config, getMappers());
- assertOrder(sorted, "username-cn", "sAMAccountName", "first name", "full name");
+ List mappers = getMappers();
- sorted = LDAPMappersComparator.sortDesc(config, getMappers());
- assertOrder(sorted, "full name", "first name", "sAMAccountName", "username-cn");
+ Collections.sort(mappers, ldapMappersComparator.sortAsc());
+ assertOrder(mappers, "username-cn", "sAMAccountName", "first name", "full name");
+
+ Collections.sort(mappers, ldapMappersComparator.sortDesc());
+ assertOrder(mappers, "full name", "first name", "sAMAccountName", "username-cn");
}
@Test
public void testCompareWithSAMAccountNameUsername() {
MultivaluedHashMap cfg = new MultivaluedHashMap<>();
cfg.add(LDAPConstants.USERNAME_LDAP_ATTRIBUTE, LDAPConstants.SAM_ACCOUNT_NAME);
- LDAPConfig config = new LDAPConfig(cfg);
+ LDAPMappersComparator ldapMappersComparator = new LDAPMappersComparator(new LDAPConfig(cfg));
- List sorted = LDAPMappersComparator.sortAsc(config, getMappers());
- assertOrder(sorted, "sAMAccountName", "username-cn", "first name", "full name");
+ List mappers = getMappers();
- sorted = LDAPMappersComparator.sortDesc(config, getMappers());
- assertOrder(sorted, "full name", "first name", "username-cn", "sAMAccountName");
+ Collections.sort(mappers, ldapMappersComparator.sortAsc());
+ assertOrder(mappers, "sAMAccountName", "username-cn", "first name", "full name");
+
+ Collections.sort(mappers, ldapMappersComparator.sortDesc());
+ assertOrder(mappers, "full name", "first name", "username-cn", "sAMAccountName");
}
private void assertOrder(List result, String... names) {
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmAdapter.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmAdapter.java
index 3af7ad6238..e9b0bc0137 100755
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmAdapter.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmAdapter.java
@@ -638,9 +638,9 @@ public class RealmAdapter implements CachedRealmModel {
}
@Override
- public List getRequiredCredentials() {
- if (isUpdated()) return updated.getRequiredCredentials();
- return cached.getRequiredCredentials();
+ public Stream getRequiredCredentialsStream() {
+ if (isUpdated()) return updated.getRequiredCredentialsStream();
+ return cached.getRequiredCredentials().stream();
}
@Override
@@ -833,21 +833,18 @@ public class RealmAdapter implements CachedRealmModel {
@Override
- public List getIdentityProviders() {
- if (isUpdated()) return updated.getIdentityProviders();
- return cached.getIdentityProviders();
+ public Stream getIdentityProvidersStream() {
+ if (isUpdated()) return updated.getIdentityProvidersStream();
+ return cached.getIdentityProviders().stream();
}
@Override
public IdentityProviderModel getIdentityProviderByAlias(String alias) {
if (isUpdated()) return updated.getIdentityProviderByAlias(alias);
- for (IdentityProviderModel identityProviderModel : getIdentityProviders()) {
- if (identityProviderModel.getAlias().equals(alias)) {
- return identityProviderModel;
- }
- }
-
- return null;
+ return getIdentityProvidersStream()
+ .filter(model -> Objects.equals(model.getAlias(), alias))
+ .findFirst()
+ .orElse(null);
}
@Override
@@ -953,9 +950,9 @@ public class RealmAdapter implements CachedRealmModel {
}
@Override
- public Set getEventsListeners() {
- if (isUpdated()) return updated.getEventsListeners();
- return cached.getEventsListeners();
+ public Stream getEventsListenersStream() {
+ if (isUpdated()) return updated.getEventsListenersStream();
+ return cached.getEventsListeners().stream();
}
@Override
@@ -965,9 +962,9 @@ public class RealmAdapter implements CachedRealmModel {
}
@Override
- public Set getEnabledEventTypes() {
- if (isUpdated()) return updated.getEnabledEventTypes();
- return cached.getEnabledEventTypes();
+ public Stream getEnabledEventTypesStream() {
+ if (isUpdated()) return updated.getEnabledEventTypesStream();
+ return cached.getEnabledEventTypes().stream();
}
@Override
@@ -1081,9 +1078,9 @@ public class RealmAdapter implements CachedRealmModel {
}
@Override
- public Set getSupportedLocales() {
- if (isUpdated()) return updated.getSupportedLocales();
- return cached.getSupportedLocales();
+ public Stream getSupportedLocalesStream() {
+ if (isUpdated()) return updated.getSupportedLocalesStream();
+ return cached.getSupportedLocales().stream();
}
@Override
@@ -1104,20 +1101,16 @@ public class RealmAdapter implements CachedRealmModel {
}
@Override
- public Set getIdentityProviderMappers() {
- if (isUpdated()) return updated.getIdentityProviderMappers();
- return cached.getIdentityProviderMapperSet();
+ public Stream getIdentityProviderMappersStream() {
+ if (isUpdated()) return updated.getIdentityProviderMappersStream();
+ return cached.getIdentityProviderMapperSet().stream();
}
@Override
- public Set getIdentityProviderMappersByAlias(String brokerAlias) {
- if (isUpdated()) return updated.getIdentityProviderMappersByAlias(brokerAlias);
- Set mappings = new HashSet<>();
- List list = cached.getIdentityProviderMappers().getList(brokerAlias);
- for (IdentityProviderMapperModel entity : list) {
- mappings.add(entity);
- }
- return Collections.unmodifiableSet(mappings);
+ public Stream getIdentityProviderMappersByAliasStream(String brokerAlias) {
+ if (isUpdated()) return updated.getIdentityProviderMappersByAliasStream(brokerAlias);
+ Set mappings = new HashSet<>(cached.getIdentityProviderMappers().getList(brokerAlias));
+ return mappings.stream();
}
@Override
@@ -1236,29 +1229,25 @@ public class RealmAdapter implements CachedRealmModel {
}
@Override
- public List getAuthenticationFlows() {
- if (isUpdated()) return updated.getAuthenticationFlows();
- return cached.getAuthenticationFlowList();
+ public Stream getAuthenticationFlowsStream() {
+ if (isUpdated()) return updated.getAuthenticationFlowsStream();
+ return cached.getAuthenticationFlowList().stream();
}
@Override
public AuthenticationFlowModel getFlowByAlias(String alias) {
- for (AuthenticationFlowModel flow : getAuthenticationFlows()) {
- if (flow.getAlias().equals(alias)) {
- return flow;
- }
- }
- return null;
+ return getAuthenticationFlowsStream()
+ .filter(flow -> Objects.equals(flow.getAlias(), alias))
+ .findFirst()
+ .orElse(null);
}
@Override
public AuthenticatorConfigModel getAuthenticatorConfigByAlias(String alias) {
- for (AuthenticatorConfigModel config : getAuthenticatorConfigs()) {
- if (config.getAlias().equals(alias)) {
- return config;
- }
- }
- return null;
+ return getAuthenticatorConfigsStream()
+ .filter(config -> Objects.equals(config.getAlias(), alias))
+ .findFirst()
+ .orElse(null);
}
@@ -1289,9 +1278,9 @@ public class RealmAdapter implements CachedRealmModel {
}
@Override
- public List getAuthenticationExecutions(String flowId) {
- if (isUpdated()) return updated.getAuthenticationExecutions(flowId);
- return cached.getAuthenticationExecutions().get(flowId);
+ public Stream getAuthenticationExecutionsStream(String flowId) {
+ if (isUpdated()) return updated.getAuthenticationExecutionsStream(flowId);
+ return cached.getAuthenticationExecutions().get(flowId).stream();
}
@Override
@@ -1327,11 +1316,9 @@ public class RealmAdapter implements CachedRealmModel {
}
@Override
- public List getAuthenticatorConfigs() {
- if (isUpdated()) return updated.getAuthenticatorConfigs();
- List models = new ArrayList<>();
- models.addAll(cached.getAuthenticatorConfigs().values());
- return Collections.unmodifiableList(models);
+ public Stream getAuthenticatorConfigsStream() {
+ if (isUpdated()) return updated.getAuthenticatorConfigsStream();
+ return cached.getAuthenticatorConfigs().values().stream();
}
@Override
@@ -1361,9 +1348,9 @@ public class RealmAdapter implements CachedRealmModel {
}
@Override
- public List getRequiredActionProviders() {
- if (isUpdated()) return updated.getRequiredActionProviders();
- return cached.getRequiredActionProviderList();
+ public Stream getRequiredActionProvidersStream() {
+ if (isUpdated()) return updated.getRequiredActionProvidersStream();
+ return cached.getRequiredActionProviderList().stream();
}
@Override
@@ -1449,20 +1436,15 @@ public class RealmAdapter implements CachedRealmModel {
}
@Override
- public List getClientScopes() {
- if (isUpdated()) return updated.getClientScopes();
- List clientScopes = cached.getClientScopes();
- if (clientScopes.isEmpty()) return Collections.EMPTY_LIST;
- List apps = new LinkedList<>();
- for (String id : clientScopes) {
- ClientScopeModel model = cacheSession.getClientScopeById(id, this);
+ public Stream getClientScopesStream() {
+ if (isUpdated()) return updated.getClientScopesStream();
+ return cached.getClientScopes().stream().map(scope -> {
+ ClientScopeModel model = cacheSession.getClientScopeById(scope, this);
if (model == null) {
- throw new IllegalStateException("Cached clientScope not found: " + id);
+ throw new IllegalStateException("Cached clientScope not found: " + scope);
}
- apps.add(model);
- }
- return Collections.unmodifiableList(apps);
-
+ return model;
+ });
}
@Override
@@ -1507,19 +1489,12 @@ public class RealmAdapter implements CachedRealmModel {
}
@Override
- public List getDefaultClientScopes(boolean defaultScope) {
- if (isUpdated()) return updated.getDefaultClientScopes(defaultScope);
-
+ public Stream getDefaultClientScopesStream(boolean defaultScope) {
+ if (isUpdated()) return updated.getDefaultClientScopesStream(defaultScope);
List clientScopeIds = defaultScope ? cached.getDefaultDefaultClientScopes() : cached.getOptionalDefaultClientScopes();
-
- List clientScopes = new LinkedList<>();
- for (String scopeId : clientScopeIds) {
- ClientScopeModel clientScope = cacheSession.getClientScopeById(scopeId, this);
- if (clientScope != null) {
- clientScopes.add(clientScope);
- }
- }
- return clientScopes;
+ return clientScopeIds.stream()
+ .map(scope -> cacheSession.getClientScopeById(scope, this))
+ .filter(Objects::nonNull);
}
@Override
@@ -1588,27 +1563,21 @@ public class RealmAdapter implements CachedRealmModel {
}
@Override
- public List getComponents(String parentId, String providerType) {
- if (isUpdated()) return updated.getComponents(parentId, providerType);
- List components = cached.getComponentsByParentAndType().getList(parentId + providerType);
- if (components == null) return Collections.EMPTY_LIST;
- return Collections.unmodifiableList(components);
+ public Stream getComponentsStream(String parentId, String providerType) {
+ if (isUpdated()) return updated.getComponentsStream(parentId, providerType);
+ return cached.getComponentsByParentAndType().getList(parentId + providerType).stream();
}
@Override
- public List getComponents(String parentId) {
- if (isUpdated()) return updated.getComponents(parentId);
- List components = cached.getComponentsByParent().getList(parentId);
- if (components == null) return Collections.EMPTY_LIST;
- return Collections.unmodifiableList(components);
+ public Stream getComponentsStream(String parentId) {
+ if (isUpdated()) return updated.getComponentsStream(parentId);
+ return cached.getComponentsByParent().getList(parentId).stream();
}
@Override
- public List getComponents() {
- if (isUpdated()) return updated.getComponents();
- List results = new LinkedList<>();
- results.addAll(cached.getComponents().values());
- return Collections.unmodifiableList(results);
+ public Stream getComponentsStream() {
+ if (isUpdated()) return updated.getComponentsStream();
+ return cached.getComponents().values().stream();
}
@Override
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmCacheSession.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmCacheSession.java
index a7e7e95a68..e68e16d0b8 100755
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmCacheSession.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmCacheSession.java
@@ -468,27 +468,20 @@ public class RealmCacheSession implements CacheRealmProvider {
}
@Override
- public List getRealmsWithProviderType(Class> type) {
+ public Stream getRealmsWithProviderTypeStream(Class> type) {
// Retrieve realms from backend
- List backendRealms = getRealmDelegate().getRealmsWithProviderType(type);
- return getRealms(backendRealms);
+ return getRealms(getRealmDelegate().getRealmsWithProviderTypeStream(type));
}
@Override
- public List getRealms() {
+ public Stream getRealmsStream() {
// Retrieve realms from backend
- List backendRealms = getRealmDelegate().getRealms();
- return getRealms(backendRealms);
+ return getRealms(getRealmDelegate().getRealmsStream());
}
- private List getRealms(List backendRealms) {
+ private Stream getRealms(Stream backendRealms) {
// Return cache delegates to ensure cache invalidated during write operations
- List cachedRealms = new LinkedList<>();
- for (RealmModel realm : backendRealms) {
- RealmModel cached = getRealm(realm.getId());
- cachedRealms.add(cached);
- }
- return cachedRealms;
+ return backendRealms.map(RealmModel::getId).map(this::getRealm);
}
@Override
@@ -1240,8 +1233,8 @@ public class RealmCacheSession implements CacheRealmProvider {
}
@Override
- public List listClientInitialAccess(RealmModel realm) {
- return getRealmDelegate().listClientInitialAccess(realm);
+ public Stream listClientInitialAccessStream(RealmModel realm) {
+ return getRealmDelegate().listClientInitialAccessStream(realm);
}
@Override
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/CachedRealm.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/CachedRealm.java
index ff2460d0ab..ccdf445deb 100755
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/CachedRealm.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/CachedRealm.java
@@ -35,7 +35,6 @@ import org.keycloak.models.RequiredActionProviderModel;
import org.keycloak.models.RequiredCredentialModel;
import org.keycloak.models.WebAuthnPolicy;
-import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
@@ -43,6 +42,7 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.function.Function;
import java.util.stream.Collectors;
/**
@@ -113,14 +113,14 @@ public class CachedRealm extends AbstractExtendableRevisioned {
protected List requiredCredentials;
protected MultivaluedHashMap componentsByParent = new MultivaluedHashMap<>();
protected MultivaluedHashMap componentsByParentAndType = new MultivaluedHashMap<>();
- protected Map components = new HashMap<>();
+ protected Map components;
protected List identityProviders;
protected Map browserSecurityHeaders;
protected Map smtpConfig;
protected Map authenticationFlows = new HashMap<>();
protected List authenticationFlowList;
- protected Map authenticatorConfigs = new HashMap<>();
+ protected Map authenticatorConfigs;
protected Map requiredActionProviders = new HashMap<>();
protected List requiredActionProviderList;
protected Map requiredActionProvidersByAlias = new HashMap<>();
@@ -224,17 +224,14 @@ public class CachedRealm extends AbstractExtendableRevisioned {
adminTheme = model.getAdminTheme();
emailTheme = model.getEmailTheme();
- requiredCredentials = model.getRequiredCredentials();
+ requiredCredentials = model.getRequiredCredentialsStream().collect(Collectors.toList());
userActionTokenLifespans = Collections.unmodifiableMap(new HashMap<>(model.getUserActionTokenLifespans()));
- this.identityProviders = new ArrayList<>();
-
- for (IdentityProviderModel identityProviderModel : model.getIdentityProviders()) {
- this.identityProviders.add(new IdentityProviderModel(identityProviderModel));
- }
+ this.identityProviders = model.getIdentityProvidersStream().map(IdentityProviderModel::new)
+ .collect(Collectors.toList());
this.identityProviders = Collections.unmodifiableList(this.identityProviders);
- this.identityProviderMapperSet = model.getIdentityProviderMappers();
+ this.identityProviderMapperSet = model.getIdentityProviderMappersStream().collect(Collectors.toSet());
for (IdentityProviderMapperModel mapper : identityProviderMapperSet) {
identityProviderMappers.add(mapper.getIdentityProviderAlias(), mapper);
}
@@ -246,8 +243,8 @@ public class CachedRealm extends AbstractExtendableRevisioned {
eventsEnabled = model.isEventsEnabled();
eventsExpiration = model.getEventsExpiration();
- eventsListeners = model.getEventsListeners();
- enabledEventTypes = model.getEnabledEventTypes();
+ eventsListeners = model.getEventsListenersStream().collect(Collectors.toSet());
+ enabledEventTypes = model.getEnabledEventTypesStream().collect(Collectors.toSet());
adminEventsEnabled = model.isAdminEventsEnabled();
adminEventsDetailsEnabled = model.isAdminEventsDetailsEnabled();
@@ -259,25 +256,24 @@ public class CachedRealm extends AbstractExtendableRevisioned {
cacheClientScopes(model);
internationalizationEnabled = model.isInternationalizationEnabled();
- supportedLocales = model.getSupportedLocales();
+ supportedLocales = model.getSupportedLocalesStream().collect(Collectors.toSet());
defaultLocale = model.getDefaultLocale();
- authenticationFlowList = model.getAuthenticationFlows();
+ authenticationFlowList = model.getAuthenticationFlowsStream().collect(Collectors.toList());
for (AuthenticationFlowModel flow : authenticationFlowList) {
this.authenticationFlows.put(flow.getId(), flow);
authenticationExecutions.put(flow.getId(), new LinkedList<>());
- for (AuthenticationExecutionModel execution : model.getAuthenticationExecutions(flow.getId())) {
+ model.getAuthenticationExecutionsStream(flow.getId()).forEachOrdered(execution -> {
authenticationExecutions.add(flow.getId(), execution);
executionsById.put(execution.getId(), execution);
if (execution.getFlowId() != null) {
executionsByFlowId.put(execution.getFlowId(), execution);
}
- }
+ });
}
- for (AuthenticatorConfigModel authenticator : model.getAuthenticatorConfigs()) {
- authenticatorConfigs.put(authenticator.getId(), authenticator);
- }
- requiredActionProviderList = model.getRequiredActionProviders();
+ authenticatorConfigs = model.getAuthenticatorConfigsStream()
+ .collect(Collectors.toMap(AuthenticatorConfigModel::getId, Function.identity()));
+ requiredActionProviderList = model.getRequiredActionProvidersStream().collect(Collectors.toList());
for (RequiredActionProviderModel action : requiredActionProviderList) {
this.requiredActionProviders.put(action.getId(), action);
requiredActionProvidersByAlias.put(action.getAlias(), action);
@@ -292,15 +288,13 @@ public class CachedRealm extends AbstractExtendableRevisioned {
clientAuthenticationFlow = model.getClientAuthenticationFlow();
dockerAuthenticationFlow = model.getDockerAuthenticationFlow();
- for (ComponentModel component : model.getComponents()) {
- componentsByParentAndType.add(component.getParentId() + component.getProviderType(), component);
- }
- for (ComponentModel component : model.getComponents()) {
- componentsByParent.add(component.getParentId(), component);
- }
- for (ComponentModel component : model.getComponents()) {
- components.put(component.getId(), component);
- }
+ model.getComponentsStream().forEach(component ->
+ componentsByParentAndType.add(component.getParentId() + component.getProviderType(), component)
+ );
+ model.getComponentsStream().forEach(component ->
+ componentsByParent.add(component.getParentId(), component)
+ );
+ components = model.getComponentsStream().collect(Collectors.toMap(component -> component.getId(), Function.identity()));
try {
attributes = model.getAttributes();
@@ -310,15 +304,11 @@ public class CachedRealm extends AbstractExtendableRevisioned {
}
protected void cacheClientScopes(RealmModel model) {
- for (ClientScopeModel clientScope : model.getClientScopes()) {
- clientScopes.add(clientScope.getId());
- }
- for (ClientScopeModel clientScope : model.getDefaultClientScopes(true)) {
- defaultDefaultClientScopes.add(clientScope.getId());
- }
- for (ClientScopeModel clientScope : model.getDefaultClientScopes(false)) {
- optionalDefaultClientScopes.add(clientScope.getId());
- }
+ clientScopes = model.getClientScopesStream().map(ClientScopeModel::getId).collect(Collectors.toList());
+ defaultDefaultClientScopes = model.getDefaultClientScopesStream(true).map(ClientScopeModel::getId)
+ .collect(Collectors.toList());
+ optionalDefaultClientScopes = model.getDefaultClientScopesStream(false).map(ClientScopeModel::getId)
+ .collect(Collectors.toList());
}
public String getMasterAdminClient() {
diff --git a/model/jpa/src/main/java/org/keycloak/events/jpa/JpaAdminEventQuery.java b/model/jpa/src/main/java/org/keycloak/events/jpa/JpaAdminEventQuery.java
index 15c58c225c..d0a892baf7 100755
--- a/model/jpa/src/main/java/org/keycloak/events/jpa/JpaAdminEventQuery.java
+++ b/model/jpa/src/main/java/org/keycloak/events/jpa/JpaAdminEventQuery.java
@@ -33,6 +33,9 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
+import java.util.stream.Stream;
+
+import static org.keycloak.utils.StreamsUtil.closing;
/**
* @author Giriraj Sharma
@@ -140,7 +143,7 @@ public class JpaAdminEventQuery implements AdminEventQuery {
}
@Override
- public List getResultList() {
+ public Stream getResultStream() {
if (!predicates.isEmpty()) {
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
}
@@ -157,12 +160,7 @@ public class JpaAdminEventQuery implements AdminEventQuery {
query.setMaxResults(maxResults);
}
- List events = new LinkedList();
- for (AdminEventEntity e : query.getResultList()) {
- events.add(JpaEventStoreProvider.convertAdminEvent(e));
- }
-
- return events;
+ return closing(query.getResultStream().map(JpaEventStoreProvider::convertAdminEvent));
}
}
diff --git a/model/jpa/src/main/java/org/keycloak/events/jpa/JpaEventQuery.java b/model/jpa/src/main/java/org/keycloak/events/jpa/JpaEventQuery.java
index 4f7a999c82..c3e2035c42 100644
--- a/model/jpa/src/main/java/org/keycloak/events/jpa/JpaEventQuery.java
+++ b/model/jpa/src/main/java/org/keycloak/events/jpa/JpaEventQuery.java
@@ -31,6 +31,9 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
+import java.util.stream.Stream;
+
+import static org.keycloak.utils.StreamsUtil.closing;
/**
* @author Stian Thorgersen
@@ -113,7 +116,7 @@ public class JpaEventQuery implements EventQuery {
}
@Override
- public List getResultList() {
+ public Stream getResultStream() {
if (!predicates.isEmpty()) {
cq.where(cb.and(predicates.toArray(new Predicate[predicates.size()])));
}
@@ -130,12 +133,8 @@ public class JpaEventQuery implements EventQuery {
query.setMaxResults(maxResults);
}
- List events = new LinkedList();
- for (EventEntity e : query.getResultList()) {
- events.add(JpaEventStoreProvider.convertEvent(e));
- }
- return events;
+ return closing(query.getResultStream().map(JpaEventStoreProvider::convertEvent));
}
}
diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java
index 978a5d4dcb..7bcca946bf 100755
--- a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java
+++ b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaRealmProvider.java
@@ -110,26 +110,20 @@ public class JpaRealmProvider implements RealmProvider, ClientProvider, GroupPro
}
@Override
- public List getRealmsWithProviderType(Class> providerType) {
+ public Stream getRealmsWithProviderTypeStream(Class> providerType) {
TypedQuery query = em.createNamedQuery("getRealmIdsWithProviderType", String.class);
query.setParameter("providerType", providerType.getName());
return getRealms(query);
}
@Override
- public List getRealms() {
+ public Stream getRealmsStream() {
TypedQuery query = em.createNamedQuery("getAllRealmIds", String.class);
return getRealms(query);
}
- private List getRealms(TypedQuery query) {
- List entities = query.getResultList();
- List realms = new ArrayList();
- for (String id : entities) {
- RealmModel realm = session.realms().getRealm(id);
- if (realm != null) realms.add(realm);
- }
- return realms;
+ private Stream getRealms(TypedQuery query) {
+ return closing(query.getResultStream().map(session.realms()::getRealm).filter(Objects::nonNull));
}
@Override
@@ -843,16 +837,12 @@ public class JpaRealmProvider implements RealmProvider, ClientProvider, GroupPro
}
@Override
- public List listClientInitialAccess(RealmModel realm) {
+ public Stream listClientInitialAccessStream(RealmModel realm) {
RealmEntity realmEntity = em.find(RealmEntity.class, realm.getId());
TypedQuery query = em.createNamedQuery("findClientInitialAccessByRealm", ClientInitialAccessEntity.class);
query.setParameter("realm", realmEntity);
- List entities = query.getResultList();
-
- return entities.stream()
- .map(this::entityToModel)
- .collect(Collectors.toList());
+ return closing(query.getResultStream().map(this::entityToModel));
}
@Override
diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java
index d5f4daa8ec..7d2aae036c 100755
--- a/model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java
+++ b/model/jpa/src/main/java/org/keycloak/models/jpa/JpaUserProvider.java
@@ -57,15 +57,7 @@ import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Subquery;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
import java.util.stream.Collectors;
import javax.persistence.LockModeType;
@@ -114,12 +106,14 @@ public class JpaUserProvider implements UserProvider, UserCredentialStore {
realm.getDefaultGroupsStream().forEach(userModel::joinGroupImpl);
}
- if (addDefaultRequiredActions){
- for (RequiredActionProviderModel r : realm.getRequiredActionProviders()) {
- if (r.isEnabled() && r.isDefaultAction()) {
- userModel.addRequiredAction(r.getAlias());
- }
- }
+ if (addDefaultRequiredActions) {
+ Optional requiredAction = realm.getRequiredActionProvidersStream()
+ .filter(RequiredActionProviderModel::isEnabled)
+ .filter(RequiredActionProviderModel::isDefaultAction)
+ .map(RequiredActionProviderModel::getAlias)
+ .findFirst();
+ if (requiredAction.isPresent())
+ userModel.addRequiredAction(requiredAction.get());
}
return userModel;
diff --git a/model/jpa/src/main/java/org/keycloak/models/jpa/RealmAdapter.java b/model/jpa/src/main/java/org/keycloak/models/jpa/RealmAdapter.java
index 2d43a8d67d..5c16154d71 100755
--- a/model/jpa/src/main/java/org/keycloak/models/jpa/RealmAdapter.java
+++ b/model/jpa/src/main/java/org/keycloak/models/jpa/RealmAdapter.java
@@ -33,10 +33,10 @@ import javax.persistence.LockModeType;
import javax.persistence.TypedQuery;
import java.util.*;
import java.util.function.Predicate;
-import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Objects.nonNull;
+import static org.keycloak.utils.StreamsUtil.closing;
/**
* @author Bill Burke
@@ -701,19 +701,8 @@ public class RealmAdapter implements RealmModel, JpaModel {
@Override
- public List getRequiredCredentials() {
- Collection entities = realm.getRequiredCredentials();
- if (entities == null) return Collections.EMPTY_LIST;
- List requiredCredentialModels = new LinkedList<>();
- for (RequiredCredentialEntity entity : entities) {
- RequiredCredentialModel model = new RequiredCredentialModel();
- model.setFormLabel(entity.getFormLabel());
- model.setType(entity.getType());
- model.setSecret(entity.isSecret());
- model.setInput(entity.isInput());
- requiredCredentialModels.add(model);
- }
- return Collections.unmodifiableList(requiredCredentialModels);
+ public Stream getRequiredCredentialsStream() {
+ return realm.getRequiredCredentials().stream().map(this::toRequiredCredentialModel);
}
@@ -1179,12 +1168,8 @@ public class RealmAdapter implements RealmModel, JpaModel {
}
@Override
- public Set getEventsListeners() {
- Set eventsListeners = realm.getEventsListeners();
- if (eventsListeners.isEmpty()) return Collections.EMPTY_SET;
- Set copy = new HashSet<>();
- copy.addAll(eventsListeners);
- return Collections.unmodifiableSet(copy);
+ public Stream getEventsListenersStream() {
+ return realm.getEventsListeners().stream();
}
@Override
@@ -1194,12 +1179,8 @@ public class RealmAdapter implements RealmModel, JpaModel {
}
@Override
- public Set getEnabledEventTypes() {
- Set enabledEventTypes = realm.getEnabledEventTypes();
- if (enabledEventTypes.isEmpty()) return Collections.EMPTY_SET;
- Set copy = new HashSet<>();
- copy.addAll(enabledEventTypes);
- return Collections.unmodifiableSet(copy);
+ public Stream getEnabledEventTypesStream() {
+ return realm.getEnabledEventTypes().stream();
}
@Override
@@ -1250,18 +1231,8 @@ public class RealmAdapter implements RealmModel, JpaModel {
}
@Override
- public List getIdentityProviders() {
- List entities = realm.getIdentityProviders();
- if (entities.isEmpty()) return Collections.EMPTY_LIST;
- List identityProviders = new ArrayList();
-
- for (IdentityProviderEntity entity: entities) {
- IdentityProviderModel identityProviderModel = entityToModel(entity);
-
- identityProviders.add(identityProviderModel);
- }
-
- return Collections.unmodifiableList(identityProviders);
+ public Stream getIdentityProvidersStream() {
+ return realm.getIdentityProviders().stream().map(this::entityToModel);
}
private IdentityProviderModel entityToModel(IdentityProviderEntity entity) {
@@ -1288,13 +1259,10 @@ public class RealmAdapter implements RealmModel, JpaModel {
@Override
public IdentityProviderModel getIdentityProviderByAlias(String alias) {
- for (IdentityProviderModel identityProviderModel : getIdentityProviders()) {
- if (identityProviderModel.getAlias().equals(alias)) {
- return identityProviderModel;
- }
- }
-
- return null;
+ return getIdentityProvidersStream()
+ .filter(model -> Objects.equals(model.getAlias(), alias))
+ .findFirst()
+ .orElse(null);
}
@Override
@@ -1414,12 +1382,8 @@ public class RealmAdapter implements RealmModel, JpaModel {
}
@Override
- public Set getSupportedLocales() {
- Set supportedLocales = realm.getSupportedLocales();
- if (supportedLocales == null || supportedLocales.isEmpty()) return Collections.EMPTY_SET;
- Set copy = new HashSet<>();
- copy.addAll(supportedLocales);
- return Collections.unmodifiableSet(copy);
+ public Stream getSupportedLocalesStream() {
+ return realm.getSupportedLocales().stream();
}
@Override
@@ -1440,28 +1404,15 @@ public class RealmAdapter implements RealmModel, JpaModel {
}
@Override
- public Set getIdentityProviderMappers() {
- Collection entities = this.realm.getIdentityProviderMappers();
- if (entities.isEmpty()) return Collections.EMPTY_SET;
- Set mappings = new HashSet();
- for (IdentityProviderMapperEntity entity : entities) {
- IdentityProviderMapperModel mapping = entityToModel(entity);
- mappings.add(mapping);
- }
- return Collections.unmodifiableSet(mappings);
+ public Stream getIdentityProviderMappersStream() {
+ return realm.getIdentityProviderMappers().stream().map(this::entityToModel);
}
@Override
- public Set getIdentityProviderMappersByAlias(String brokerAlias) {
- Set mappings = new HashSet();
- for (IdentityProviderMapperEntity entity : this.realm.getIdentityProviderMappers()) {
- if (!entity.getIdentityProviderAlias().equals(brokerAlias)) {
- continue;
- }
- IdentityProviderMapperModel mapping = entityToModel(entity);
- mappings.add(mapping);
- }
- return mappings;
+ public Stream getIdentityProviderMappersByAliasStream(String brokerAlias) {
+ return realm.getIdentityProviderMappers().stream()
+ .filter(e -> Objects.equals(e.getIdentityProviderAlias(), brokerAlias))
+ .map(this::entityToModel);
}
@Override
@@ -1630,31 +1581,24 @@ public class RealmAdapter implements RealmModel, JpaModel {
}
@Override
- public List getAuthenticationFlows() {
- return realm.getAuthenticationFlows().stream()
- .map(this::entityToModel)
- .collect(Collectors.collectingAndThen(
- Collectors.toList(), Collections::unmodifiableList));
+ public Stream getAuthenticationFlowsStream() {
+ return realm.getAuthenticationFlows().stream().map(this::entityToModel);
}
@Override
public AuthenticationFlowModel getFlowByAlias(String alias) {
- for (AuthenticationFlowModel flow : getAuthenticationFlows()) {
- if (flow.getAlias().equals(alias)) {
- return flow;
- }
- }
- return null;
+ return getAuthenticationFlowsStream()
+ .filter(flow -> Objects.equals(flow.getAlias(), alias))
+ .findFirst()
+ .orElse(null);
}
@Override
public AuthenticatorConfigModel getAuthenticatorConfigByAlias(String alias) {
- for (AuthenticatorConfigModel config : getAuthenticatorConfigs()) {
- if (config.getAlias().equals(alias)) {
- return config;
- }
- }
- return null;
+ return getAuthenticatorConfigsStream()
+ .filter(config -> Objects.equals(config.getAlias(), alias))
+ .findFirst()
+ .orElse(null);
}
protected AuthenticationFlowModel entityToModel(AuthenticationFlowEntity entity) {
@@ -1725,15 +1669,13 @@ public class RealmAdapter implements RealmModel, JpaModel {
}
@Override
- public List getAuthenticationExecutions(String flowId) {
+ public Stream getAuthenticationExecutionsStream(String flowId) {
AuthenticationFlowEntity flow = em.getReference(AuthenticationFlowEntity.class, flowId);
return flow.getExecutions().stream()
.filter(e -> getId().equals(e.getRealm().getId()))
.map(this::entityToModel)
- .sorted(AuthenticationExecutionModel.ExecutionComparator.SINGLETON)
- .collect(Collectors.collectingAndThen(
- Collectors.toList(), Collections::unmodifiableList));
+ .sorted(AuthenticationExecutionModel.ExecutionComparator.SINGLETON);
}
public AuthenticationExecutionModel entityToModel(AuthenticationExecutionEntity entity) {
@@ -1889,14 +1831,8 @@ public class RealmAdapter implements RealmModel, JpaModel {
}
@Override
- public List getAuthenticatorConfigs() {
- Collection entities = realm.getAuthenticatorConfigs();
- if (entities.isEmpty()) return Collections.EMPTY_LIST;
- List authenticators = new LinkedList<>();
- for (AuthenticatorConfigEntity entity : entities) {
- authenticators.add(entityToModel(entity));
- }
- return Collections.unmodifiableList(authenticators);
+ public Stream getAuthenticatorConfigsStream() {
+ return realm.getAuthenticatorConfigs().stream().map(this::entityToModel);
}
@Override
@@ -1973,15 +1909,10 @@ public class RealmAdapter implements RealmModel, JpaModel {
}
@Override
- public List getRequiredActionProviders() {
- Collection entities = realm.getRequiredActionProviders();
- if (entities.isEmpty()) return Collections.EMPTY_LIST;
- List actions = new LinkedList<>();
- for (RequiredActionProviderEntity entity : entities) {
- actions.add(entityToModel(entity));
- }
- Collections.sort(actions, RequiredActionProviderModel.RequiredActionComparator.SINGLETON);
- return Collections.unmodifiableList(actions);
+ public Stream getRequiredActionProvidersStream() {
+ return realm.getRequiredActionProviders().stream()
+ .map(this::entityToModel)
+ .sorted(RequiredActionProviderModel.RequiredActionComparator.SINGLETON);
}
private RequiredActionProviderEntity getRequiredProviderEntity(String id, boolean readForRemove) {
@@ -1995,10 +1926,10 @@ public class RealmAdapter implements RealmModel, JpaModel {
@Override
public RequiredActionProviderModel getRequiredActionProviderByAlias(String alias) {
- for (RequiredActionProviderModel action : getRequiredActionProviders()) {
- if (action.getAlias().equals(alias)) return action;
- }
- return null;
+ return getRequiredActionProvidersStream()
+ .filter(action -> Objects.equals(action.getAlias(), alias))
+ .findFirst()
+ .orElse(null);
}
@Override
@@ -2052,14 +1983,8 @@ public class RealmAdapter implements RealmModel, JpaModel {
}
@Override
- public List getClientScopes() {
- Collection entities = realm.getClientScopes();
- if (entities == null || entities.isEmpty()) return Collections.EMPTY_LIST;
- List list = new LinkedList<>();
- for (ClientScopeEntity entity : entities) {
- list.add(session.realms().getClientScopeById(entity.getId(), this));
- }
- return Collections.unmodifiableList(list);
+ public Stream getClientScopesStream() {
+ return realm.getClientScopes().stream().map(ClientScopeEntity::getId).map(this::getClientScopeById);
}
@Override
@@ -2142,19 +2067,11 @@ public class RealmAdapter implements RealmModel, JpaModel {
}
@Override
- public List getDefaultClientScopes(boolean defaultScope) {
+ public Stream getDefaultClientScopesStream(boolean defaultScope) {
TypedQuery query = em.createNamedQuery("defaultClientScopeRealmMappingIdsByRealm", String.class);
query.setParameter("realm", getEntity());
query.setParameter("defaultScope", defaultScope);
- List ids = query.getResultList();
-
- List clientScopes = new LinkedList<>();
- for (String clientScopeId : ids) {
- ClientScopeModel clientScope = getClientScopeById(clientScopeId);
- if (clientScope == null) continue;
- clientScopes.add(clientScope);
- }
- return clientScopes;
+ return closing(query.getResultStream().map(this::getClientScopeById).filter(Objects::nonNull));
}
@Override
@@ -2273,23 +2190,22 @@ public class RealmAdapter implements RealmModel, JpaModel {
}
@Override
- public List getComponents(String parentId, final String providerType) {
+ public Stream getComponentsStream(String parentId, final String providerType) {
if (parentId == null) parentId = getId();
final String parent = parentId;
- return realm.getComponents().stream()
- .filter(c -> parent.equals(c.getParentId())
- && providerType.equals(c.getProviderType()))
- .map(this::entityToModel)
- .collect(Collectors.toList());
+ Stream componentStream = realm.getComponents().stream()
+ .filter(c -> Objects.equals(parent, c.getParentId()));
+
+ if (providerType != null) {
+ componentStream = componentStream.filter(c -> Objects.equals(providerType, c.getProviderType()));
+ }
+ return componentStream.map(this::entityToModel);
}
@Override
- public List getComponents(final String parentId) {
- return realm.getComponents().stream()
- .filter(c -> parentId.equals(c.getParentId()))
- .map(this::entityToModel)
- .collect(Collectors.toList());
+ public Stream getComponentsStream(final String parentId) {
+ return getComponentsStream(parentId, null);
}
protected ComponentModel entityToModel(ComponentEntity c) {
@@ -2308,9 +2224,18 @@ public class RealmAdapter implements RealmModel, JpaModel {
return model;
}
+ private RequiredCredentialModel toRequiredCredentialModel(RequiredCredentialEntity entity) {
+ RequiredCredentialModel model = new RequiredCredentialModel();
+ model.setFormLabel(entity.getFormLabel());
+ model.setType(entity.getType());
+ model.setSecret(entity.isSecret());
+ model.setInput(entity.isInput());
+ return model;
+ }
+
@Override
- public List getComponents() {
- return realm.getComponents().stream().map(this::entityToModel).collect(Collectors.toList());
+ public Stream getComponentsStream() {
+ return realm.getComponents().stream().map(this::entityToModel);
}
@Override
diff --git a/server-spi-private/src/main/java/org/keycloak/events/EventBuilder.java b/server-spi-private/src/main/java/org/keycloak/events/EventBuilder.java
index 369e28cc47..ea29b775e5 100755
--- a/server-spi-private/src/main/java/org/keycloak/events/EventBuilder.java
+++ b/server-spi-private/src/main/java/org/keycloak/events/EventBuilder.java
@@ -27,9 +27,10 @@ import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel;
import java.util.HashMap;
-import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
/**
* @author Stian Thorgersen
@@ -57,17 +58,19 @@ public class EventBuilder {
}
}
- if (realm.getEventsListeners() != null && !realm.getEventsListeners().isEmpty()) {
- this.listeners = new LinkedList<>();
- for (String id : realm.getEventsListeners()) {
- EventListenerProvider listener = session.getProvider(EventListenerProvider.class, id);
- if (listener != null) {
- listeners.add(listener);
- } else {
- log.error("Event listener '" + id + "' registered, but provider not found");
- }
- }
- }
+
+ this.listeners = realm.getEventsListenersStream()
+ .map(id -> {
+ EventListenerProvider listener = session.getProvider(EventListenerProvider.class, id);
+ if (listener != null) {
+ return listener;
+ } else {
+ log.error("Event listener '" + id + "' registered, but provider not found");
+ return null;
+ }
+ })
+ .filter(Objects::nonNull)
+ .collect(Collectors.toList());
realm(realm);
ipAddress(clientConnection.getRemoteAddr());
@@ -177,7 +180,8 @@ public class EventBuilder {
event.setTime(Time.currentTimeMillis());
if (store != null) {
- if (realm.getEnabledEventTypes() != null && !realm.getEnabledEventTypes().isEmpty() ? realm.getEnabledEventTypes().contains(event.getType().name()) : event.getType().isSaveByDefault()) {
+ Set eventTypes = realm.getEnabledEventTypesStream().collect(Collectors.toSet());
+ if (!eventTypes.isEmpty() ? eventTypes.contains(event.getType().name()) : event.getType().isSaveByDefault()) {
try {
store.onEvent(event);
} catch (Throwable t) {
diff --git a/server-spi-private/src/main/java/org/keycloak/events/EventQuery.java b/server-spi-private/src/main/java/org/keycloak/events/EventQuery.java
index dac4b251a8..57687f93cd 100644
--- a/server-spi-private/src/main/java/org/keycloak/events/EventQuery.java
+++ b/server-spi-private/src/main/java/org/keycloak/events/EventQuery.java
@@ -19,6 +19,8 @@ package org.keycloak.events;
import java.util.Date;
import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
/**
* @author Stian Thorgersen
@@ -43,6 +45,17 @@ public interface EventQuery {
EventQuery maxResults(int results);
- List getResultList();
+ /**
+ * @deprecated Use {@link #getResultStream() getResultStream} instead.
+ */
+ @Deprecated
+ default List getResultList() {
+ return getResultStream().collect(Collectors.toList());
+ }
+ /**
+ * Returns requested results that match given criteria as a stream.
+ * @return Stream of events
+ */
+ Stream getResultStream();
}
diff --git a/server-spi-private/src/main/java/org/keycloak/events/admin/AdminEventQuery.java b/server-spi-private/src/main/java/org/keycloak/events/admin/AdminEventQuery.java
index 5702298190..330130997c 100644
--- a/server-spi-private/src/main/java/org/keycloak/events/admin/AdminEventQuery.java
+++ b/server-spi-private/src/main/java/org/keycloak/events/admin/AdminEventQuery.java
@@ -19,6 +19,8 @@ package org.keycloak.events.admin;
import java.util.Date;
import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
/**
* @author Stian Thorgersen
@@ -127,8 +129,16 @@ public interface AdminEventQuery {
/**
* Executes the query and returns the results
- *
- * @return
+ * @deprecated Use {@link #getResultStream() getResultStream} instead.
*/
- List getResultList();
+ @Deprecated
+ default List getResultList() {
+ return getResultStream().collect(Collectors.toList());
+ }
+
+ /**
+ * Executes the query and returns the results as a stream.
+ * @return Stream of admin events
+ */
+ Stream getResultStream();
}
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_2_0.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_2_0.java
index db5c42b5fb..c11822640d 100755
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_2_0.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_2_0.java
@@ -26,8 +26,6 @@ import org.keycloak.models.RoleModel;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.representations.idm.RealmRepresentation;
-import java.util.List;
-
/**
* @author Bill Burke
* @version $Revision: 1 $
@@ -68,12 +66,10 @@ public class MigrateTo1_2_0 implements Migration {
}
public void migrate(KeycloakSession session) {
- List realms = session.realms().getRealms();
- for (RealmModel realm : realms) {
+ session.realms().getRealmsStream().forEach(realm -> {
setupBrokerService(realm);
setupClientNames(realm);
- }
-
+ });
}
@Override
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_3_0.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_3_0.java
index 85dbad4ccf..b98f25b460 100755
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_3_0.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_3_0.java
@@ -19,7 +19,6 @@ package org.keycloak.migration.migrators;
import org.keycloak.common.util.MultivaluedHashMap;
import org.keycloak.component.ComponentFactory;
-import org.keycloak.component.ComponentModel;
import org.keycloak.migration.ModelVersion;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.LDAPConstants;
@@ -44,11 +43,7 @@ public class MigrateTo1_3_0 implements Migration {
}
public void migrate(KeycloakSession session) {
- List realms = session.realms().getRealms();
- for (RealmModel realm : realms) {
- migrateLDAPProviders(session, realm);
- }
-
+ session.realms().getRealmsStream().forEach(realm -> migrateLDAPProviders(session, realm));
}
@Override
@@ -57,9 +52,7 @@ public class MigrateTo1_3_0 implements Migration {
}
private void migrateLDAPProviders(KeycloakSession session, RealmModel realm) {
- List federationProviders = realm.getUserStorageProviders();
- for (UserStorageProviderModel fedProvider : federationProviders) {
-
+ realm.getUserStorageProvidersStream().forEachOrdered(fedProvider -> {
if (fedProvider.getProviderId().equals(LDAPConstants.LDAP_PROVIDER)) {
fedProvider = new UserStorageProviderModel(fedProvider); // copy don't want to muck with cache
MultivaluedHashMap config = fedProvider.getConfig();
@@ -91,14 +84,13 @@ public class MigrateTo1_3_0 implements Migration {
realm.updateComponent(fedProvider);
// Create default mappers for LDAP
- List mappers = realm.getComponents(fedProvider.getId());
- if (mappers.isEmpty()) {
+ if (realm.getComponentsStream(fedProvider.getId()).count() == 0) {
ProviderFactory ldapFactory = session.getKeycloakSessionFactory().getProviderFactory(UserStorageProvider.class, LDAPConstants.LDAP_PROVIDER);
if (ldapFactory != null) {
((ComponentFactory) ldapFactory).onCreate(session, realm, fedProvider);
}
}
}
- }
+ });
}
}
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_4_0.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_4_0.java
index 792a151680..91783ff978 100755
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_4_0.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_4_0.java
@@ -29,10 +29,10 @@ import org.keycloak.models.utils.DefaultAuthenticationFlows;
import org.keycloak.models.utils.DefaultRequiredActions;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.representations.idm.RealmRepresentation;
-import org.keycloak.storage.UserStorageProviderModel;
import java.util.Arrays;
import java.util.List;
+import java.util.Objects;
/**
* @author Bill Burke
@@ -45,15 +45,11 @@ public class MigrateTo1_4_0 implements Migration {
}
public void migrate(KeycloakSession session) {
- List realms = session.realms().getRealms();
- for (RealmModel realm : realms) {
- migrateRealm(session, realm);
- }
-
+ session.realms().getRealmsStream().forEach(realm -> migrateRealm(session, realm));
}
protected void migrateRealm(KeycloakSession session, RealmModel realm) {
- if (realm.getAuthenticationFlows().size() == 0) {
+ if (realm.getAuthenticationFlowsStream().count() == 0) {
DefaultAuthenticationFlows.migrateFlows(realm);
DefaultRequiredActions.addActions(realm);
}
@@ -71,19 +67,15 @@ public class MigrateTo1_4_0 implements Migration {
private void migrateLDAPMappers(KeycloakSession session, RealmModel realm) {
List mandatoryInLdap = Arrays.asList("username", "username-cn", "first name", "last name");
- for (UserStorageProviderModel providerModel : realm.getUserStorageProviders()) {
- if (providerModel.getProviderId().equals(LDAPConstants.LDAP_PROVIDER)) {
- List mappers = realm.getComponents(providerModel.getId());
- for (ComponentModel mapper : mappers) {
- if (mandatoryInLdap.contains(mapper.getName())) {
- mapper = new ComponentModel(mapper); // don't want to modify cache
- mapper.getConfig().putSingle("is.mandatory.in.ldap", "true");
- realm.updateComponent(mapper);
- }
-
- }
- }
- }
+ realm.getUserStorageProvidersStream()
+ .filter(providerModel -> Objects.equals(providerModel.getProviderId(), LDAPConstants.LDAP_PROVIDER))
+ .forEachOrdered(providerModel -> realm.getComponentsStream(providerModel.getId())
+ .filter(mapper -> mandatoryInLdap.contains(mapper.getName()))
+ .forEach(mapper -> {
+ mapper = new ComponentModel(mapper); // don't want to modify cache
+ mapper.getConfig().putSingle("is.mandatory.in.ldap", "true");
+ realm.updateComponent(mapper);
+ }));
}
private void migrateUsers(KeycloakSession session, RealmModel realm) {
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_5_0.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_5_0.java
index 8ccb3ef458..26e43431ca 100755
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_5_0.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_5_0.java
@@ -25,8 +25,6 @@ import org.keycloak.models.RealmModel;
import org.keycloak.models.utils.DefaultAuthenticationFlows;
import org.keycloak.representations.idm.RealmRepresentation;
-import java.util.List;
-
/**
* @author Bill Burke
* @version $Revision: 1 $
@@ -39,11 +37,7 @@ public class MigrateTo1_5_0 implements Migration {
}
public void migrate(KeycloakSession session) {
- List realms = session.realms().getRealms();
- for (RealmModel realm : realms) {
- migrateRealm(session, realm);
- }
-
+ session.realms().getRealmsStream().forEach(realm -> migrateRealm(session, realm));
}
@Override
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_6_0.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_6_0.java
index d66bfc1896..92f5715bed 100644
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_6_0.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_6_0.java
@@ -29,8 +29,6 @@ import org.keycloak.models.RoleModel;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.representations.idm.RealmRepresentation;
-import java.util.List;
-
/**
* @author Marek Posolda
*/
@@ -51,10 +49,7 @@ public class MigrateTo1_6_0 implements Migration {
throw new RuntimeException("Can't find default locale mapper");
}
- List realms = session.realms().getRealms();
- for (RealmModel realm : realms) {
- migrateRealm(session, localeMapper, realm);
- }
+ session.realms().getRealmsStream().forEach(realm -> migrateRealm(session, localeMapper, realm));
}
@Override
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_7_0.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_7_0.java
index adb6801f24..5d56897a84 100644
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_7_0.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_7_0.java
@@ -21,14 +21,11 @@ import org.keycloak.migration.MigrationProvider;
import org.keycloak.migration.ModelVersion;
import org.keycloak.models.AuthenticationFlowModel;
import org.keycloak.models.Constants;
-import org.keycloak.models.IdentityProviderModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.utils.DefaultAuthenticationFlows;
import org.keycloak.representations.idm.RealmRepresentation;
-import java.util.List;
-
/**
* @author Marek Posolda
*/
@@ -41,11 +38,7 @@ public class MigrateTo1_7_0 implements Migration {
}
public void migrate(KeycloakSession session) {
- List realms = session.realms().getRealms();
- for (RealmModel realm : realms) {
- migrateRealm(session, realm);
-
- }
+ session.realms().getRealmsStream().forEach(realm -> migrateRealm(session, realm));
}
@Override
@@ -65,12 +58,11 @@ public class MigrateTo1_7_0 implements Migration {
DefaultAuthenticationFlows.migrateFlows(realm);
AuthenticationFlowModel firstBrokerLoginFlow = realm.getFlowByAlias(DefaultAuthenticationFlows.FIRST_BROKER_LOGIN_FLOW);
- List identityProviders = realm.getIdentityProviders();
- for (IdentityProviderModel identityProvider : identityProviders) {
- if (identityProvider.getFirstBrokerLoginFlowId() == null) {
- identityProvider.setFirstBrokerLoginFlowId(firstBrokerLoginFlow.getId());
- realm.updateIdentityProvider(identityProvider);
- }
- }
+ realm.getIdentityProvidersStream()
+ .filter(provider -> provider.getFirstBrokerLoginFlowId() == null)
+ .forEach(provider -> {
+ provider.setFirstBrokerLoginFlowId(firstBrokerLoginFlow.getId());
+ realm.updateIdentityProvider(provider);
+ });
}
}
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_8_0.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_8_0.java
index f28bb5479b..231e57f84c 100644
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_8_0.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_8_0.java
@@ -26,7 +26,7 @@ import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.representations.idm.RealmRepresentation;
import org.keycloak.storage.UserStorageProviderModel;
-import java.util.List;
+import java.util.Objects;
/**
* @author Marek Posolda
@@ -41,12 +41,7 @@ public class MigrateTo1_8_0 implements Migration {
public void migrate(KeycloakSession session) {
- List realms = session.realms().getRealms();
- for (RealmModel realm : realms) {
-
- migrateRealm(realm);
-
- }
+ session.realms().getRealmsStream().forEach(this::migrateRealm);
}
@Override
@@ -55,30 +50,22 @@ public class MigrateTo1_8_0 implements Migration {
}
protected void migrateRealm(RealmModel realm) {
- List federationProviders = realm.getUserStorageProviders();
- for (UserStorageProviderModel fedProvider : federationProviders) {
-
- if (fedProvider.getProviderId().equals(LDAPConstants.LDAP_PROVIDER)) {
-
- if (isActiveDirectory(fedProvider)) {
- // Create mapper for MSAD account controls
- if (getMapperByName(realm, fedProvider, "MSAD account controls") == null) {
- ComponentModel mapperModel = KeycloakModelUtils.createComponentModel("MSAD account controls", fedProvider.getId(), LDAPConstants.MSAD_USER_ACCOUNT_CONTROL_MAPPER, "org.keycloak.storage.ldap.mappers.LDAPStorageMapper");
- realm.addComponentModel(mapperModel);
- }
- }
- }
- }
+ realm.getUserStorageProvidersStream()
+ .filter(fedProvider -> Objects.equals(fedProvider.getProviderId(), LDAPConstants.LDAP_PROVIDER))
+ .filter(this::isActiveDirectory)
+ .filter(fedProvider -> Objects.isNull(getMapperByName(realm, fedProvider, "MSAD account controls")))
+ // Create mapper for MSAD account controls
+ .map(fedProvider -> KeycloakModelUtils.createComponentModel("MSAD account controls",
+ fedProvider.getId(), LDAPConstants.MSAD_USER_ACCOUNT_CONTROL_MAPPER,
+ "org.keycloak.storage.ldap.mappers.LDAPStorageMapper"))
+ .forEachOrdered(realm::addComponentModel);
}
public static ComponentModel getMapperByName(RealmModel realm, ComponentModel providerModel, String name) {
- List components = realm.getComponents(providerModel.getId(), "org.keycloak.storage.ldap.mappers.LDAPStorageMapper");
- for (ComponentModel component : components) {
- if (component.getName().equals(name)) {
- return component;
- }
- }
- return null;
+ return realm.getComponentsStream(providerModel.getId(), "org.keycloak.storage.ldap.mappers.LDAPStorageMapper")
+ .filter(component -> Objects.equals(component.getName(), name))
+ .findFirst()
+ .orElse(null);
}
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_9_2.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_9_2.java
index 171d9ef0e5..97d831a558 100644
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_9_2.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo1_9_2.java
@@ -35,9 +35,7 @@ public class MigrateTo1_9_2 implements Migration {
}
public void migrate(KeycloakSession session) {
- for (RealmModel realm : session.realms().getRealms()) {
- migrateRealm(realm);
- }
+ session.realms().getRealmsStream().forEach(this::migrateRealm);
}
@Override
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo2_0_0.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo2_0_0.java
index 788e373a7c..b85eee8ac2 100644
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo2_0_0.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo2_0_0.java
@@ -33,9 +33,7 @@ public class MigrateTo2_0_0 implements Migration {
}
public void migrate(KeycloakSession session) {
- for (RealmModel realm : session.realms().getRealms()) {
- migrateAuthorizationServices(realm);
- }
+ session.realms().getRealmsStream().forEach(this::migrateAuthorizationServices);
}
@Override
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo2_1_0.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo2_1_0.java
index 550dac4ccf..6eef89a99e 100644
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo2_1_0.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo2_1_0.java
@@ -47,10 +47,10 @@ public class MigrateTo2_1_0 implements Migration {
}
public void migrate(KeycloakSession session) {
- for (RealmModel realm : session.realms().getRealms()) {
+ session.realms().getRealmsStream().forEach(realm -> {
migrateDefaultRequiredAction(realm);
migrateRolePolicies(realm, session);
- }
+ });
}
@Override
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo2_2_0.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo2_2_0.java
index 19ab4c4a1c..762c7c9641 100644
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo2_2_0.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo2_2_0.java
@@ -35,9 +35,7 @@ public class MigrateTo2_2_0 implements Migration {
}
public void migrate(KeycloakSession session) {
- for (RealmModel realm : session.realms().getRealms()) {
- addIdentityProviderAuthenticator(realm);
- }
+ session.realms().getRealmsStream().forEach(this::addIdentityProviderAuthenticator);
}
@Override
@@ -47,13 +45,12 @@ public class MigrateTo2_2_0 implements Migration {
}
private void addIdentityProviderAuthenticator(RealmModel realm) {
- String defaultProvider = null;
- for (IdentityProviderModel provider : realm.getIdentityProviders()) {
- if (provider.isEnabled() && provider.isAuthenticateByDefault()) {
- defaultProvider = provider.getAlias();
- break;
- }
- }
+ String defaultProvider = realm.getIdentityProvidersStream()
+ .filter(IdentityProviderModel::isEnabled)
+ .filter(IdentityProviderModel::isAuthenticateByDefault)
+ .map(IdentityProviderModel::getAlias)
+ .findFirst()
+ .orElse(null);
DefaultAuthenticationFlows.addIdentityProviderAuthenticator(realm, defaultProvider);
}
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo2_3_0.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo2_3_0.java
index a2e8c1a149..d147eb2c99 100644
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo2_3_0.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo2_3_0.java
@@ -19,7 +19,6 @@ package org.keycloak.migration.migrators;
import org.keycloak.migration.ModelVersion;
-import org.keycloak.models.ClientScopeModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.representations.idm.RealmRepresentation;
@@ -33,17 +32,13 @@ public class MigrateTo2_3_0 implements Migration {
@Override
public void migrate(KeycloakSession session) {
- for (RealmModel realm : session.realms().getRealms()) {
- migrateRealm(realm);
- }
+ session.realms().getRealmsStream().forEach(this::migrateRealm);
}
protected void migrateRealm(RealmModel realm) {
realm.getClientsStream().forEach(MigrationUtils::updateProtocolMappers);
- for (ClientScopeModel clientScope : realm.getClientScopes()) {
- MigrationUtils.updateProtocolMappers(clientScope);
- }
+ realm.getClientScopesStream().forEach(MigrationUtils::updateProtocolMappers);
}
@Override
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo2_5_0.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo2_5_0.java
index b28264f22f..7744836d27 100644
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo2_5_0.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo2_5_0.java
@@ -33,9 +33,7 @@ public class MigrateTo2_5_0 implements Migration {
@Override
public void migrate(KeycloakSession session) {
- session.realms().getRealms().stream().forEach(
- r -> DefaultKeyProviders.createSecretProvider(r)
- );
+ session.realms().getRealmsStream().forEach(DefaultKeyProviders::createSecretProvider);
}
@Override
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_0_0.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_0_0.java
index 2e8eb3d94a..4a465a0dbd 100644
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_0_0.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_0_0.java
@@ -41,12 +41,7 @@ public class MigrateTo3_0_0 implements Migration {
@Override
public void migrate(KeycloakSession session) {
- for (RealmModel realm : session.realms().getRealms()) {
-
- migrateRealm(realm);
-
- }
-
+ session.realms().getRealmsStream().forEach(this::migrateRealm);
}
@Override
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_1_0.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_1_0.java
index 4f66fc07df..e5bf948def 100644
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_1_0.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_1_0.java
@@ -36,9 +36,7 @@ public class MigrateTo3_1_0 implements Migration {
@Override
public void migrate(KeycloakSession session) {
- for (RealmModel realm : session.realms().getRealms()) {
- migrateRealm(realm);
- }
+ session.realms().getRealmsStream().forEach(this::migrateRealm);
}
protected void migrateRealm(RealmModel realm) {
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_2_0.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_2_0.java
index 13d77e3b35..ef9abc4160 100644
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_2_0.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_2_0.java
@@ -33,10 +33,7 @@ public class MigrateTo3_2_0 implements Migration {
@Override
public void migrate(KeycloakSession session) {
- for (RealmModel realm : session.realms().getRealms()) {
- migrateRealm(session, realm);
-
- }
+ session.realms().getRealmsStream().forEach(realm -> migrateRealm(session, realm));
}
@Override
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_4_0.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_4_0.java
index 8e6c13316c..6accd3d889 100644
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_4_0.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_4_0.java
@@ -17,7 +17,6 @@
package org.keycloak.migration.migrators;
-import org.keycloak.keys.KeyProvider;
import org.keycloak.migration.ModelVersion;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
@@ -37,11 +36,7 @@ public class MigrateTo3_4_0 implements Migration {
@Override
public void migrate(KeycloakSession session) {
- session.realms().getRealms().stream().forEach(
- r -> {
- migrateRealm(r);
- }
- );
+ session.realms().getRealmsStream().forEach(this::migrateRealm);
}
@Override
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_4_1.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_4_1.java
index c855643b2f..7afd9c3206 100644
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_4_1.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_4_1.java
@@ -37,11 +37,7 @@ public class MigrateTo3_4_1 implements Migration {
@Override
public void migrate(KeycloakSession session) {
- session.realms().getRealms().stream().forEach(
- r -> {
- migrateRealm(r);
- }
- );
+ session.realms().getRealmsStream().forEach(this::migrateRealm);
}
@Override
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_4_2.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_4_2.java
index 9edf276322..669505b8b8 100644
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_4_2.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo3_4_2.java
@@ -36,11 +36,7 @@ public class MigrateTo3_4_2 implements Migration {
@Override
public void migrate(KeycloakSession session) {
- session.realms().getRealms().stream().forEach(
- r -> {
- migrateRealm(r);
- }
- );
+ session.realms().getRealmsStream().forEach(this::migrateRealm);
}
@Override
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo4_0_0.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo4_0_0.java
index 96e0a440a1..ac9cdae41d 100644
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo4_0_0.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo4_0_0.java
@@ -18,10 +18,10 @@
package org.keycloak.migration.migrators;
import java.util.List;
+import java.util.Objects;
import org.jboss.logging.Logger;
import org.keycloak.OAuth2Constants;
-import org.keycloak.component.ComponentModel;
import org.keycloak.migration.ModelVersion;
import org.keycloak.models.ClientModel;
import org.keycloak.models.ClientScopeModel;
@@ -48,11 +48,7 @@ public class MigrateTo4_0_0 implements Migration {
@Override
public void migrate(KeycloakSession session) {
- session.realms().getRealms().stream().forEach(
- r -> {
- migrateRealm(session, r, false);
- }
- );
+ session.realms().getRealmsStream().forEach(realm -> migrateRealm(session, realm, false));
}
@Override
@@ -63,13 +59,14 @@ public class MigrateTo4_0_0 implements Migration {
protected void migrateRealm(KeycloakSession session, RealmModel realm, boolean json) {
// Upgrade names of clientScopes to not contain space
- for (ClientScopeModel clientScope : realm.getClientScopes()) {
- if (clientScope.getName().contains(" ")) {
- LOG.debugf("Replacing spaces with underscores in the name of client scope '%s' of realm '%s'", clientScope.getName(), realm.getName());
- String replacedName = clientScope.getName().replaceAll(" ", "_");
- clientScope.setName(replacedName);
- }
- }
+ realm.getClientScopesStream()
+ .filter(clientScope -> clientScope.getName().contains(" "))
+ .forEach(clientScope -> {
+ LOG.debugf("Replacing spaces with underscores in the name of client scope '%s' of realm '%s'",
+ clientScope.getName(), realm.getName());
+ String replacedName = clientScope.getName().replaceAll(" ", "_");
+ clientScope.setName(replacedName);
+ });
if (!json) {
// Add default client scopes. But don't add them to existing clients. For JSON, they were already added
@@ -78,17 +75,17 @@ public class MigrateTo4_0_0 implements Migration {
}
// Upgrade configuration of "allowed-client-templates" client registration policy
- for (ComponentModel component : realm.getComponents(realm.getId(), "org.keycloak.services.clientregistration.policy.ClientRegistrationPolicy")) {
- if ("allowed-client-templates".equals(component.getProviderId())) {
- List configVal = component.getConfig().remove("allowed-client-templates");
- if (configVal != null) {
- component.getConfig().put("allowed-client-scopes", configVal);
- }
- component.put("allow-default-scopes", true);
+ realm.getComponentsStream(realm.getId(), "org.keycloak.services.clientregistration.policy.ClientRegistrationPolicy")
+ .filter(component -> Objects.equals(component.getProviderId(), "allowed-client-templates"))
+ .forEach(component -> {
+ List configVal = component.getConfig().remove("allowed-client-templates");
+ if (configVal != null) {
+ component.getConfig().put("allowed-client-scopes", configVal);
+ }
+ component.put("allow-default-scopes", true);
- realm.updateComponent(component);
- }
- }
+ realm.updateComponent(component);
+ });
// If client has scope for offline_access role (either directly or through fullScopeAllowed), then add offline_access client
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo4_2_0.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo4_2_0.java
index e14ca50cea..748ee544fc 100644
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo4_2_0.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo4_2_0.java
@@ -19,8 +19,7 @@ package org.keycloak.migration.migrators;
import static java.util.Comparator.comparing;
-import java.util.List;
-import java.util.stream.Collectors;
+import java.util.concurrent.atomic.AtomicInteger;
import org.jboss.logging.Logger;
import org.keycloak.migration.ModelVersion;
@@ -45,29 +44,27 @@ public class MigrateTo4_2_0 implements Migration {
@Override
public void migrate(KeycloakSession session) {
- session.realms().getRealms().stream().forEach(r -> {
- migrateRealm(session, r, false);
- });
+ session.realms().getRealmsStream().forEach(this::migrateRealm);
}
@Override
public void migrateImport(KeycloakSession session, RealmModel realm, RealmRepresentation rep, boolean skipUserDependent) {
- migrateRealm(session, realm, true);
+ migrateRealm(realm);
}
- protected void migrateRealm(KeycloakSession session, RealmModel realm, boolean json) {
+ protected void migrateRealm(RealmModel realm) {
// Set default priority of required actions in alphabetical order
- List actions = realm.getRequiredActionProviders().stream()
- .sorted(comparing(RequiredActionProviderModel::getName)).collect(Collectors.toList());
- int priority = 10;
- for (RequiredActionProviderModel model : actions) {
- LOG.debugf("Setting priority '%d' for required action '%s' in realm '%s'", priority, model.getAlias(),
- realm.getName());
- model.setPriority(priority);
- priority += 10;
+ AtomicInteger priority = new AtomicInteger(10);
+ realm.getRequiredActionProvidersStream()
+ .sorted(comparing(RequiredActionProviderModel::getName))
+ .forEachOrdered(model -> {
+ LOG.debugf("Setting priority '%d' for required action '%s' in realm '%s'", priority.get(), model.getAlias(),
+ realm.getName());
+ model.setPriority(priority.get());
+ priority.addAndGet(10);
- // Save
- realm.updateRequiredActionProvider(model);
- }
+ // Save
+ realm.updateRequiredActionProvider(model);
+ });
}
}
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo4_6_0.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo4_6_0.java
index 1891cf68c2..0293d94378 100644
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo4_6_0.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo4_6_0.java
@@ -42,9 +42,7 @@ public class MigrateTo4_6_0 implements Migration {
@Override
public void migrate(KeycloakSession session) {
- session.realms().getRealms().stream().forEach(r -> {
- migrateRealm(session, r, false);
- });
+ session.realms().getRealmsStream().forEach(realm -> migrateRealm(session, realm, false));
}
@Override
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo6_0_0.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo6_0_0.java
index d04780ba95..600345d8ae 100644
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo6_0_0.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo6_0_0.java
@@ -43,9 +43,7 @@ public class MigrateTo6_0_0 implements Migration {
@Override
public void migrate(KeycloakSession session) {
- session.realms().getRealms().stream().forEach(r -> {
- migrateRealm(session, r, false);
- });
+ session.realms().getRealmsStream().forEach(realm -> migrateRealm(session, realm, false));
}
@Override
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo8_0_0.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo8_0_0.java
index 2d6d8541f6..b38b10d22a 100644
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo8_0_0.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo8_0_0.java
@@ -46,11 +46,9 @@ public class MigrateTo8_0_0 implements Migration {
@Override
public void migrate(KeycloakSession session) {
// Perform basic realm migration first (non multi-factor authentication)
- session.realms().getRealms().stream().forEach(realm -> migrateRealmCommon(realm));
+ session.realms().getRealmsStream().forEach(this::migrateRealmCommon);
// Moreover, for multi-factor authentication migrate optional execution of realm flows to subflows
- session.realms().getRealms().stream().forEach(r -> {
- migrateRealmMFA(session, r, false);
- });
+ session.realms().getRealmsStream().forEach(realm -> migrateRealmMFA(realm));
}
@Override
@@ -79,15 +77,12 @@ public class MigrateTo8_0_0 implements Migration {
}
}
- protected void migrateRealmMFA(KeycloakSession session, RealmModel realm, boolean jsn) {
- for (AuthenticationFlowModel authFlow : realm.getAuthenticationFlows()) {
- for (AuthenticationExecutionModel authExecution : realm.getAuthenticationExecutions(authFlow.getId())) {
- // Those were OPTIONAL executions in previous version
- if (authExecution.getRequirement() == AuthenticationExecutionModel.Requirement.CONDITIONAL) {
- migrateOptionalAuthenticationExecution(realm, authFlow, authExecution, true);
- }
- }
- }
+ protected void migrateRealmMFA(RealmModel realm) {
+ realm.getAuthenticationFlowsStream()
+ .forEach(authFlow ->
+ realm.getAuthenticationExecutionsStream(authFlow.getId())
+ .filter(exe -> exe.getRequirement() == AuthenticationExecutionModel.Requirement.CONDITIONAL)
+ .forEachOrdered(exe -> migrateOptionalAuthenticationExecution(realm, authFlow, exe, true)));
}
public static void migrateOptionalAuthenticationExecution(RealmModel realm, AuthenticationFlowModel parentFlow, AuthenticationExecutionModel optionalExecution, boolean updateOptionalExecution) {
diff --git a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo8_0_2.java b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo8_0_2.java
index 1ee95b3aad..675dbe17ce 100644
--- a/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo8_0_2.java
+++ b/server-spi-private/src/main/java/org/keycloak/migration/migrators/MigrateTo8_0_2.java
@@ -19,6 +19,10 @@
package org.keycloak.migration.migrators;
import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
import org.jboss.logging.Logger;
import org.keycloak.migration.ModelVersion;
@@ -28,6 +32,8 @@ import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.representations.idm.RealmRepresentation;
+import static org.keycloak.models.AuthenticationExecutionModel.Requirement.*;
+
/**
* @author Marek Posolda
*/
@@ -44,7 +50,7 @@ public class MigrateTo8_0_2 implements Migration {
@Override
public void migrate(KeycloakSession session) {
- session.realms().getRealms().forEach(this::migrateAuthenticationFlowsWithAlternativeRequirements);
+ session.realms().getRealmsStream().forEach(this::migrateAuthenticationFlowsWithAlternativeRequirements);
}
@Override
@@ -54,47 +60,39 @@ public class MigrateTo8_0_2 implements Migration {
protected void migrateAuthenticationFlowsWithAlternativeRequirements(RealmModel realm) {
- for (AuthenticationFlowModel flow : realm.getAuthenticationFlows()) {
+ for (AuthenticationFlowModel flow : realm.getAuthenticationFlowsStream().collect(Collectors.toList())) {
+ List executions = realm.getAuthenticationExecutionsStream(flow.getId())
+ .collect(Collectors.toList());
- boolean alternativeFound = false;
- boolean requiredFound = false;
- for (AuthenticationExecutionModel execution : realm.getAuthenticationExecutions(flow.getId())) {
- switch (execution.getRequirement()) {
- case REQUIRED:
- case CONDITIONAL:
- requiredFound = true;
- break;
- case ALTERNATIVE:
- alternativeFound = true;
- break;
- }
- }
+ Set requirements = executions.stream()
+ .map(AuthenticationExecutionModel::getRequirement)
+ .collect(Collectors.toSet());
// This flow contains some REQUIRED and ALTERNATIVE at the same level. We will migrate ALTERNATIVES to separate subflows
// to try to preserve same behaviour as in previous versions
- if (requiredFound && alternativeFound) {
+ if (requirements.contains(REQUIRED) || requirements.contains(CONDITIONAL) && requirements.contains(ALTERNATIVE)) {
// Suffix used just to avoid name conflicts
- int suffix = 0;
+ AtomicInteger suffix = new AtomicInteger(0);
LinkedList