keycloak-uncached
Changes
blacklist 24(+21 -3)
docker-compose.yml 2(+1 -1)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedPermissionTicket.java 156(+78 -78)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedPolicy.java 274(+137 -137)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedResource.java 248(+124 -124)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedResourceServer.java 78(+39 -39)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedScope.java 116(+58 -58)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/AuthorizationCacheInvalidationEvent.java 20(+10 -10)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/PermissionTicketRemovedEvent.java 124(+62 -62)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/PermissionTicketUpdatedEvent.java 124(+62 -62)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/PolicyRemovedEvent.java 220(+110 -110)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/PolicyUpdatedEvent.java 220(+110 -110)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ResourceRemovedEvent.java 228(+114 -114)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ResourceServerRemovedEvent.java 184(+92 -92)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ResourceServerUpdatedEvent.java 176(+88 -88)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ResourceUpdatedEvent.java 228(+114 -114)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ScopeRemovedEvent.java 192(+96 -96)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ScopeUpdatedEvent.java 192(+96 -96)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/InfinispanCacheStoreFactoryProviderFactory.java 192(+96 -96)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/PermissionTicketAdapter.java 306(+153 -153)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/PolicyAdapter.java 670(+335 -335)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/ResourceAdapter.java 584(+292 -292)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/ResourceServerAdapter.java 242(+121 -121)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/ScopeAdapter.java 278(+139 -139)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/StoreFactoryCacheManager.java 316(+158 -158)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/StoreFactoryCacheSession.java 2300(+1152 -1148)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/CacheManager.java 450(+225 -225)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/ClientAdapter.java 1338(+669 -669)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/ClientScopeAdapter.java 506(+253 -253)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/AbstractRevisioned.java 16(+9 -7)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/CachedClient.java 498(+249 -249)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/ClientAddedEvent.java 190(+95 -95)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/ClientRemovedEvent.java 238(+119 -119)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/ClientTemplateEvent.java 182(+91 -91)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/ClientUpdatedEvent.java 190(+95 -95)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/GroupAddedEvent.java 184(+92 -92)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/GroupMovedEvent.java 212(+106 -106)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/GroupRemovedEvent.java 198(+99 -99)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/GroupUpdatedEvent.java 176(+88 -88)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RealmCacheInvalidationEvent.java 18(+9 -9)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RealmRemovedEvent.java 182(+91 -91)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RealmUpdatedEvent.java 182(+91 -91)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RoleAddedEvent.java 182(+91 -91)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RoleRemovedEvent.java 190(+95 -95)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RoleUpdatedEvent.java 190(+95 -95)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserCacheInvalidationEvent.java 18(+9 -9)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserCacheRealmInvalidationEvent.java 174(+87 -87)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserConsentsUpdatedEvent.java 174(+87 -87)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserFederationLinkRemovedEvent.java 228(+114 -114)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserFederationLinkUpdatedEvent.java 142(+71 -71)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserFullInvalidationEvent.java 250(+125 -125)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserUpdatedEvent.java 198(+99 -99)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/GroupAdapter.java 556(+278 -278)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/InfinispanCacheRealmProviderFactory.java 194(+97 -97)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/InfinispanUserCacheProviderFactory.java 200(+100 -100)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmAdapter.java 3144(+1572 -1572)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmCacheManager.java 210(+105 -105)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmCacheSession.java 2397(+1199 -1198)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/stream/HasRolePredicate.java 10(+5 -5)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserCacheManager.java 218(+109 -109)
model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserCacheSession.java 1774(+887 -887)
model/infinispan/src/main/resources/META-INF/services/org.keycloak.models.cache.authorization.CachedStoreProviderFactory 2(+1 -1)
model/infinispan/src/main/resources/META-INF/services/org.keycloak.models.cache.CacheRealmProviderFactory 2(+1 -1)
model/infinispan/src/main/resources/META-INF/services/org.keycloak.models.cache.UserCacheProviderFactory 2(+1 -1)
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMultipleAttributesTest.java 488(+244 -244)
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPProvidersIntegrationTest.java 2106(+1053 -1053)
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSyncTest.java 10(+5 -5)
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPMultipleAttributesNoImportTest.java 118(+59 -59)
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPProvidersIntegrationNoImportTest.java 452(+226 -226)
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPRoleMappingsNoImportTest.java 584(+292 -292)
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/ClientStorageTest.java 920(+460 -460)
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageTest.java 1568(+784 -784)
testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CacheTest.java 316(+158 -158)
testsuite/integration-deprecated/src/test/java/org/keycloak/testsuite/federation/storage/BrokenUserStorageTest.java 278(+139 -139)
Details
blacklist 24(+21 -3)
diff --git a/blacklist b/blacklist
index 79c3c53..0df63e5 100644
--- a/blacklist
+++ b/blacklist
@@ -1,5 +1,23 @@
+private static java.util.stream.Stream org.keycloak.models.utils.RoleUtils.expandCompositeRolesStream(org.keycloak.models.RoleModel, java.util.Set)
+private static java.util.stream.Stream org.keycloak.models.utils.RoleUtils.lambda$expandCompositeRoles$3(java.util.Set, org.keycloak.models.RoleModel)
+public java.lang.Object org.keycloak.json.StringOrArrayDeserializer.deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext)
+public static java.lang.Object org.keycloak.util.JsonSerialization.readValue(java.io.InputStream, java.lang.Class)
+public static java.lang.Object org.keycloak.util.JsonSerialization.readValue(java.io.InputStream, java.lang.Class, boolean)
+public static java.util.Collection org.keycloak.models.utils.KeycloakModelUtils.resolveAttribute(org.keycloak.models.UserModel, java.lang.String, boolean)
+public static java.util.Set org.keycloak.models.utils.RoleUtils.expandCompositeRoles(java.util.Set)
+public static java.util.Set org.keycloak.models.utils.RoleUtils.getDeepUserRoleMappings(org.keycloak.models.UserModel)
public static transient java.lang.Object org.keycloak.common.util.reflections.Reflections.invokeMethod(boolean, java.lang.reflect.Method, java.lang.Class, java.lang.Object, java.lang.Object[])
public static transient java.lang.Object org.keycloak.common.util.reflections.Reflections.invokeMethod(boolean, java.lang.reflect.Method, java.lang.Object, java.lang.Object[])
-public static java.lang.Object org.keycloak.util.JsonSerialization.readValue(java.io.InputStream, java.lang.Class, boolean)
-public static java.lang.Object org.keycloak.util.JsonSerialization.readValue(java.io.InputStream, java.lang.Class)
-public java.lang.Object org.keycloak.json.StringOrArrayDeserializer.deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext)
\ No newline at end of file
+public static org.keycloak.models.ClientScopeModel org.keycloak.models.utils.KeycloakModelUtils.getClientScopeByName(org.keycloak.models.RealmModel, java.lang.String)
+public org.keycloak.authorization.store.StoreFactory org.keycloak.authorization.AuthorizationProvider.getLocalStoreFactory()
+private org.keycloak.authorization.store.StoreFactory org.keycloak.authorization.AuthorizationProvider.createStoreFactory(org.keycloak.authorization.store.StoreFactory)
+public org.keycloak.authorization.store.StoreFactory org.keycloak.authorization.AuthorizationProvider.getStoreFactory()
+private org.keycloak.authorization.store.PolicyStore org.keycloak.authorization.AuthorizationProvider.createPolicyWrapper(org.keycloak.authorization.store.StoreFactory)
+static org.keycloak.authorization.store.PolicyStore org.keycloak.authorization.AuthorizationProvider.access$200(org.keycloak.authorization.AuthorizationProvider, org.keycloak.authorization.store.StoreFactory)
+public org.keycloak.authorization.store.PolicyStore org.keycloak.authorization.AuthorizationProvider.1.getPolicyStore()
+private org.keycloak.authorization.store.ResourceStore org.keycloak.authorization.AuthorizationProvider.createResourceStoreWrapper(org.keycloak.authorization.store.StoreFactory)
+static org.keycloak.authorization.store.ResourceStore org.keycloak.authorization.AuthorizationProvider.access$000(org.keycloak.authorization.AuthorizationProvider, org.keycloak.authorization.store.StoreFactory)
+public org.keycloak.authorization.store.ResourceStore org.keycloak.authorization.AuthorizationProvider.1.getResourceStore()
+public static org.keycloak.representations.idm.UserRepresentation org.keycloak.models.utils.ModelToRepresentation.toRepresentation(org.keycloak.models.KeycloakSession, org.keycloak.models.RealmModel, org.keycloak.models.UserModel)
+public static org.keycloak.representations.idm.ClientScopeRepresentation org.keycloak.models.utils.ModelToRepresentation.toRepresentation(org.keycloak.models.ClientScopeModel)
+public static boolean org.keycloak.models.utils.KeycloakModelUtils.searchFor(org.keycloak.models.RoleModel, org.keycloak.models.RoleModel, java.util.Set)
\ No newline at end of file
docker-compose.yml 2(+1 -1)
diff --git a/docker-compose.yml b/docker-compose.yml
index 35d3cf3..1edd3fa 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -11,7 +11,7 @@ services:
environment:
- JAVA_OPTS=${JAVA_OPTS:-"-Xms4096m -Xmx6124m"}
- TRACER_ENABLE=${TRACER_ENABLE:-true}
- - TRACER_MINIMUM_EXECUTION_TIME=${TRACER_MINIMUM_EXECUTION_TIME:-1}
+ - TRACER_MINIMUM_EXECUTION_TIME=${TRACER_MINIMUM_EXECUTION_TIME:-5}
- TRACER_SERIALISE_INTERNALS=false
- TRACER_VERBOSE=true
- TRACER_TRACES=/caching-approaches-comparison/applications/traces/keycloak
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 f95050a..89ba074 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
@@ -39,12 +39,12 @@ import org.keycloak.credential.CredentialModel;
import org.keycloak.federation.kerberos.impl.KerberosUsernamePasswordAuthenticator;
import org.keycloak.federation.kerberos.impl.SPNEGOAuthenticator;
import org.keycloak.models.*;
-import org.keycloak.models.cache.CachedUserModel;
+// import org.keycloak.models.cache.CachedUserModel;
import org.keycloak.models.utils.DefaultRoles;
import org.keycloak.models.utils.ReadOnlyUserModelDelegate;
import org.keycloak.policy.PasswordPolicyManagerProvider;
import org.keycloak.policy.PolicyError;
-import org.keycloak.models.cache.UserCache;
+// import org.keycloak.models.cache.UserCache;
import org.keycloak.models.credential.PasswordUserCredentialModel;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.models.utils.ReadOnlyUserModelDelegate;
@@ -162,14 +162,14 @@ public class LDAPStorageProvider implements UserStorageProvider,
}
// We need to avoid having CachedUserModel as cache is upper-layer then LDAP. Hence having CachedUserModel here may cause StackOverflowError
- if (local instanceof CachedUserModel) {
- local = session.userStorageManager().getUserById(local.getId(), realm);
+ // if (local instanceof CachedUserModel) {
+ // local = session.userStorageManager().getUserById(local.getId(), realm);
- existing = userManager.getManagedProxiedUser(local.getId());
- if (existing != null) {
- return existing;
- }
- }
+ // existing = userManager.getManagedProxiedUser(local.getId());
+ // if (existing != null) {
+ // return existing;
+ // }
+ // }
UserModel proxied = local;
@@ -209,10 +209,10 @@ public class LDAPStorageProvider implements UserStorageProvider,
logger.debugf("Updated LDAP DN of user '%s' to '%s'", local.getUsername(), ldapDn);
local.setSingleAttribute(LDAPConstants.LDAP_ENTRY_DN, ldapDn);
- UserCache userCache = session.userCache();
- if (userCache != null) {
- userCache.evict(realm, local);
- }
+ // UserCache userCache = session.userCache();
+ // if (userCache != null) {
+ // userCache.evict(realm, local);
+ // }
}
}
@@ -746,10 +746,10 @@ public class LDAPStorageProvider implements UserStorageProvider,
logger.warnf("User with username [%s] aready exists and is linked to provider [%s] but is not valid. Stale LDAP_ID on local user is: %s",
username, model.getName(), user.getFirstAttribute(LDAPConstants.LDAP_ID));
logger.warn("Will re-create user");
- UserCache userCache = session.userCache();
- if (userCache != null) {
- userCache.evict(realm, user);
- }
+ // UserCache userCache = session.userCache();
+ // if (userCache != null) {
+ // userCache.evict(realm, user);
+ // }
new UserManager(session).removeUser(realm, user, session.userLocalStorage());
}
}
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 b3ed27a..abc6da2 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
@@ -34,7 +34,7 @@ import org.keycloak.models.LDAPConstants;
import org.keycloak.models.ModelException;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
-import org.keycloak.models.cache.UserCache;
+// import org.keycloak.models.cache.UserCache;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.provider.ProviderConfigProperty;
import org.keycloak.provider.ProviderConfigurationBuilder;
@@ -561,10 +561,10 @@ public class LDAPStorageProviderFactory implements UserStorageProviderFactory<LD
LDAPStorageMapper ldapMapper = ldapFedProvider.getMapperManager().getMapper(mapperModel);
ldapMapper.onImportUserFromLDAP(ldapUser, currentUser, currentRealm, false);
}
- UserCache userCache = session.userCache();
- if (userCache != null) {
- userCache.evict(currentRealm, currentUser);
- }
+ // UserCache userCache = session.userCache();
+ // if (userCache != null) {
+ // userCache.evict(currentRealm, currentUser);
+ // }
logger.debugf("Updated user from LDAP: %s", currentUser.getUsername());
syncResult.increaseUpdated();
} else {
@@ -596,10 +596,10 @@ public class LDAPStorageProviderFactory implements UserStorageProviderFactory<LD
if (username != null) {
UserModel existing = session.userLocalStorage().getUserByUsername(username, currentRealm);
if (existing != null) {
- UserCache userCache = session.userCache();
- if (userCache != null) {
- userCache.evict(currentRealm, existing);
- }
+ // UserCache userCache = session.userCache();
+ // if (userCache != null) {
+ // userCache.evict(currentRealm, existing);
+ // }
session.userLocalStorage().removeUser(currentRealm, existing);
}
}
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedPermissionTicket.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedPermissionTicket.java
index 40631b2..096dc65 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedPermissionTicket.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedPermissionTicket.java
@@ -1,92 +1,92 @@
-/*
- * Copyright 2017 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
+// /*
+// * Copyright 2017 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
-package org.keycloak.models.cache.infinispan.authorization.entities;
+// package org.keycloak.models.cache.infinispan.authorization.entities;
-import org.keycloak.authorization.model.PermissionTicket;
-import org.keycloak.authorization.model.Policy;
-import org.keycloak.models.cache.infinispan.entities.AbstractRevisioned;
+// import org.keycloak.authorization.model.PermissionTicket;
+// import org.keycloak.authorization.model.Policy;
+// import org.keycloak.models.cache.infinispan.entities.AbstractRevisioned;
-/**
- * @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
- */
-public class CachedPermissionTicket extends AbstractRevisioned implements InResourceServer {
+// /**
+// * @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
+// */
+// public class CachedPermissionTicket extends AbstractRevisioned implements InResourceServer {
- private final String requester;
- private String owner;
- private String resourceServerId;
- private String resourceId;
- private String scopeId;
- private boolean granted;
- private Long createdTimestamp;
- private Long grantedTimestamp;
- private String policy;
+// private final String requester;
+// private String owner;
+// private String resourceServerId;
+// private String resourceId;
+// private String scopeId;
+// private boolean granted;
+// private Long createdTimestamp;
+// private Long grantedTimestamp;
+// private String policy;
- public CachedPermissionTicket(Long revision, PermissionTicket permissionTicket) {
- super(revision, permissionTicket.getId());
- this.owner = permissionTicket.getOwner();
- requester = permissionTicket.getRequester();
- this.resourceServerId = permissionTicket.getResourceServer().getId();
- this.resourceId = permissionTicket.getResource().getId();
- if (permissionTicket.getScope() != null) {
- this.scopeId = permissionTicket.getScope().getId();
- }
- this.granted = permissionTicket.isGranted();
- createdTimestamp = permissionTicket.getCreatedTimestamp();
- grantedTimestamp = permissionTicket.getGrantedTimestamp();
- Policy policy = permissionTicket.getPolicy();
- if (policy != null) {
- this.policy = policy.getId();
- }
- }
+// public CachedPermissionTicket(Long revision, PermissionTicket permissionTicket) {
+// super(revision, permissionTicket.getId());
+// this.owner = permissionTicket.getOwner();
+// requester = permissionTicket.getRequester();
+// this.resourceServerId = permissionTicket.getResourceServer().getId();
+// this.resourceId = permissionTicket.getResource().getId();
+// if (permissionTicket.getScope() != null) {
+// this.scopeId = permissionTicket.getScope().getId();
+// }
+// this.granted = permissionTicket.isGranted();
+// createdTimestamp = permissionTicket.getCreatedTimestamp();
+// grantedTimestamp = permissionTicket.getGrantedTimestamp();
+// Policy policy = permissionTicket.getPolicy();
+// if (policy != null) {
+// this.policy = policy.getId();
+// }
+// }
- public String getOwner() {
- return owner;
- }
+// public String getOwner() {
+// return owner;
+// }
- public String getRequester() {
- return requester;
- }
+// public String getRequester() {
+// return requester;
+// }
- public String getResourceId() {
- return resourceId;
- }
+// public String getResourceId() {
+// return resourceId;
+// }
- public String getScopeId() {
- return scopeId;
- }
+// public String getScopeId() {
+// return scopeId;
+// }
- public boolean isGranted() {
- return granted;
- }
+// public boolean isGranted() {
+// return granted;
+// }
- public long getCreatedTimestamp() {
- return createdTimestamp;
- }
+// public long getCreatedTimestamp() {
+// return createdTimestamp;
+// }
- public Long getGrantedTimestamp() {
- return grantedTimestamp;
- }
+// public Long getGrantedTimestamp() {
+// return grantedTimestamp;
+// }
- public String getResourceServerId() {
- return this.resourceServerId;
- }
+// public String getResourceServerId() {
+// return this.resourceServerId;
+// }
- public String getPolicy() {
- return policy;
- }
-}
+// public String getPolicy() {
+// return policy;
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedPolicy.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedPolicy.java
index 062668e..1582267 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedPolicy.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedPolicy.java
@@ -1,137 +1,137 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2016 Red Hat, Inc., and individual contributors
- * as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.authorization.entities;
-
-import org.keycloak.authorization.model.Policy;
-import org.keycloak.authorization.model.Resource;
-import org.keycloak.authorization.model.Scope;
-import org.keycloak.models.cache.infinispan.DefaultLazyLoader;
-import org.keycloak.models.cache.infinispan.LazyLoader;
-import org.keycloak.models.cache.infinispan.entities.AbstractRevisioned;
-import org.keycloak.representations.idm.authorization.DecisionStrategy;
-import org.keycloak.representations.idm.authorization.Logic;
-
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-
-/**
- * @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
- */
-public class CachedPolicy extends AbstractRevisioned implements InResourceServer {
-
- private final String type;
- private final DecisionStrategy decisionStrategy;
- private final Logic logic;
- private final String name;
- private final String description;
- private final String resourceServerId;
- private final LazyLoader<Policy, Set<String>> associatedPoliciesIds;
- private final LazyLoader<Policy, Set<String>> resourcesIds;
- private final LazyLoader<Policy, Set<String>> scopesIds;
- private final LazyLoader<Policy, Map<String, String>> config;
- private final String owner;
-
- public CachedPolicy(Long revision, Policy policy) {
- super(revision, policy.getId());
- this.type = policy.getType();
- this.decisionStrategy = policy.getDecisionStrategy();
- this.logic = policy.getLogic();
- this.name = policy.getName();
- this.description = policy.getDescription();
- this.resourceServerId = policy.getResourceServer().getId();
-
- if (policy.isFetched("associatedPolicies")) {
- Set<String> data = policy.getAssociatedPolicies().stream().map(Policy::getId).collect(Collectors.toSet());
- this.associatedPoliciesIds = source -> data;
- } else {
- this.associatedPoliciesIds = new DefaultLazyLoader<>(source -> source.getAssociatedPolicies().stream().map(Policy::getId).collect(Collectors.toSet()), Collections::emptySet);
- }
-
- if (policy.isFetched("resources")) {
- Set<String> data = policy.getResources().stream().map(Resource::getId).collect(Collectors.toSet());
- this.resourcesIds = source -> data;
- } else {
- this.resourcesIds = new DefaultLazyLoader<>(source -> source.getResources().stream().map(Resource::getId).collect(Collectors.toSet()), Collections::emptySet);
- }
-
- if (policy.isFetched("scopes")) {
- Set<String> data = policy.getScopes().stream().map(Scope::getId).collect(Collectors.toSet());
- this.scopesIds = source -> data;
- } else {
- this.scopesIds = new DefaultLazyLoader<>(source -> source.getScopes().stream().map(Scope::getId).collect(Collectors.toSet()), Collections::emptySet);
- }
-
- if (policy.isFetched("config")) {
- Map<String, String> data = new HashMap<>(policy.getConfig());
- this.config = source -> data;
- } else {
- this.config = new DefaultLazyLoader<>(source -> new HashMap<>(source.getConfig()), Collections::emptyMap);
- }
-
- this.owner = policy.getOwner();
- }
-
- public String getType() {
- return this.type;
- }
-
- public DecisionStrategy getDecisionStrategy() {
- return this.decisionStrategy;
- }
-
- public Logic getLogic() {
- return this.logic;
- }
-
- public Map<String, String> getConfig(Supplier<Policy> policy) {
- return this.config.get(policy);
- }
-
- public String getName() {
- return this.name;
- }
-
- public String getDescription() {
- return this.description;
- }
-
- public Set<String> getAssociatedPoliciesIds(Supplier<Policy> policy) {
- return this.associatedPoliciesIds.get(policy);
- }
-
- public Set<String> getResourcesIds(Supplier<Policy> policy) {
- return this.resourcesIds.get(policy);
- }
-
- public Set<String> getScopesIds(Supplier<Policy> policy) {
- return this.scopesIds.get(policy);
- }
-
- public String getResourceServerId() {
- return this.resourceServerId;
- }
-
- public String getOwner() {
- return owner;
- }
-}
+// /*
+// * JBoss, Home of Professional Open Source.
+// * Copyright 2016 Red Hat, Inc., and individual contributors
+// * as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.authorization.entities;
+
+// import org.keycloak.authorization.model.Policy;
+// import org.keycloak.authorization.model.Resource;
+// import org.keycloak.authorization.model.Scope;
+// import org.keycloak.models.cache.infinispan.DefaultLazyLoader;
+// import org.keycloak.models.cache.infinispan.LazyLoader;
+// import org.keycloak.models.cache.infinispan.entities.AbstractRevisioned;
+// import org.keycloak.representations.idm.authorization.DecisionStrategy;
+// import org.keycloak.representations.idm.authorization.Logic;
+
+// import java.util.Collections;
+// import java.util.HashMap;
+// import java.util.Map;
+// import java.util.Set;
+// import java.util.function.Supplier;
+// import java.util.stream.Collectors;
+
+// /**
+// * @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
+// */
+// public class CachedPolicy extends AbstractRevisioned implements InResourceServer {
+
+// private final String type;
+// private final DecisionStrategy decisionStrategy;
+// private final Logic logic;
+// private final String name;
+// private final String description;
+// private final String resourceServerId;
+// private final LazyLoader<Policy, Set<String>> associatedPoliciesIds;
+// private final LazyLoader<Policy, Set<String>> resourcesIds;
+// private final LazyLoader<Policy, Set<String>> scopesIds;
+// private final LazyLoader<Policy, Map<String, String>> config;
+// private final String owner;
+
+// public CachedPolicy(Long revision, Policy policy) {
+// super(revision, policy.getId());
+// this.type = policy.getType();
+// this.decisionStrategy = policy.getDecisionStrategy();
+// this.logic = policy.getLogic();
+// this.name = policy.getName();
+// this.description = policy.getDescription();
+// this.resourceServerId = policy.getResourceServer().getId();
+
+// if (policy.isFetched("associatedPolicies")) {
+// Set<String> data = policy.getAssociatedPolicies().stream().map(Policy::getId).collect(Collectors.toSet());
+// this.associatedPoliciesIds = source -> data;
+// } else {
+// this.associatedPoliciesIds = new DefaultLazyLoader<>(source -> source.getAssociatedPolicies().stream().map(Policy::getId).collect(Collectors.toSet()), Collections::emptySet);
+// }
+
+// if (policy.isFetched("resources")) {
+// Set<String> data = policy.getResources().stream().map(Resource::getId).collect(Collectors.toSet());
+// this.resourcesIds = source -> data;
+// } else {
+// this.resourcesIds = new DefaultLazyLoader<>(source -> source.getResources().stream().map(Resource::getId).collect(Collectors.toSet()), Collections::emptySet);
+// }
+
+// if (policy.isFetched("scopes")) {
+// Set<String> data = policy.getScopes().stream().map(Scope::getId).collect(Collectors.toSet());
+// this.scopesIds = source -> data;
+// } else {
+// this.scopesIds = new DefaultLazyLoader<>(source -> source.getScopes().stream().map(Scope::getId).collect(Collectors.toSet()), Collections::emptySet);
+// }
+
+// if (policy.isFetched("config")) {
+// Map<String, String> data = new HashMap<>(policy.getConfig());
+// this.config = source -> data;
+// } else {
+// this.config = new DefaultLazyLoader<>(source -> new HashMap<>(source.getConfig()), Collections::emptyMap);
+// }
+
+// this.owner = policy.getOwner();
+// }
+
+// public String getType() {
+// return this.type;
+// }
+
+// public DecisionStrategy getDecisionStrategy() {
+// return this.decisionStrategy;
+// }
+
+// public Logic getLogic() {
+// return this.logic;
+// }
+
+// public Map<String, String> getConfig(Supplier<Policy> policy) {
+// return this.config.get(policy);
+// }
+
+// public String getName() {
+// return this.name;
+// }
+
+// public String getDescription() {
+// return this.description;
+// }
+
+// public Set<String> getAssociatedPoliciesIds(Supplier<Policy> policy) {
+// return this.associatedPoliciesIds.get(policy);
+// }
+
+// public Set<String> getResourcesIds(Supplier<Policy> policy) {
+// return this.resourcesIds.get(policy);
+// }
+
+// public Set<String> getScopesIds(Supplier<Policy> policy) {
+// return this.scopesIds.get(policy);
+// }
+
+// public String getResourceServerId() {
+// return this.resourceServerId;
+// }
+
+// public String getOwner() {
+// return owner;
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedResource.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedResource.java
index 0205550..7185258 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedResource.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedResource.java
@@ -1,124 +1,124 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2016 Red Hat, Inc., and individual contributors
- * as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.authorization.entities;
-
-import org.keycloak.authorization.model.Resource;
-import org.keycloak.authorization.model.Scope;
-import org.keycloak.common.util.MultivaluedHashMap;
-import org.keycloak.models.cache.infinispan.DefaultLazyLoader;
-import org.keycloak.models.cache.infinispan.LazyLoader;
-import org.keycloak.models.cache.infinispan.entities.AbstractRevisioned;
-
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-
-/**
- * @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
- */
-public class CachedResource extends AbstractRevisioned implements InResourceServer {
-
- private final String resourceServerId;
- private final String iconUri;
- private final String owner;
- private final String type;
- private final String name;
- private final String displayName;
- private final boolean ownerManagedAccess;
- private LazyLoader<Resource, Set<String>> scopesIds;
- private LazyLoader<Resource, Set<String>> uris;
- private LazyLoader<Resource, MultivaluedHashMap<String, String>> attributes;
-
- public CachedResource(Long revision, Resource resource) {
- super(revision, resource.getId());
- this.name = resource.getName();
- this.displayName = resource.getDisplayName();
- this.type = resource.getType();
- this.owner = resource.getOwner();
- this.iconUri = resource.getIconUri();
- this.resourceServerId = resource.getResourceServer().getId();
- ownerManagedAccess = resource.isOwnerManagedAccess();
-
- if (resource.isFetched("uris")) {
- Set<String> data = new HashSet<>(resource.getUris());
- this.uris = source -> data;
- } else {
- this.uris = new DefaultLazyLoader<>(source -> new HashSet<>(source.getUris()), Collections::emptySet);
- }
-
- if (resource.isFetched("scopes")) {
- Set<String> data = resource.getScopes().stream().map(Scope::getId).collect(Collectors.toSet());
- this.scopesIds = source -> data;
- } else {
- this.scopesIds = new DefaultLazyLoader<>(source -> source.getScopes().stream().map(Scope::getId).collect(Collectors.toSet()), Collections::emptySet);
- }
-
- if (resource.isFetched("attributes")) {
- MultivaluedHashMap<String, String> data = new MultivaluedHashMap<>(resource.getAttributes());
- this.attributes = source -> data;
- } else {
- this.attributes = new DefaultLazyLoader<>(source -> new MultivaluedHashMap<>(source.getAttributes()), MultivaluedHashMap::new);
- }
- }
-
-
- public String getName() {
- return this.name;
- }
-
- public String getDisplayName() {
- return this.displayName;
- }
-
- public Set<String> getUris(Supplier<Resource> source) {
- return this.uris.get(source);
- }
-
- public String getType() {
- return this.type;
- }
-
- public String getIconUri() {
- return this.iconUri;
- }
-
- public String getOwner() {
- return this.owner;
- }
-
- public boolean isOwnerManagedAccess() {
- return ownerManagedAccess;
- }
-
- public String getResourceServerId() {
- return this.resourceServerId;
- }
-
- public Set<String> getScopesIds(Supplier<Resource> source) {
- return this.scopesIds.get(source);
- }
-
- public Map<String, List<String>> getAttributes(Supplier<Resource> source) {
- return attributes.get(source);
- }
-}
+// /*
+// * JBoss, Home of Professional Open Source.
+// * Copyright 2016 Red Hat, Inc., and individual contributors
+// * as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.authorization.entities;
+
+// import org.keycloak.authorization.model.Resource;
+// import org.keycloak.authorization.model.Scope;
+// import org.keycloak.common.util.MultivaluedHashMap;
+// import org.keycloak.models.cache.infinispan.DefaultLazyLoader;
+// import org.keycloak.models.cache.infinispan.LazyLoader;
+// import org.keycloak.models.cache.infinispan.entities.AbstractRevisioned;
+
+// import java.util.Collections;
+// import java.util.HashSet;
+// import java.util.List;
+// import java.util.Map;
+// import java.util.Set;
+// import java.util.function.Supplier;
+// import java.util.stream.Collectors;
+
+// /**
+// * @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
+// */
+// public class CachedResource extends AbstractRevisioned implements InResourceServer {
+
+// private final String resourceServerId;
+// private final String iconUri;
+// private final String owner;
+// private final String type;
+// private final String name;
+// private final String displayName;
+// private final boolean ownerManagedAccess;
+// private LazyLoader<Resource, Set<String>> scopesIds;
+// private LazyLoader<Resource, Set<String>> uris;
+// private LazyLoader<Resource, MultivaluedHashMap<String, String>> attributes;
+
+// public CachedResource(Long revision, Resource resource) {
+// super(revision, resource.getId());
+// this.name = resource.getName();
+// this.displayName = resource.getDisplayName();
+// this.type = resource.getType();
+// this.owner = resource.getOwner();
+// this.iconUri = resource.getIconUri();
+// this.resourceServerId = resource.getResourceServer().getId();
+// ownerManagedAccess = resource.isOwnerManagedAccess();
+
+// if (resource.isFetched("uris")) {
+// Set<String> data = new HashSet<>(resource.getUris());
+// this.uris = source -> data;
+// } else {
+// this.uris = new DefaultLazyLoader<>(source -> new HashSet<>(source.getUris()), Collections::emptySet);
+// }
+
+// if (resource.isFetched("scopes")) {
+// Set<String> data = resource.getScopes().stream().map(Scope::getId).collect(Collectors.toSet());
+// this.scopesIds = source -> data;
+// } else {
+// this.scopesIds = new DefaultLazyLoader<>(source -> source.getScopes().stream().map(Scope::getId).collect(Collectors.toSet()), Collections::emptySet);
+// }
+
+// if (resource.isFetched("attributes")) {
+// MultivaluedHashMap<String, String> data = new MultivaluedHashMap<>(resource.getAttributes());
+// this.attributes = source -> data;
+// } else {
+// this.attributes = new DefaultLazyLoader<>(source -> new MultivaluedHashMap<>(source.getAttributes()), MultivaluedHashMap::new);
+// }
+// }
+
+
+// public String getName() {
+// return this.name;
+// }
+
+// public String getDisplayName() {
+// return this.displayName;
+// }
+
+// public Set<String> getUris(Supplier<Resource> source) {
+// return this.uris.get(source);
+// }
+
+// public String getType() {
+// return this.type;
+// }
+
+// public String getIconUri() {
+// return this.iconUri;
+// }
+
+// public String getOwner() {
+// return this.owner;
+// }
+
+// public boolean isOwnerManagedAccess() {
+// return ownerManagedAccess;
+// }
+
+// public String getResourceServerId() {
+// return this.resourceServerId;
+// }
+
+// public Set<String> getScopesIds(Supplier<Resource> source) {
+// return this.scopesIds.get(source);
+// }
+
+// public Map<String, List<String>> getAttributes(Supplier<Resource> source) {
+// return attributes.get(source);
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedResourceServer.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedResourceServer.java
index ac07f6e..604fc57 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedResourceServer.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedResourceServer.java
@@ -1,46 +1,46 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2016 Red Hat, Inc., and individual contributors
- * as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
+// /*
+// * JBoss, Home of Professional Open Source.
+// * Copyright 2016 Red Hat, Inc., and individual contributors
+// * as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
-package org.keycloak.models.cache.infinispan.authorization.entities;
+// package org.keycloak.models.cache.infinispan.authorization.entities;
-import org.keycloak.authorization.model.ResourceServer;
-import org.keycloak.models.cache.infinispan.entities.AbstractRevisioned;
-import org.keycloak.representations.idm.authorization.PolicyEnforcementMode;
+// import org.keycloak.authorization.model.ResourceServer;
+// import org.keycloak.models.cache.infinispan.entities.AbstractRevisioned;
+// import org.keycloak.representations.idm.authorization.PolicyEnforcementMode;
-/**
- * @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
- */
-public class CachedResourceServer extends AbstractRevisioned {
+// /**
+// * @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
+// */
+// public class CachedResourceServer extends AbstractRevisioned {
- private final boolean allowRemoteResourceManagement;
- private final PolicyEnforcementMode policyEnforcementMode;
+// private final boolean allowRemoteResourceManagement;
+// private final PolicyEnforcementMode policyEnforcementMode;
- public CachedResourceServer(Long revision, ResourceServer resourceServer) {
- super(revision, resourceServer.getId());
- this.allowRemoteResourceManagement = resourceServer.isAllowRemoteResourceManagement();
- this.policyEnforcementMode = resourceServer.getPolicyEnforcementMode();
- }
+// public CachedResourceServer(Long revision, ResourceServer resourceServer) {
+// super(revision, resourceServer.getId());
+// this.allowRemoteResourceManagement = resourceServer.isAllowRemoteResourceManagement();
+// this.policyEnforcementMode = resourceServer.getPolicyEnforcementMode();
+// }
- public boolean isAllowRemoteResourceManagement() {
- return this.allowRemoteResourceManagement;
- }
+// public boolean isAllowRemoteResourceManagement() {
+// return this.allowRemoteResourceManagement;
+// }
- public PolicyEnforcementMode getPolicyEnforcementMode() {
- return this.policyEnforcementMode;
- }
-}
+// public PolicyEnforcementMode getPolicyEnforcementMode() {
+// return this.policyEnforcementMode;
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedScope.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedScope.java
index e879134..8614ebe 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedScope.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/entities/CachedScope.java
@@ -1,58 +1,58 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2016 Red Hat, Inc., and individual contributors
- * as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.authorization.entities;
-
-import org.keycloak.authorization.model.Scope;
-import org.keycloak.models.cache.infinispan.entities.AbstractRevisioned;
-
-/**
- * @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
- */
-public class CachedScope extends AbstractRevisioned implements InResourceServer {
-
- private String resourceServerId;
- private String name;
- private String displayName;
- private String iconUri;
-
- public CachedScope(Long revision, Scope scope) {
- super(revision, scope.getId());
- this.name = scope.getName();
- this.displayName = scope.getDisplayName();
- this.iconUri = scope.getIconUri();
- this.resourceServerId = scope.getResourceServer().getId();
- }
-
- public String getName() {
- return this.name;
- }
-
- public String getDisplayName() {
- return displayName;
- }
-
- public String getIconUri() {
- return this.iconUri;
- }
-
- @Override
- public String getResourceServerId() {
- return this.resourceServerId;
- }
-}
+// /*
+// * JBoss, Home of Professional Open Source.
+// * Copyright 2016 Red Hat, Inc., and individual contributors
+// * as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.authorization.entities;
+
+// import org.keycloak.authorization.model.Scope;
+// import org.keycloak.models.cache.infinispan.entities.AbstractRevisioned;
+
+// /**
+// * @author <a href="mailto:psilva@redhat.com">Pedro Igor</a>
+// */
+// public class CachedScope extends AbstractRevisioned implements InResourceServer {
+
+// private String resourceServerId;
+// private String name;
+// private String displayName;
+// private String iconUri;
+
+// public CachedScope(Long revision, Scope scope) {
+// super(revision, scope.getId());
+// this.name = scope.getName();
+// this.displayName = scope.getDisplayName();
+// this.iconUri = scope.getIconUri();
+// this.resourceServerId = scope.getResourceServer().getId();
+// }
+
+// public String getName() {
+// return this.name;
+// }
+
+// public String getDisplayName() {
+// return displayName;
+// }
+
+// public String getIconUri() {
+// return this.iconUri;
+// }
+
+// @Override
+// public String getResourceServerId() {
+// return this.resourceServerId;
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/AuthorizationCacheInvalidationEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/AuthorizationCacheInvalidationEvent.java
index 3f4add1..18c9912 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/AuthorizationCacheInvalidationEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/AuthorizationCacheInvalidationEvent.java
@@ -14,16 +14,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.keycloak.models.cache.infinispan.authorization.events;
+// package org.keycloak.models.cache.infinispan.authorization.events;
-import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
+// import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
-import java.util.Set;
+// import java.util.Set;
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public interface AuthorizationCacheInvalidationEvent {
- void addInvalidations(StoreFactoryCacheManager realmCache, Set<String> invalidations);
-}
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public interface AuthorizationCacheInvalidationEvent {
+// void addInvalidations(StoreFactoryCacheManager realmCache, Set<String> invalidations);
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/PermissionTicketRemovedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/PermissionTicketRemovedEvent.java
index f5296e6..e65ee68 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/PermissionTicketRemovedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/PermissionTicketRemovedEvent.java
@@ -1,62 +1,62 @@
-/*
- * Copyright 2017 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.authorization.events;
-
-import java.util.Set;
-
-import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
-import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-public class PermissionTicketRemovedEvent extends InvalidationEvent implements AuthorizationCacheInvalidationEvent {
-
- private String id;
- private String owner;
- private String resource;
- private String scope;
- private String serverId;
- private String requester;
-
- public static PermissionTicketRemovedEvent create(String id, String owner, String requester, String resource, String scope, String serverId) {
- PermissionTicketRemovedEvent event = new PermissionTicketRemovedEvent();
- event.id = id;
- event.owner = owner;
- event.requester = requester;
- event.resource = resource;
- event.scope = scope;
- event.serverId = serverId;
- return event;
- }
-
- @Override
- public String getId() {
- return id;
- }
-
- @Override
- public String toString() {
- return String.format("PermissionTicketRemovedEvent [ id=%s, name=%s]", id, resource);
- }
-
- @Override
- public void addInvalidations(StoreFactoryCacheManager cache, Set<String> invalidations) {
- cache.permissionTicketRemoval(id, owner, requester, resource, scope, serverId, invalidations);
- }
-}
+// /*
+// * Copyright 2017 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.authorization.events;
+
+// import java.util.Set;
+
+// import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
+// import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// public class PermissionTicketRemovedEvent extends InvalidationEvent implements AuthorizationCacheInvalidationEvent {
+
+// private String id;
+// private String owner;
+// private String resource;
+// private String scope;
+// private String serverId;
+// private String requester;
+
+// public static PermissionTicketRemovedEvent create(String id, String owner, String requester, String resource, String scope, String serverId) {
+// PermissionTicketRemovedEvent event = new PermissionTicketRemovedEvent();
+// event.id = id;
+// event.owner = owner;
+// event.requester = requester;
+// event.resource = resource;
+// event.scope = scope;
+// event.serverId = serverId;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return id;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("PermissionTicketRemovedEvent [ id=%s, name=%s]", id, resource);
+// }
+
+// @Override
+// public void addInvalidations(StoreFactoryCacheManager cache, Set<String> invalidations) {
+// cache.permissionTicketRemoval(id, owner, requester, resource, scope, serverId, invalidations);
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/PermissionTicketUpdatedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/PermissionTicketUpdatedEvent.java
index 3323531..cc667f3 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/PermissionTicketUpdatedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/PermissionTicketUpdatedEvent.java
@@ -1,62 +1,62 @@
-/*
- * Copyright 2017 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.authorization.events;
-
-import java.util.Set;
-
-import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
-import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-public class PermissionTicketUpdatedEvent extends InvalidationEvent implements AuthorizationCacheInvalidationEvent {
-
- private String id;
- private String owner;
- private String resource;
- private String scope;
- private String serverId;
- private String requester;
-
- public static PermissionTicketUpdatedEvent create(String id, String owner, String requester, String resource, String scope, String serverId) {
- PermissionTicketUpdatedEvent event = new PermissionTicketUpdatedEvent();
- event.id = id;
- event.owner = owner;
- event.requester = requester;
- event.resource = resource;
- event.scope = scope;
- event.serverId = serverId;
- return event;
- }
-
- @Override
- public String getId() {
- return id;
- }
-
- @Override
- public String toString() {
- return String.format("PermissionTicketUpdatedEvent [ id=%s, name=%s]", id, resource);
- }
-
- @Override
- public void addInvalidations(StoreFactoryCacheManager cache, Set<String> invalidations) {
- cache.permissionTicketUpdated(id, owner, requester, resource, scope, serverId, invalidations);
- }
-}
+// /*
+// * Copyright 2017 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.authorization.events;
+
+// import java.util.Set;
+
+// import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
+// import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// public class PermissionTicketUpdatedEvent extends InvalidationEvent implements AuthorizationCacheInvalidationEvent {
+
+// private String id;
+// private String owner;
+// private String resource;
+// private String scope;
+// private String serverId;
+// private String requester;
+
+// public static PermissionTicketUpdatedEvent create(String id, String owner, String requester, String resource, String scope, String serverId) {
+// PermissionTicketUpdatedEvent event = new PermissionTicketUpdatedEvent();
+// event.id = id;
+// event.owner = owner;
+// event.requester = requester;
+// event.resource = resource;
+// event.scope = scope;
+// event.serverId = serverId;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return id;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("PermissionTicketUpdatedEvent [ id=%s, name=%s]", id, resource);
+// }
+
+// @Override
+// public void addInvalidations(StoreFactoryCacheManager cache, Set<String> invalidations) {
+// cache.permissionTicketUpdated(id, owner, requester, resource, scope, serverId, invalidations);
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/PolicyRemovedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/PolicyRemovedEvent.java
index b8f296d..dcc2005 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/PolicyRemovedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/PolicyRemovedEvent.java
@@ -1,110 +1,110 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.authorization.events;
-
-import java.util.Set;
-
-import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
-import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
-import org.keycloak.models.sessions.infinispan.util.KeycloakMarshallUtil;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import java.util.HashSet;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(PolicyRemovedEvent.ExternalizerImpl.class)
-public class PolicyRemovedEvent extends InvalidationEvent implements AuthorizationCacheInvalidationEvent {
-
- private String id;
- private String name;
- private Set<String> resources;
- private Set<String> resourceTypes;
- private Set<String> scopes;
- private String serverId;
-
- public static PolicyRemovedEvent create(String id, String name, Set<String> resources, Set<String> resourceTypes, Set<String> scopes, String serverId) {
- PolicyRemovedEvent event = new PolicyRemovedEvent();
- event.id = id;
- event.name = name;
- event.resources = resources;
- event.resourceTypes = resourceTypes;
- event.scopes = scopes;
- event.serverId = serverId;
- return event;
- }
-
- @Override
- public String getId() {
- return id;
- }
-
- @Override
- public String toString() {
- return String.format("PolicyRemovedEvent [ id=%s, name=%s]", id, name);
- }
-
- @Override
- public void addInvalidations(StoreFactoryCacheManager cache, Set<String> invalidations) {
- cache.policyRemoval(id, name, resources, resourceTypes, scopes, serverId, invalidations);
- }
-
- public static class ExternalizerImpl implements Externalizer<PolicyRemovedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, PolicyRemovedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.id, output);
- MarshallUtil.marshallString(obj.name, output);
- KeycloakMarshallUtil.writeCollection(obj.scopes, KeycloakMarshallUtil.STRING_EXT, output);
- KeycloakMarshallUtil.writeCollection(obj.resources, KeycloakMarshallUtil.STRING_EXT, output);
- KeycloakMarshallUtil.writeCollection(obj.resourceTypes, KeycloakMarshallUtil.STRING_EXT, output);
- MarshallUtil.marshallString(obj.serverId, output);
- }
-
- @Override
- public PolicyRemovedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public PolicyRemovedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- PolicyRemovedEvent res = new PolicyRemovedEvent();
- res.id = MarshallUtil.unmarshallString(input);
- res.name = MarshallUtil.unmarshallString(input);
- res.scopes = KeycloakMarshallUtil.readCollection(input, KeycloakMarshallUtil.STRING_EXT, HashSet::new);
- res.resources = KeycloakMarshallUtil.readCollection(input, KeycloakMarshallUtil.STRING_EXT, HashSet::new);
- res.resourceTypes = KeycloakMarshallUtil.readCollection(input, KeycloakMarshallUtil.STRING_EXT, HashSet::new);
- res.serverId = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.authorization.events;
+
+// import java.util.Set;
+
+// import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
+// import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
+// import org.keycloak.models.sessions.infinispan.util.KeycloakMarshallUtil;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import java.util.HashSet;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(PolicyRemovedEvent.ExternalizerImpl.class)
+// public class PolicyRemovedEvent extends InvalidationEvent implements AuthorizationCacheInvalidationEvent {
+
+// private String id;
+// private String name;
+// private Set<String> resources;
+// private Set<String> resourceTypes;
+// private Set<String> scopes;
+// private String serverId;
+
+// public static PolicyRemovedEvent create(String id, String name, Set<String> resources, Set<String> resourceTypes, Set<String> scopes, String serverId) {
+// PolicyRemovedEvent event = new PolicyRemovedEvent();
+// event.id = id;
+// event.name = name;
+// event.resources = resources;
+// event.resourceTypes = resourceTypes;
+// event.scopes = scopes;
+// event.serverId = serverId;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return id;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("PolicyRemovedEvent [ id=%s, name=%s]", id, name);
+// }
+
+// @Override
+// public void addInvalidations(StoreFactoryCacheManager cache, Set<String> invalidations) {
+// cache.policyRemoval(id, name, resources, resourceTypes, scopes, serverId, invalidations);
+// }
+
+// public static class ExternalizerImpl implements Externalizer<PolicyRemovedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, PolicyRemovedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.id, output);
+// MarshallUtil.marshallString(obj.name, output);
+// KeycloakMarshallUtil.writeCollection(obj.scopes, KeycloakMarshallUtil.STRING_EXT, output);
+// KeycloakMarshallUtil.writeCollection(obj.resources, KeycloakMarshallUtil.STRING_EXT, output);
+// KeycloakMarshallUtil.writeCollection(obj.resourceTypes, KeycloakMarshallUtil.STRING_EXT, output);
+// MarshallUtil.marshallString(obj.serverId, output);
+// }
+
+// @Override
+// public PolicyRemovedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public PolicyRemovedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// PolicyRemovedEvent res = new PolicyRemovedEvent();
+// res.id = MarshallUtil.unmarshallString(input);
+// res.name = MarshallUtil.unmarshallString(input);
+// res.scopes = KeycloakMarshallUtil.readCollection(input, KeycloakMarshallUtil.STRING_EXT, HashSet::new);
+// res.resources = KeycloakMarshallUtil.readCollection(input, KeycloakMarshallUtil.STRING_EXT, HashSet::new);
+// res.resourceTypes = KeycloakMarshallUtil.readCollection(input, KeycloakMarshallUtil.STRING_EXT, HashSet::new);
+// res.serverId = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/PolicyUpdatedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/PolicyUpdatedEvent.java
index 86912fb..39b9e18 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/PolicyUpdatedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/PolicyUpdatedEvent.java
@@ -1,110 +1,110 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.authorization.events;
-
-import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
-import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
-
-import org.keycloak.models.sessions.infinispan.util.KeycloakMarshallUtil;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import java.util.HashSet;
-import java.util.Set;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(PolicyUpdatedEvent.ExternalizerImpl.class)
-public class PolicyUpdatedEvent extends InvalidationEvent implements AuthorizationCacheInvalidationEvent {
-
- private String id;
- private String name;
- private Set<String> resources;
- private Set<String> resourceTypes;
- private Set<String> scopes;
- private String serverId;
-
- public static PolicyUpdatedEvent create(String id, String name, Set<String> resources, Set<String> resourceTypes, Set<String> scopes, String serverId) {
- PolicyUpdatedEvent event = new PolicyUpdatedEvent();
- event.id = id;
- event.name = name;
- event.resources = resources;
- event.resourceTypes = resourceTypes;
- event.scopes = scopes;
- event.serverId = serverId;
- return event;
- }
-
- @Override
- public String getId() {
- return id;
- }
-
- @Override
- public String toString() {
- return String.format("PolicyUpdatedEvent [ id=%s, name=%s ]", id, name);
- }
-
- @Override
- public void addInvalidations(StoreFactoryCacheManager cache, Set<String> invalidations) {
- cache.policyUpdated(id, name, resources, resourceTypes, scopes, serverId, invalidations);
- }
-
- public static class ExternalizerImpl implements Externalizer<PolicyUpdatedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, PolicyUpdatedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.id, output);
- MarshallUtil.marshallString(obj.name, output);
- KeycloakMarshallUtil.writeCollection(obj.resources, KeycloakMarshallUtil.STRING_EXT, output);
- KeycloakMarshallUtil.writeCollection(obj.resourceTypes, KeycloakMarshallUtil.STRING_EXT, output);
- KeycloakMarshallUtil.writeCollection(obj.scopes, KeycloakMarshallUtil.STRING_EXT, output);
- MarshallUtil.marshallString(obj.serverId, output);
- }
-
- @Override
- public PolicyUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public PolicyUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- PolicyUpdatedEvent res = new PolicyUpdatedEvent();
- res.id = MarshallUtil.unmarshallString(input);
- res.name = MarshallUtil.unmarshallString(input);
- res.resources = KeycloakMarshallUtil.readCollection(input, KeycloakMarshallUtil.STRING_EXT, HashSet::new);
- res.resourceTypes = KeycloakMarshallUtil.readCollection(input, KeycloakMarshallUtil.STRING_EXT, HashSet::new);
- res.scopes = KeycloakMarshallUtil.readCollection(input, KeycloakMarshallUtil.STRING_EXT, HashSet::new);
- res.serverId = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.authorization.events;
+
+// import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
+// import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
+
+// import org.keycloak.models.sessions.infinispan.util.KeycloakMarshallUtil;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import java.util.HashSet;
+// import java.util.Set;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(PolicyUpdatedEvent.ExternalizerImpl.class)
+// public class PolicyUpdatedEvent extends InvalidationEvent implements AuthorizationCacheInvalidationEvent {
+
+// private String id;
+// private String name;
+// private Set<String> resources;
+// private Set<String> resourceTypes;
+// private Set<String> scopes;
+// private String serverId;
+
+// public static PolicyUpdatedEvent create(String id, String name, Set<String> resources, Set<String> resourceTypes, Set<String> scopes, String serverId) {
+// PolicyUpdatedEvent event = new PolicyUpdatedEvent();
+// event.id = id;
+// event.name = name;
+// event.resources = resources;
+// event.resourceTypes = resourceTypes;
+// event.scopes = scopes;
+// event.serverId = serverId;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return id;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("PolicyUpdatedEvent [ id=%s, name=%s ]", id, name);
+// }
+
+// @Override
+// public void addInvalidations(StoreFactoryCacheManager cache, Set<String> invalidations) {
+// cache.policyUpdated(id, name, resources, resourceTypes, scopes, serverId, invalidations);
+// }
+
+// public static class ExternalizerImpl implements Externalizer<PolicyUpdatedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, PolicyUpdatedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.id, output);
+// MarshallUtil.marshallString(obj.name, output);
+// KeycloakMarshallUtil.writeCollection(obj.resources, KeycloakMarshallUtil.STRING_EXT, output);
+// KeycloakMarshallUtil.writeCollection(obj.resourceTypes, KeycloakMarshallUtil.STRING_EXT, output);
+// KeycloakMarshallUtil.writeCollection(obj.scopes, KeycloakMarshallUtil.STRING_EXT, output);
+// MarshallUtil.marshallString(obj.serverId, output);
+// }
+
+// @Override
+// public PolicyUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public PolicyUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// PolicyUpdatedEvent res = new PolicyUpdatedEvent();
+// res.id = MarshallUtil.unmarshallString(input);
+// res.name = MarshallUtil.unmarshallString(input);
+// res.resources = KeycloakMarshallUtil.readCollection(input, KeycloakMarshallUtil.STRING_EXT, HashSet::new);
+// res.resourceTypes = KeycloakMarshallUtil.readCollection(input, KeycloakMarshallUtil.STRING_EXT, HashSet::new);
+// res.scopes = KeycloakMarshallUtil.readCollection(input, KeycloakMarshallUtil.STRING_EXT, HashSet::new);
+// res.serverId = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ResourceRemovedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ResourceRemovedEvent.java
index 0b30046..644ebf3 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ResourceRemovedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ResourceRemovedEvent.java
@@ -1,114 +1,114 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.authorization.events;
-
-import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
-import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
-
-import org.keycloak.models.sessions.infinispan.util.KeycloakMarshallUtil;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import java.util.HashSet;
-import java.util.Set;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(ResourceRemovedEvent.ExternalizerImpl.class)
-public class ResourceRemovedEvent extends InvalidationEvent implements AuthorizationCacheInvalidationEvent {
-
- private String id;
- private String name;
- private String owner;
- private String serverId;
- private String type;
- private Set<String> uris;
- private Set<String> scopes;
-
- public static ResourceRemovedEvent create(String id, String name, String type, Set<String> uris, String owner, Set<String> scopes, String serverId) {
- ResourceRemovedEvent event = new ResourceRemovedEvent();
- event.id = id;
- event.name = name;
- event.type = type;
- event.uris = uris;
- event.owner = owner;
- event.scopes = scopes;
- event.serverId = serverId;
- return event;
- }
-
- @Override
- public String getId() {
- return id;
- }
-
- @Override
- public String toString() {
- return String.format("ResourceRemovedEvent [ id=%s, name=%s ]", id, name);
- }
-
- @Override
- public void addInvalidations(StoreFactoryCacheManager cache, Set<String> invalidations) {
- cache.resourceRemoval(id, name, type, uris, owner, scopes, serverId, invalidations);
- }
-
- public static class ExternalizerImpl implements Externalizer<ResourceRemovedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, ResourceRemovedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.id, output);
- MarshallUtil.marshallString(obj.name, output);
- MarshallUtil.marshallString(obj.type, output);
- KeycloakMarshallUtil.writeCollection(obj.uris, KeycloakMarshallUtil.STRING_EXT, output);
- MarshallUtil.marshallString(obj.owner, output);
- KeycloakMarshallUtil.writeCollection(obj.scopes, KeycloakMarshallUtil.STRING_EXT, output);
- MarshallUtil.marshallString(obj.serverId, output);
- }
-
- @Override
- public ResourceRemovedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public ResourceRemovedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- ResourceRemovedEvent res = new ResourceRemovedEvent();
- res.id = MarshallUtil.unmarshallString(input);
- res.name = MarshallUtil.unmarshallString(input);
- res.type = MarshallUtil.unmarshallString(input);
- res.uris = KeycloakMarshallUtil.readCollection(input, KeycloakMarshallUtil.STRING_EXT, HashSet::new);
- res.owner = MarshallUtil.unmarshallString(input);
- res.scopes = KeycloakMarshallUtil.readCollection(input, KeycloakMarshallUtil.STRING_EXT, HashSet::new);
- res.serverId = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.authorization.events;
+
+// import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
+// import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
+
+// import org.keycloak.models.sessions.infinispan.util.KeycloakMarshallUtil;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import java.util.HashSet;
+// import java.util.Set;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(ResourceRemovedEvent.ExternalizerImpl.class)
+// public class ResourceRemovedEvent extends InvalidationEvent implements AuthorizationCacheInvalidationEvent {
+
+// private String id;
+// private String name;
+// private String owner;
+// private String serverId;
+// private String type;
+// private Set<String> uris;
+// private Set<String> scopes;
+
+// public static ResourceRemovedEvent create(String id, String name, String type, Set<String> uris, String owner, Set<String> scopes, String serverId) {
+// ResourceRemovedEvent event = new ResourceRemovedEvent();
+// event.id = id;
+// event.name = name;
+// event.type = type;
+// event.uris = uris;
+// event.owner = owner;
+// event.scopes = scopes;
+// event.serverId = serverId;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return id;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("ResourceRemovedEvent [ id=%s, name=%s ]", id, name);
+// }
+
+// @Override
+// public void addInvalidations(StoreFactoryCacheManager cache, Set<String> invalidations) {
+// cache.resourceRemoval(id, name, type, uris, owner, scopes, serverId, invalidations);
+// }
+
+// public static class ExternalizerImpl implements Externalizer<ResourceRemovedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, ResourceRemovedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.id, output);
+// MarshallUtil.marshallString(obj.name, output);
+// MarshallUtil.marshallString(obj.type, output);
+// KeycloakMarshallUtil.writeCollection(obj.uris, KeycloakMarshallUtil.STRING_EXT, output);
+// MarshallUtil.marshallString(obj.owner, output);
+// KeycloakMarshallUtil.writeCollection(obj.scopes, KeycloakMarshallUtil.STRING_EXT, output);
+// MarshallUtil.marshallString(obj.serverId, output);
+// }
+
+// @Override
+// public ResourceRemovedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public ResourceRemovedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// ResourceRemovedEvent res = new ResourceRemovedEvent();
+// res.id = MarshallUtil.unmarshallString(input);
+// res.name = MarshallUtil.unmarshallString(input);
+// res.type = MarshallUtil.unmarshallString(input);
+// res.uris = KeycloakMarshallUtil.readCollection(input, KeycloakMarshallUtil.STRING_EXT, HashSet::new);
+// res.owner = MarshallUtil.unmarshallString(input);
+// res.scopes = KeycloakMarshallUtil.readCollection(input, KeycloakMarshallUtil.STRING_EXT, HashSet::new);
+// res.serverId = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ResourceServerRemovedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ResourceServerRemovedEvent.java
index ef432eb..96f1c8a 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ResourceServerRemovedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ResourceServerRemovedEvent.java
@@ -1,92 +1,92 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.authorization.events;
-
-import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
-import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
-
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import java.util.Set;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(ResourceServerRemovedEvent.ExternalizerImpl.class)
-public class ResourceServerRemovedEvent extends InvalidationEvent implements AuthorizationCacheInvalidationEvent {
-
- private String id;
- private String clientId;
-
- public static ResourceServerRemovedEvent create(String id, String clientId) {
- ResourceServerRemovedEvent event = new ResourceServerRemovedEvent();
- event.id = id;
- event.clientId = clientId;
- return event;
- }
-
- @Override
- public String getId() {
- return id;
- }
-
- @Override
- public String toString() {
- return String.format("ResourceServerRemovedEvent [ id=%s, clientId=%s ]", id, clientId);
- }
-
- @Override
- public void addInvalidations(StoreFactoryCacheManager cache, Set<String> invalidations) {
- cache.resourceServerRemoval(id, invalidations);
- }
-
- public static class ExternalizerImpl implements Externalizer<ResourceServerRemovedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, ResourceServerRemovedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.id, output);
- MarshallUtil.marshallString(obj.clientId, output);
- }
-
- @Override
- public ResourceServerRemovedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public ResourceServerRemovedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- ResourceServerRemovedEvent res = new ResourceServerRemovedEvent();
- res.id = MarshallUtil.unmarshallString(input);
- res.clientId = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.authorization.events;
+
+// import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
+// import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
+
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import java.util.Set;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(ResourceServerRemovedEvent.ExternalizerImpl.class)
+// public class ResourceServerRemovedEvent extends InvalidationEvent implements AuthorizationCacheInvalidationEvent {
+
+// private String id;
+// private String clientId;
+
+// public static ResourceServerRemovedEvent create(String id, String clientId) {
+// ResourceServerRemovedEvent event = new ResourceServerRemovedEvent();
+// event.id = id;
+// event.clientId = clientId;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return id;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("ResourceServerRemovedEvent [ id=%s, clientId=%s ]", id, clientId);
+// }
+
+// @Override
+// public void addInvalidations(StoreFactoryCacheManager cache, Set<String> invalidations) {
+// cache.resourceServerRemoval(id, invalidations);
+// }
+
+// public static class ExternalizerImpl implements Externalizer<ResourceServerRemovedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, ResourceServerRemovedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.id, output);
+// MarshallUtil.marshallString(obj.clientId, output);
+// }
+
+// @Override
+// public ResourceServerRemovedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public ResourceServerRemovedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// ResourceServerRemovedEvent res = new ResourceServerRemovedEvent();
+// res.id = MarshallUtil.unmarshallString(input);
+// res.clientId = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ResourceServerUpdatedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ResourceServerUpdatedEvent.java
index f46611b..5652029 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ResourceServerUpdatedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ResourceServerUpdatedEvent.java
@@ -1,88 +1,88 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.authorization.events;
-
-import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
-import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
-
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import java.util.Set;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(ResourceServerUpdatedEvent.ExternalizerImpl.class)
-public class ResourceServerUpdatedEvent extends InvalidationEvent implements AuthorizationCacheInvalidationEvent {
-
- private String id;
-
- public static ResourceServerUpdatedEvent create(String id) {
- ResourceServerUpdatedEvent event = new ResourceServerUpdatedEvent();
- event.id = id;
- return event;
- }
-
- @Override
- public String getId() {
- return id;
- }
-
- @Override
- public String toString() {
- return String.format("ResourceServerRemovedEvent [ id=%s, clientId=%s ]", id, id);
- }
-
- @Override
- public void addInvalidations(StoreFactoryCacheManager cache, Set<String> invalidations) {
- cache.resourceServerUpdated(id, invalidations);
- }
-
- public static class ExternalizerImpl implements Externalizer<ResourceServerUpdatedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, ResourceServerUpdatedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.id, output);
- }
-
- @Override
- public ResourceServerUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public ResourceServerUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- ResourceServerUpdatedEvent res = new ResourceServerUpdatedEvent();
- res.id = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.authorization.events;
+
+// import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
+// import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
+
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import java.util.Set;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(ResourceServerUpdatedEvent.ExternalizerImpl.class)
+// public class ResourceServerUpdatedEvent extends InvalidationEvent implements AuthorizationCacheInvalidationEvent {
+
+// private String id;
+
+// public static ResourceServerUpdatedEvent create(String id) {
+// ResourceServerUpdatedEvent event = new ResourceServerUpdatedEvent();
+// event.id = id;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return id;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("ResourceServerRemovedEvent [ id=%s, clientId=%s ]", id, id);
+// }
+
+// @Override
+// public void addInvalidations(StoreFactoryCacheManager cache, Set<String> invalidations) {
+// cache.resourceServerUpdated(id, invalidations);
+// }
+
+// public static class ExternalizerImpl implements Externalizer<ResourceServerUpdatedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, ResourceServerUpdatedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.id, output);
+// }
+
+// @Override
+// public ResourceServerUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public ResourceServerUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// ResourceServerUpdatedEvent res = new ResourceServerUpdatedEvent();
+// res.id = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ResourceUpdatedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ResourceUpdatedEvent.java
index 10bfb64..4cad431 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ResourceUpdatedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ResourceUpdatedEvent.java
@@ -1,114 +1,114 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.authorization.events;
-
-import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
-import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
-
-import org.keycloak.models.sessions.infinispan.util.KeycloakMarshallUtil;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import java.util.HashSet;
-import java.util.Set;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(ResourceUpdatedEvent.ExternalizerImpl.class)
-public class ResourceUpdatedEvent extends InvalidationEvent implements AuthorizationCacheInvalidationEvent {
-
- private String id;
- private String name;
- private String serverId;
- private String type;
- private Set<String> uris;
- private Set<String> scopes;
- private String owner;
-
- public static ResourceUpdatedEvent create(String id, String name, String type, Set<String> uris, Set<String> scopes, String serverId, String owner) {
- ResourceUpdatedEvent event = new ResourceUpdatedEvent();
- event.id = id;
- event.name = name;
- event.type = type;
- event.uris = uris;
- event.scopes = scopes;
- event.serverId = serverId;
- event.owner = owner;
- return event;
- }
-
- @Override
- public String getId() {
- return id;
- }
-
- @Override
- public String toString() {
- return String.format("ResourceUpdatedEvent [ id=%s, name=%s ]", id, name);
- }
-
- @Override
- public void addInvalidations(StoreFactoryCacheManager cache, Set<String> invalidations) {
- cache.resourceUpdated(id, name, type, uris, scopes, serverId, owner, invalidations);
- }
-
- public static class ExternalizerImpl implements Externalizer<ResourceUpdatedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, ResourceUpdatedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.id, output);
- MarshallUtil.marshallString(obj.name, output);
- MarshallUtil.marshallString(obj.type, output);
- KeycloakMarshallUtil.writeCollection(obj.uris, KeycloakMarshallUtil.STRING_EXT, output);
- KeycloakMarshallUtil.writeCollection(obj.scopes, KeycloakMarshallUtil.STRING_EXT, output);
- MarshallUtil.marshallString(obj.serverId, output);
- MarshallUtil.marshallString(obj.owner, output);
- }
-
- @Override
- public ResourceUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public ResourceUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- ResourceUpdatedEvent res = new ResourceUpdatedEvent();
- res.id = MarshallUtil.unmarshallString(input);
- res.name = MarshallUtil.unmarshallString(input);
- res.type = MarshallUtil.unmarshallString(input);
- res.uris = KeycloakMarshallUtil.readCollection(input, KeycloakMarshallUtil.STRING_EXT, HashSet::new);
- res.scopes = KeycloakMarshallUtil.readCollection(input, KeycloakMarshallUtil.STRING_EXT, HashSet::new);
- res.serverId = MarshallUtil.unmarshallString(input);
- res.owner = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.authorization.events;
+
+// import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
+// import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
+
+// import org.keycloak.models.sessions.infinispan.util.KeycloakMarshallUtil;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import java.util.HashSet;
+// import java.util.Set;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(ResourceUpdatedEvent.ExternalizerImpl.class)
+// public class ResourceUpdatedEvent extends InvalidationEvent implements AuthorizationCacheInvalidationEvent {
+
+// private String id;
+// private String name;
+// private String serverId;
+// private String type;
+// private Set<String> uris;
+// private Set<String> scopes;
+// private String owner;
+
+// public static ResourceUpdatedEvent create(String id, String name, String type, Set<String> uris, Set<String> scopes, String serverId, String owner) {
+// ResourceUpdatedEvent event = new ResourceUpdatedEvent();
+// event.id = id;
+// event.name = name;
+// event.type = type;
+// event.uris = uris;
+// event.scopes = scopes;
+// event.serverId = serverId;
+// event.owner = owner;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return id;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("ResourceUpdatedEvent [ id=%s, name=%s ]", id, name);
+// }
+
+// @Override
+// public void addInvalidations(StoreFactoryCacheManager cache, Set<String> invalidations) {
+// cache.resourceUpdated(id, name, type, uris, scopes, serverId, owner, invalidations);
+// }
+
+// public static class ExternalizerImpl implements Externalizer<ResourceUpdatedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, ResourceUpdatedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.id, output);
+// MarshallUtil.marshallString(obj.name, output);
+// MarshallUtil.marshallString(obj.type, output);
+// KeycloakMarshallUtil.writeCollection(obj.uris, KeycloakMarshallUtil.STRING_EXT, output);
+// KeycloakMarshallUtil.writeCollection(obj.scopes, KeycloakMarshallUtil.STRING_EXT, output);
+// MarshallUtil.marshallString(obj.serverId, output);
+// MarshallUtil.marshallString(obj.owner, output);
+// }
+
+// @Override
+// public ResourceUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public ResourceUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// ResourceUpdatedEvent res = new ResourceUpdatedEvent();
+// res.id = MarshallUtil.unmarshallString(input);
+// res.name = MarshallUtil.unmarshallString(input);
+// res.type = MarshallUtil.unmarshallString(input);
+// res.uris = KeycloakMarshallUtil.readCollection(input, KeycloakMarshallUtil.STRING_EXT, HashSet::new);
+// res.scopes = KeycloakMarshallUtil.readCollection(input, KeycloakMarshallUtil.STRING_EXT, HashSet::new);
+// res.serverId = MarshallUtil.unmarshallString(input);
+// res.owner = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ScopeRemovedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ScopeRemovedEvent.java
index 370354e..e96bea9 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ScopeRemovedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ScopeRemovedEvent.java
@@ -1,96 +1,96 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.authorization.events;
-
-import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
-import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
-
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import java.util.Set;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(ScopeRemovedEvent.ExternalizerImpl.class)
-public class ScopeRemovedEvent extends InvalidationEvent implements AuthorizationCacheInvalidationEvent {
-
- private String id;
- private String name;
- private String serverId;
-
- public static ScopeRemovedEvent create(String id, String name, String serverId) {
- ScopeRemovedEvent event = new ScopeRemovedEvent();
- event.id = id;
- event.name = name;
- event.serverId = serverId;
- return event;
- }
-
- @Override
- public String getId() {
- return id;
- }
-
- @Override
- public String toString() {
- return String.format("ScopeRemovedEvent [ id=%s, name=%s]", id, name);
- }
-
- @Override
- public void addInvalidations(StoreFactoryCacheManager cache, Set<String> invalidations) {
- cache.scopeRemoval(id, name, serverId, invalidations);
- }
-
- public static class ExternalizerImpl implements Externalizer<ScopeRemovedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, ScopeRemovedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.id, output);
- MarshallUtil.marshallString(obj.name, output);
- MarshallUtil.marshallString(obj.serverId, output);
- }
-
- @Override
- public ScopeRemovedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public ScopeRemovedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- ScopeRemovedEvent res = new ScopeRemovedEvent();
- res.id = MarshallUtil.unmarshallString(input);
- res.name = MarshallUtil.unmarshallString(input);
- res.serverId = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.authorization.events;
+
+// import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
+// import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
+
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import java.util.Set;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(ScopeRemovedEvent.ExternalizerImpl.class)
+// public class ScopeRemovedEvent extends InvalidationEvent implements AuthorizationCacheInvalidationEvent {
+
+// private String id;
+// private String name;
+// private String serverId;
+
+// public static ScopeRemovedEvent create(String id, String name, String serverId) {
+// ScopeRemovedEvent event = new ScopeRemovedEvent();
+// event.id = id;
+// event.name = name;
+// event.serverId = serverId;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return id;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("ScopeRemovedEvent [ id=%s, name=%s]", id, name);
+// }
+
+// @Override
+// public void addInvalidations(StoreFactoryCacheManager cache, Set<String> invalidations) {
+// cache.scopeRemoval(id, name, serverId, invalidations);
+// }
+
+// public static class ExternalizerImpl implements Externalizer<ScopeRemovedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, ScopeRemovedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.id, output);
+// MarshallUtil.marshallString(obj.name, output);
+// MarshallUtil.marshallString(obj.serverId, output);
+// }
+
+// @Override
+// public ScopeRemovedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public ScopeRemovedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// ScopeRemovedEvent res = new ScopeRemovedEvent();
+// res.id = MarshallUtil.unmarshallString(input);
+// res.name = MarshallUtil.unmarshallString(input);
+// res.serverId = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ScopeUpdatedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ScopeUpdatedEvent.java
index f714b46..e5558c5 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ScopeUpdatedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/events/ScopeUpdatedEvent.java
@@ -1,96 +1,96 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.authorization.events;
-
-import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
-import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
-
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import java.util.Set;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(ScopeUpdatedEvent.ExternalizerImpl.class)
-public class ScopeUpdatedEvent extends InvalidationEvent implements AuthorizationCacheInvalidationEvent {
-
- private String id;
- private String name;
- private String serverId;
-
- public static ScopeUpdatedEvent create(String id, String name, String serverId) {
- ScopeUpdatedEvent event = new ScopeUpdatedEvent();
- event.id = id;
- event.name = name;
- event.serverId = serverId;
- return event;
- }
-
- @Override
- public String getId() {
- return id;
- }
-
- @Override
- public String toString() {
- return String.format("ScopeUpdatedEvent [ id=%s, name=%s ]", id, name);
- }
-
- @Override
- public void addInvalidations(StoreFactoryCacheManager cache, Set<String> invalidations) {
- cache.scopeUpdated(id, name, serverId, invalidations);
- }
-
- public static class ExternalizerImpl implements Externalizer<ScopeUpdatedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, ScopeUpdatedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.id, output);
- MarshallUtil.marshallString(obj.name, output);
- MarshallUtil.marshallString(obj.serverId, output);
- }
-
- @Override
- public ScopeUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public ScopeUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- ScopeUpdatedEvent res = new ScopeUpdatedEvent();
- res.id = MarshallUtil.unmarshallString(input);
- res.name = MarshallUtil.unmarshallString(input);
- res.serverId = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.authorization.events;
+
+// import org.keycloak.models.cache.infinispan.authorization.StoreFactoryCacheManager;
+// import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
+
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import java.util.Set;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(ScopeUpdatedEvent.ExternalizerImpl.class)
+// public class ScopeUpdatedEvent extends InvalidationEvent implements AuthorizationCacheInvalidationEvent {
+
+// private String id;
+// private String name;
+// private String serverId;
+
+// public static ScopeUpdatedEvent create(String id, String name, String serverId) {
+// ScopeUpdatedEvent event = new ScopeUpdatedEvent();
+// event.id = id;
+// event.name = name;
+// event.serverId = serverId;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return id;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("ScopeUpdatedEvent [ id=%s, name=%s ]", id, name);
+// }
+
+// @Override
+// public void addInvalidations(StoreFactoryCacheManager cache, Set<String> invalidations) {
+// cache.scopeUpdated(id, name, serverId, invalidations);
+// }
+
+// public static class ExternalizerImpl implements Externalizer<ScopeUpdatedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, ScopeUpdatedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.id, output);
+// MarshallUtil.marshallString(obj.name, output);
+// MarshallUtil.marshallString(obj.serverId, output);
+// }
+
+// @Override
+// public ScopeUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public ScopeUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// ScopeUpdatedEvent res = new ScopeUpdatedEvent();
+// res.id = MarshallUtil.unmarshallString(input);
+// res.name = MarshallUtil.unmarshallString(input);
+// res.serverId = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/InfinispanCacheStoreFactoryProviderFactory.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/InfinispanCacheStoreFactoryProviderFactory.java
index a5726a0..ca12efe 100755
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/InfinispanCacheStoreFactoryProviderFactory.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/InfinispanCacheStoreFactoryProviderFactory.java
@@ -1,96 +1,96 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.authorization;
-
-import static org.keycloak.models.cache.infinispan.InfinispanCacheRealmProviderFactory.REALM_CLEAR_CACHE_EVENTS;
-
-import org.infinispan.Cache;
-import org.jboss.logging.Logger;
-import org.keycloak.Config;
-import org.keycloak.cluster.ClusterEvent;
-import org.keycloak.cluster.ClusterProvider;
-import org.keycloak.connections.infinispan.InfinispanConnectionProvider;
-import org.keycloak.models.KeycloakSession;
-import org.keycloak.models.KeycloakSessionFactory;
-import org.keycloak.models.cache.authorization.CachedStoreFactoryProvider;
-import org.keycloak.models.cache.authorization.CachedStoreProviderFactory;
-import org.keycloak.models.cache.infinispan.entities.Revisioned;
-import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
-
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
- */
-public class InfinispanCacheStoreFactoryProviderFactory implements CachedStoreProviderFactory {
-
- private static final Logger log = Logger.getLogger(InfinispanCacheStoreFactoryProviderFactory.class);
- public static final String AUTHORIZATION_CLEAR_CACHE_EVENTS = "AUTHORIZATION_CLEAR_CACHE_EVENTS";
- public static final String AUTHORIZATION_INVALIDATION_EVENTS = "AUTHORIZATION_INVALIDATION_EVENTS";
-
- protected volatile StoreFactoryCacheManager storeCache;
-
- @Override
- public CachedStoreFactoryProvider create(KeycloakSession session) {
- lazyInit(session);
- return new StoreFactoryCacheSession(storeCache, session);
- }
-
- private void lazyInit(KeycloakSession session) {
- if (storeCache == null) {
- synchronized (this) {
- if (storeCache == null) {
- Cache<String, Revisioned> cache = session.getProvider(InfinispanConnectionProvider.class).getCache(InfinispanConnectionProvider.AUTHORIZATION_CACHE_NAME);
- Cache<String, Long> revisions = session.getProvider(InfinispanConnectionProvider.class).getCache(InfinispanConnectionProvider.AUTHORIZATION_REVISIONS_CACHE_NAME);
- storeCache = new StoreFactoryCacheManager(cache, revisions);
- ClusterProvider cluster = session.getProvider(ClusterProvider.class);
-
- cluster.registerListener(AUTHORIZATION_INVALIDATION_EVENTS, (ClusterEvent event) -> {
-
- InvalidationEvent invalidationEvent = (InvalidationEvent) event;
- storeCache.invalidationEventReceived(invalidationEvent);
-
- });
-
- cluster.registerListener(AUTHORIZATION_CLEAR_CACHE_EVENTS, (ClusterEvent event) -> storeCache.clear());
- cluster.registerListener(REALM_CLEAR_CACHE_EVENTS, (ClusterEvent event) -> storeCache.clear());
-
- log.debug("Registered cluster listeners");
- }
- }
- }
- }
-
- @Override
- public void init(Config.Scope config) {
- }
-
- @Override
- public void postInit(KeycloakSessionFactory factory) {
-
- }
-
- @Override
- public void close() {
- }
-
- @Override
- public String getId() {
- return "default";
- }
-
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.authorization;
+
+// import static org.keycloak.models.cache.infinispan.InfinispanCacheRealmProviderFactory.REALM_CLEAR_CACHE_EVENTS;
+
+// import org.infinispan.Cache;
+// import org.jboss.logging.Logger;
+// import org.keycloak.Config;
+// import org.keycloak.cluster.ClusterEvent;
+// import org.keycloak.cluster.ClusterProvider;
+// import org.keycloak.connections.infinispan.InfinispanConnectionProvider;
+// import org.keycloak.models.KeycloakSession;
+// import org.keycloak.models.KeycloakSessionFactory;
+// import org.keycloak.models.cache.authorization.CachedStoreFactoryProvider;
+// import org.keycloak.models.cache.authorization.CachedStoreProviderFactory;
+// import org.keycloak.models.cache.infinispan.entities.Revisioned;
+// import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
+
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
+// */
+// public class InfinispanCacheStoreFactoryProviderFactory implements CachedStoreProviderFactory {
+
+// private static final Logger log = Logger.getLogger(InfinispanCacheStoreFactoryProviderFactory.class);
+// public static final String AUTHORIZATION_CLEAR_CACHE_EVENTS = "AUTHORIZATION_CLEAR_CACHE_EVENTS";
+// public static final String AUTHORIZATION_INVALIDATION_EVENTS = "AUTHORIZATION_INVALIDATION_EVENTS";
+
+// protected volatile StoreFactoryCacheManager storeCache;
+
+// @Override
+// public CachedStoreFactoryProvider create(KeycloakSession session) {
+// lazyInit(session);
+// return new StoreFactoryCacheSession(storeCache, session);
+// }
+
+// private void lazyInit(KeycloakSession session) {
+// if (storeCache == null) {
+// synchronized (this) {
+// if (storeCache == null) {
+// Cache<String, Revisioned> cache = session.getProvider(InfinispanConnectionProvider.class).getCache(InfinispanConnectionProvider.AUTHORIZATION_CACHE_NAME);
+// Cache<String, Long> revisions = session.getProvider(InfinispanConnectionProvider.class).getCache(InfinispanConnectionProvider.AUTHORIZATION_REVISIONS_CACHE_NAME);
+// storeCache = new StoreFactoryCacheManager(cache, revisions);
+// ClusterProvider cluster = session.getProvider(ClusterProvider.class);
+
+// cluster.registerListener(AUTHORIZATION_INVALIDATION_EVENTS, (ClusterEvent event) -> {
+
+// InvalidationEvent invalidationEvent = (InvalidationEvent) event;
+// storeCache.invalidationEventReceived(invalidationEvent);
+
+// });
+
+// cluster.registerListener(AUTHORIZATION_CLEAR_CACHE_EVENTS, (ClusterEvent event) -> storeCache.clear());
+// cluster.registerListener(REALM_CLEAR_CACHE_EVENTS, (ClusterEvent event) -> storeCache.clear());
+
+// log.debug("Registered cluster listeners");
+// }
+// }
+// }
+// }
+
+// @Override
+// public void init(Config.Scope config) {
+// }
+
+// @Override
+// public void postInit(KeycloakSessionFactory factory) {
+
+// }
+
+// @Override
+// public void close() {
+// }
+
+// @Override
+// public String getId() {
+// return "default";
+// }
+
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/PermissionTicketAdapter.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/PermissionTicketAdapter.java
index 3ef19cf..769b43c 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/PermissionTicketAdapter.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/PermissionTicketAdapter.java
@@ -1,153 +1,153 @@
-/*
- * Copyright 2017 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.keycloak.models.cache.infinispan.authorization;
-
-import org.keycloak.authorization.model.CachedModel;
-import org.keycloak.authorization.model.PermissionTicket;
-import org.keycloak.authorization.model.Policy;
-import org.keycloak.authorization.model.Resource;
-import org.keycloak.authorization.model.ResourceServer;
-import org.keycloak.authorization.model.Scope;
-import org.keycloak.models.cache.infinispan.authorization.entities.CachedPermissionTicket;
-
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class PermissionTicketAdapter implements PermissionTicket, CachedModel<PermissionTicket> {
-
- protected CachedPermissionTicket cached;
- protected StoreFactoryCacheSession cacheSession;
- protected PermissionTicket updated;
-
- public PermissionTicketAdapter(CachedPermissionTicket cached, StoreFactoryCacheSession cacheSession) {
- this.cached = cached;
- this.cacheSession = cacheSession;
- }
-
- @Override
- public PermissionTicket getDelegateForUpdate() {
- if (updated == null) {
- cacheSession.registerPermissionTicketInvalidation(cached.getId(), cached.getOwner(), cached.getRequester(), cached.getResourceId(), cached.getScopeId(), cached.getResourceServerId());
- updated = cacheSession.getPermissionTicketStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
- if (updated == null) throw new IllegalStateException("Not found in database");
- }
- return updated;
- }
-
- protected boolean invalidated;
-
- protected void invalidateFlag() {
- invalidated = true;
- }
-
- @Override
- public void invalidate() {
- invalidated = true;
- getDelegateForUpdate();
- }
-
- @Override
- public long getCacheTimestamp() {
- return cached.getCacheTimestamp();
- }
-
- protected boolean isUpdated() {
- if (updated != null) return true;
- if (!invalidated) return false;
- updated = cacheSession.getPermissionTicketStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
- if (updated == null) throw new IllegalStateException("Not found in database");
- return true;
- }
-
-
- @Override
- public String getId() {
- if (isUpdated()) return updated.getId();
- return cached.getId();
- }
-
- @Override
- public String getOwner() {
- if (isUpdated()) return updated.getOwner();
- return cached.getOwner();
- }
-
- @Override
- public String getRequester() {
- if (isUpdated()) return updated.getRequester();
- return cached.getRequester();
- }
-
- @Override
- public boolean isGranted() {
- if (isUpdated()) return updated.isGranted();
- return cached.isGranted();
- }
-
- @Override
- public Long getCreatedTimestamp() {
- if (isUpdated()) return updated.getCreatedTimestamp();
- return cached.getCreatedTimestamp();
- }
-
- @Override
- public Long getGrantedTimestamp() {
- if (isUpdated()) return updated.getGrantedTimestamp();
- return cached.getGrantedTimestamp();
- }
-
- @Override
- public void setGrantedTimestamp(Long millis) {
- getDelegateForUpdate();
- cacheSession.registerPermissionTicketInvalidation(cached.getId(), cached.getOwner(), cached.getRequester(), cached.getResourceId(), cached.getScopeId(), cached.getResourceServerId());
- updated.setGrantedTimestamp(millis);
- }
-
- @Override
- public ResourceServer getResourceServer() {
- return cacheSession.getResourceServerStore().findById(cached.getResourceServerId());
- }
-
- @Override
- public Policy getPolicy() {
- if (isUpdated()) return updated.getPolicy();
- return cacheSession.getPolicyStore().findById(cached.getPolicy(), cached.getResourceServerId());
- }
-
- @Override
- public void setPolicy(Policy policy) {
- getDelegateForUpdate();
- cacheSession.registerPermissionTicketInvalidation(cached.getId(), cached.getOwner(), cached.getRequester(), cached.getResourceId(), cached.getScopeId(), cached.getResourceServerId());
- updated.setPolicy(policy);
- }
-
- @Override
- public Resource getResource() {
- return cacheSession.getResourceStore().findById(cached.getResourceId(), getResourceServer().getId());
- }
-
- @Override
- public Scope getScope() {
- return cacheSession.getScopeStore().findById(cached.getScopeId(), getResourceServer().getId());
- }
-
- @Override
- public int hashCode() {
- return getId().hashCode();
- }
-}
+// /*
+// * Copyright 2017 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+// package org.keycloak.models.cache.infinispan.authorization;
+
+// import org.keycloak.authorization.model.CachedModel;
+// import org.keycloak.authorization.model.PermissionTicket;
+// import org.keycloak.authorization.model.Policy;
+// import org.keycloak.authorization.model.Resource;
+// import org.keycloak.authorization.model.ResourceServer;
+// import org.keycloak.authorization.model.Scope;
+// import org.keycloak.models.cache.infinispan.authorization.entities.CachedPermissionTicket;
+
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public class PermissionTicketAdapter implements PermissionTicket, CachedModel<PermissionTicket> {
+
+// protected CachedPermissionTicket cached;
+// protected StoreFactoryCacheSession cacheSession;
+// protected PermissionTicket updated;
+
+// public PermissionTicketAdapter(CachedPermissionTicket cached, StoreFactoryCacheSession cacheSession) {
+// this.cached = cached;
+// this.cacheSession = cacheSession;
+// }
+
+// @Override
+// public PermissionTicket getDelegateForUpdate() {
+// if (updated == null) {
+// cacheSession.registerPermissionTicketInvalidation(cached.getId(), cached.getOwner(), cached.getRequester(), cached.getResourceId(), cached.getScopeId(), cached.getResourceServerId());
+// updated = cacheSession.getPermissionTicketStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
+// if (updated == null) throw new IllegalStateException("Not found in database");
+// }
+// return updated;
+// }
+
+// protected boolean invalidated;
+
+// protected void invalidateFlag() {
+// invalidated = true;
+// }
+
+// @Override
+// public void invalidate() {
+// invalidated = true;
+// getDelegateForUpdate();
+// }
+
+// @Override
+// public long getCacheTimestamp() {
+// return cached.getCacheTimestamp();
+// }
+
+// protected boolean isUpdated() {
+// if (updated != null) return true;
+// if (!invalidated) return false;
+// updated = cacheSession.getPermissionTicketStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
+// if (updated == null) throw new IllegalStateException("Not found in database");
+// return true;
+// }
+
+
+// @Override
+// public String getId() {
+// if (isUpdated()) return updated.getId();
+// return cached.getId();
+// }
+
+// @Override
+// public String getOwner() {
+// if (isUpdated()) return updated.getOwner();
+// return cached.getOwner();
+// }
+
+// @Override
+// public String getRequester() {
+// if (isUpdated()) return updated.getRequester();
+// return cached.getRequester();
+// }
+
+// @Override
+// public boolean isGranted() {
+// if (isUpdated()) return updated.isGranted();
+// return cached.isGranted();
+// }
+
+// @Override
+// public Long getCreatedTimestamp() {
+// if (isUpdated()) return updated.getCreatedTimestamp();
+// return cached.getCreatedTimestamp();
+// }
+
+// @Override
+// public Long getGrantedTimestamp() {
+// if (isUpdated()) return updated.getGrantedTimestamp();
+// return cached.getGrantedTimestamp();
+// }
+
+// @Override
+// public void setGrantedTimestamp(Long millis) {
+// getDelegateForUpdate();
+// cacheSession.registerPermissionTicketInvalidation(cached.getId(), cached.getOwner(), cached.getRequester(), cached.getResourceId(), cached.getScopeId(), cached.getResourceServerId());
+// updated.setGrantedTimestamp(millis);
+// }
+
+// @Override
+// public ResourceServer getResourceServer() {
+// return cacheSession.getResourceServerStore().findById(cached.getResourceServerId());
+// }
+
+// @Override
+// public Policy getPolicy() {
+// if (isUpdated()) return updated.getPolicy();
+// return cacheSession.getPolicyStore().findById(cached.getPolicy(), cached.getResourceServerId());
+// }
+
+// @Override
+// public void setPolicy(Policy policy) {
+// getDelegateForUpdate();
+// cacheSession.registerPermissionTicketInvalidation(cached.getId(), cached.getOwner(), cached.getRequester(), cached.getResourceId(), cached.getScopeId(), cached.getResourceServerId());
+// updated.setPolicy(policy);
+// }
+
+// @Override
+// public Resource getResource() {
+// return cacheSession.getResourceStore().findById(cached.getResourceId(), getResourceServer().getId());
+// }
+
+// @Override
+// public Scope getScope() {
+// return cacheSession.getScopeStore().findById(cached.getScopeId(), getResourceServer().getId());
+// }
+
+// @Override
+// public int hashCode() {
+// return getId().hashCode();
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/PolicyAdapter.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/PolicyAdapter.java
index 34785cc..2bff8a6 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/PolicyAdapter.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/PolicyAdapter.java
@@ -1,335 +1,335 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.keycloak.models.cache.infinispan.authorization;
-
-import org.keycloak.authorization.model.CachedModel;
-import org.keycloak.authorization.model.Policy;
-import org.keycloak.authorization.model.Resource;
-import org.keycloak.authorization.model.ResourceServer;
-import org.keycloak.authorization.model.Scope;
-import org.keycloak.authorization.store.PolicyStore;
-import org.keycloak.authorization.store.ResourceStore;
-import org.keycloak.authorization.store.ScopeStore;
-import org.keycloak.models.cache.infinispan.authorization.entities.CachedPolicy;
-import org.keycloak.representations.idm.authorization.DecisionStrategy;
-import org.keycloak.representations.idm.authorization.Logic;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class PolicyAdapter implements Policy, CachedModel<Policy> {
-
- private final Supplier<Policy> modelSupplier;
- protected final CachedPolicy cached;
- protected final StoreFactoryCacheSession cacheSession;
- protected Policy updated;
-
- public PolicyAdapter(CachedPolicy cached, StoreFactoryCacheSession cacheSession) {
- this.cached = cached;
- this.cacheSession = cacheSession;
- this.modelSupplier = this::getPolicyModel;
- }
-
- @Override
- public Policy getDelegateForUpdate() {
- if (updated == null) {
- updated = modelSupplier.get();
- String defaultResourceType = updated.getConfig().get("defaultResourceType");
- cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), cached.getResourcesIds(modelSupplier), cached.getScopesIds(modelSupplier), defaultResourceType, cached.getResourceServerId());
- if (updated == null) throw new IllegalStateException("Not found in database");
- }
- return updated;
- }
-
- protected boolean invalidated;
-
- protected void invalidateFlag() {
- invalidated = true;
-
- }
-
- @Override
- public void invalidate() {
- invalidated = true;
- getDelegateForUpdate();
- }
-
- @Override
- public long getCacheTimestamp() {
- return cached.getCacheTimestamp();
- }
-
- protected boolean isUpdated() {
- if (updated != null) return true;
- if (!invalidated) return false;
- updated = cacheSession.getPolicyStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
- if (updated == null) throw new IllegalStateException("Not found in database");
- return true;
- }
-
-
- @Override
- public String getId() {
- if (isUpdated()) return updated.getId();
- return cached.getId();
- }
-
- @Override
- public String getName() {
- if (isUpdated()) return updated.getName();
- return cached.getName();
- }
-
- @Override
- public void setName(String name) {
- getDelegateForUpdate();
- cacheSession.registerPolicyInvalidation(cached.getId(), name, cached.getResourcesIds(modelSupplier), cached.getScopesIds(modelSupplier), cached.getConfig(modelSupplier).get("defaultResourceType"), cached.getResourceServerId());
- updated.setName(name);
- }
-
- @Override
- public ResourceServer getResourceServer() {
- return cacheSession.getResourceServerStore().findById(cached.getResourceServerId());
- }
-
- @Override
- public String getType() {
- if (isUpdated()) return updated.getType();
- return cached.getType();
- }
-
- @Override
- public DecisionStrategy getDecisionStrategy() {
- if (isUpdated()) return updated.getDecisionStrategy();
- return cached.getDecisionStrategy();
- }
-
- @Override
- public void setDecisionStrategy(DecisionStrategy decisionStrategy) {
- getDelegateForUpdate();
- updated.setDecisionStrategy(decisionStrategy);
-
- }
-
- @Override
- public Logic getLogic() {
- if (isUpdated()) return updated.getLogic();
- return cached.getLogic();
- }
-
- @Override
- public void setLogic(Logic logic) {
- getDelegateForUpdate();
- updated.setLogic(logic);
-
- }
-
- @Override
- public Map<String, String> getConfig() {
- if (isUpdated()) return updated.getConfig();
- return cached.getConfig(modelSupplier);
- }
-
- @Override
- public void setConfig(Map<String, String> config) {
- getDelegateForUpdate();
- if (config.containsKey("defaultResourceType") || cached.getConfig(modelSupplier).containsKey("defaultResourceType")) {
- cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), cached.getResourcesIds(modelSupplier), cached.getScopesIds(modelSupplier), cached.getConfig(modelSupplier).get("defaultResourceType"), cached.getResourceServerId());
- cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), cached.getResourcesIds(modelSupplier), cached.getScopesIds(modelSupplier), config.get("defaultResourceType"), cached.getResourceServerId());
- }
- updated.setConfig(config);
-
- }
-
- @Override
- public void removeConfig(String name) {
- getDelegateForUpdate();
- if (name.equals("defaultResourceType")) {
- cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), cached.getResourcesIds(modelSupplier), cached.getScopesIds(modelSupplier), cached.getConfig(modelSupplier).get("defaultResourceType"), cached.getResourceServerId());
- }
- updated.removeConfig(name);
-
- }
-
- @Override
- public void putConfig(String name, String value) {
- getDelegateForUpdate();
- if (name.equals("defaultResourceType")) {
- cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), cached.getResourcesIds(modelSupplier), cached.getScopesIds(modelSupplier), cached.getConfig(modelSupplier).get("defaultResourceType"), cached.getResourceServerId());
- cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), cached.getResourcesIds(modelSupplier), cached.getScopesIds(modelSupplier), value, cached.getResourceServerId());
- }
- updated.putConfig(name, value);
- }
-
- @Override
- public String getDescription() {
- if (isUpdated()) return updated.getDescription();
- return cached.getDescription();
- }
-
- @Override
- public void setDescription(String description) {
- getDelegateForUpdate();
- updated.setDescription(description);
- }
-
- protected Set<Policy> associatedPolicies;
-
- @Override
- public Set<Policy> getAssociatedPolicies() {
- if (isUpdated()) {
- return updated.getAssociatedPolicies().stream().map(policy -> new PolicyAdapter(cacheSession.createCachedPolicy(policy, policy.getId()), cacheSession)).collect(Collectors.toSet());
- }
- if (associatedPolicies != null) return associatedPolicies;
- associatedPolicies = new HashSet<>();
- PolicyStore policyStore = cacheSession.getPolicyStore();
- String resourceServerId = cached.getResourceServerId();
- for (String id : cached.getAssociatedPoliciesIds(modelSupplier)) {
- Policy policy = policyStore.findById(id, resourceServerId);
- cacheSession.cachePolicy(policy);
- associatedPolicies.add(policy);
- }
- return associatedPolicies = Collections.unmodifiableSet(associatedPolicies);
- }
-
- protected Set<Resource> resources;
-
- @Override
- public Set<Resource> getResources() {
- if (isUpdated()) return updated.getResources();
- if (resources != null) return resources;
- resources = new HashSet<>();
- ResourceStore resourceStore = cacheSession.getResourceStore();
- for (String resourceId : cached.getResourcesIds(modelSupplier)) {
- String resourceServerId = cached.getResourceServerId();
- Resource resource = resourceStore.findById(resourceId, resourceServerId);
- cacheSession.cacheResource(resource);
- resources.add(resource);
- }
- return resources = Collections.unmodifiableSet(resources);
- }
-
- @Override
- public void addScope(Scope scope) {
- getDelegateForUpdate();
- cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), cached.getResourcesIds(modelSupplier), new HashSet<>(Arrays.asList(scope.getId())), cached.getConfig(modelSupplier).get("defaultResourceType"), cached.getResourceServerId());
- updated.addScope(scope);
- }
-
- @Override
- public void removeScope(Scope scope) {
- getDelegateForUpdate();
- cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), cached.getResourcesIds(modelSupplier), new HashSet<>(Arrays.asList(scope.getId())), cached.getConfig(modelSupplier).get("defaultResourceType"), cached.getResourceServerId());
- updated.removeScope(scope);
- }
-
- @Override
- public void addAssociatedPolicy(Policy associatedPolicy) {
- getDelegateForUpdate();
- updated.addAssociatedPolicy(associatedPolicy);
-
- }
-
- @Override
- public void removeAssociatedPolicy(Policy associatedPolicy) {
- getDelegateForUpdate();
- updated.removeAssociatedPolicy(associatedPolicy);
-
- }
-
- @Override
- public void addResource(Resource resource) {
- getDelegateForUpdate();
- HashSet<String> resources = new HashSet<>();
- resources.add(resource.getId());
- cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), resources, cached.getScopesIds(modelSupplier), cached.getConfig(modelSupplier).get("defaultResourceType"), cached.getResourceServerId());
- updated.addResource(resource);
-
- }
-
- @Override
- public void removeResource(Resource resource) {
- getDelegateForUpdate();
- HashSet<String> resources = new HashSet<>();
- resources.add(resource.getId());
- cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), resources, cached.getScopesIds(modelSupplier), cached.getConfig(modelSupplier).get("defaultResourceType"), cached.getResourceServerId());
- updated.removeResource(resource);
-
- }
-
- @Override
- public boolean isFetched(String association) {
- return modelSupplier.get().isFetched(association);
- }
-
- protected Set<Scope> scopes;
-
- @Override
- public Set<Scope> getScopes() {
- if (isUpdated()) return updated.getScopes();
- if (scopes != null) return scopes;
- scopes = new HashSet<>();
- ScopeStore scopeStore = cacheSession.getScopeStore();
- String resourceServerId = cached.getResourceServerId();
- for (String scopeId : cached.getScopesIds(modelSupplier)) {
- Scope scope = scopeStore.findById(scopeId, resourceServerId);
- cacheSession.cacheScope(scope);
- scopes.add(scope);
- }
- return scopes = Collections.unmodifiableSet(scopes);
- }
-
- @Override
- public String getOwner() {
- if (isUpdated()) return updated.getOwner();
- return cached.getOwner();
- }
-
- @Override
- public void setOwner(String owner) {
- getDelegateForUpdate();
- cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), cached.getResourcesIds(modelSupplier), cached.getScopesIds(modelSupplier), cached.getConfig(modelSupplier).get("defaultResourceType"), cached.getResourceServerId());
- updated.setOwner(owner);
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || !(o instanceof Policy)) return false;
-
- Policy that = (Policy) o;
- return that.getId().equals(getId());
- }
-
- @Override
- public int hashCode() {
- return getId().hashCode();
- }
-
- private Policy getPolicyModel() {
- return cacheSession.getPolicyStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+// package org.keycloak.models.cache.infinispan.authorization;
+
+// import org.keycloak.authorization.model.CachedModel;
+// import org.keycloak.authorization.model.Policy;
+// import org.keycloak.authorization.model.Resource;
+// import org.keycloak.authorization.model.ResourceServer;
+// import org.keycloak.authorization.model.Scope;
+// import org.keycloak.authorization.store.PolicyStore;
+// import org.keycloak.authorization.store.ResourceStore;
+// import org.keycloak.authorization.store.ScopeStore;
+// import org.keycloak.models.cache.infinispan.authorization.entities.CachedPolicy;
+// import org.keycloak.representations.idm.authorization.DecisionStrategy;
+// import org.keycloak.representations.idm.authorization.Logic;
+
+// import java.util.Arrays;
+// import java.util.Collections;
+// import java.util.HashSet;
+// import java.util.Map;
+// import java.util.Set;
+// import java.util.function.Supplier;
+// import java.util.stream.Collectors;
+
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public class PolicyAdapter implements Policy, CachedModel<Policy> {
+
+// private final Supplier<Policy> modelSupplier;
+// protected final CachedPolicy cached;
+// protected final StoreFactoryCacheSession cacheSession;
+// protected Policy updated;
+
+// public PolicyAdapter(CachedPolicy cached, StoreFactoryCacheSession cacheSession) {
+// this.cached = cached;
+// this.cacheSession = cacheSession;
+// this.modelSupplier = this::getPolicyModel;
+// }
+
+// @Override
+// public Policy getDelegateForUpdate() {
+// if (updated == null) {
+// updated = modelSupplier.get();
+// String defaultResourceType = updated.getConfig().get("defaultResourceType");
+// cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), cached.getResourcesIds(modelSupplier), cached.getScopesIds(modelSupplier), defaultResourceType, cached.getResourceServerId());
+// if (updated == null) throw new IllegalStateException("Not found in database");
+// }
+// return updated;
+// }
+
+// protected boolean invalidated;
+
+// protected void invalidateFlag() {
+// invalidated = true;
+
+// }
+
+// @Override
+// public void invalidate() {
+// invalidated = true;
+// getDelegateForUpdate();
+// }
+
+// @Override
+// public long getCacheTimestamp() {
+// return cached.getCacheTimestamp();
+// }
+
+// protected boolean isUpdated() {
+// if (updated != null) return true;
+// if (!invalidated) return false;
+// updated = cacheSession.getPolicyStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
+// if (updated == null) throw new IllegalStateException("Not found in database");
+// return true;
+// }
+
+
+// @Override
+// public String getId() {
+// if (isUpdated()) return updated.getId();
+// return cached.getId();
+// }
+
+// @Override
+// public String getName() {
+// if (isUpdated()) return updated.getName();
+// return cached.getName();
+// }
+
+// @Override
+// public void setName(String name) {
+// getDelegateForUpdate();
+// cacheSession.registerPolicyInvalidation(cached.getId(), name, cached.getResourcesIds(modelSupplier), cached.getScopesIds(modelSupplier), cached.getConfig(modelSupplier).get("defaultResourceType"), cached.getResourceServerId());
+// updated.setName(name);
+// }
+
+// @Override
+// public ResourceServer getResourceServer() {
+// return cacheSession.getResourceServerStore().findById(cached.getResourceServerId());
+// }
+
+// @Override
+// public String getType() {
+// if (isUpdated()) return updated.getType();
+// return cached.getType();
+// }
+
+// @Override
+// public DecisionStrategy getDecisionStrategy() {
+// if (isUpdated()) return updated.getDecisionStrategy();
+// return cached.getDecisionStrategy();
+// }
+
+// @Override
+// public void setDecisionStrategy(DecisionStrategy decisionStrategy) {
+// getDelegateForUpdate();
+// updated.setDecisionStrategy(decisionStrategy);
+
+// }
+
+// @Override
+// public Logic getLogic() {
+// if (isUpdated()) return updated.getLogic();
+// return cached.getLogic();
+// }
+
+// @Override
+// public void setLogic(Logic logic) {
+// getDelegateForUpdate();
+// updated.setLogic(logic);
+
+// }
+
+// @Override
+// public Map<String, String> getConfig() {
+// if (isUpdated()) return updated.getConfig();
+// return cached.getConfig(modelSupplier);
+// }
+
+// @Override
+// public void setConfig(Map<String, String> config) {
+// getDelegateForUpdate();
+// if (config.containsKey("defaultResourceType") || cached.getConfig(modelSupplier).containsKey("defaultResourceType")) {
+// cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), cached.getResourcesIds(modelSupplier), cached.getScopesIds(modelSupplier), cached.getConfig(modelSupplier).get("defaultResourceType"), cached.getResourceServerId());
+// cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), cached.getResourcesIds(modelSupplier), cached.getScopesIds(modelSupplier), config.get("defaultResourceType"), cached.getResourceServerId());
+// }
+// updated.setConfig(config);
+
+// }
+
+// @Override
+// public void removeConfig(String name) {
+// getDelegateForUpdate();
+// if (name.equals("defaultResourceType")) {
+// cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), cached.getResourcesIds(modelSupplier), cached.getScopesIds(modelSupplier), cached.getConfig(modelSupplier).get("defaultResourceType"), cached.getResourceServerId());
+// }
+// updated.removeConfig(name);
+
+// }
+
+// @Override
+// public void putConfig(String name, String value) {
+// getDelegateForUpdate();
+// if (name.equals("defaultResourceType")) {
+// cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), cached.getResourcesIds(modelSupplier), cached.getScopesIds(modelSupplier), cached.getConfig(modelSupplier).get("defaultResourceType"), cached.getResourceServerId());
+// cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), cached.getResourcesIds(modelSupplier), cached.getScopesIds(modelSupplier), value, cached.getResourceServerId());
+// }
+// updated.putConfig(name, value);
+// }
+
+// @Override
+// public String getDescription() {
+// if (isUpdated()) return updated.getDescription();
+// return cached.getDescription();
+// }
+
+// @Override
+// public void setDescription(String description) {
+// getDelegateForUpdate();
+// updated.setDescription(description);
+// }
+
+// protected Set<Policy> associatedPolicies;
+
+// @Override
+// public Set<Policy> getAssociatedPolicies() {
+// if (isUpdated()) {
+// return updated.getAssociatedPolicies().stream().map(policy -> new PolicyAdapter(cacheSession.createCachedPolicy(policy, policy.getId()), cacheSession)).collect(Collectors.toSet());
+// }
+// if (associatedPolicies != null) return associatedPolicies;
+// associatedPolicies = new HashSet<>();
+// PolicyStore policyStore = cacheSession.getPolicyStore();
+// String resourceServerId = cached.getResourceServerId();
+// for (String id : cached.getAssociatedPoliciesIds(modelSupplier)) {
+// Policy policy = policyStore.findById(id, resourceServerId);
+// cacheSession.cachePolicy(policy);
+// associatedPolicies.add(policy);
+// }
+// return associatedPolicies = Collections.unmodifiableSet(associatedPolicies);
+// }
+
+// protected Set<Resource> resources;
+
+// @Override
+// public Set<Resource> getResources() {
+// if (isUpdated()) return updated.getResources();
+// if (resources != null) return resources;
+// resources = new HashSet<>();
+// ResourceStore resourceStore = cacheSession.getResourceStore();
+// for (String resourceId : cached.getResourcesIds(modelSupplier)) {
+// String resourceServerId = cached.getResourceServerId();
+// Resource resource = resourceStore.findById(resourceId, resourceServerId);
+// cacheSession.cacheResource(resource);
+// resources.add(resource);
+// }
+// return resources = Collections.unmodifiableSet(resources);
+// }
+
+// @Override
+// public void addScope(Scope scope) {
+// getDelegateForUpdate();
+// cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), cached.getResourcesIds(modelSupplier), new HashSet<>(Arrays.asList(scope.getId())), cached.getConfig(modelSupplier).get("defaultResourceType"), cached.getResourceServerId());
+// updated.addScope(scope);
+// }
+
+// @Override
+// public void removeScope(Scope scope) {
+// getDelegateForUpdate();
+// cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), cached.getResourcesIds(modelSupplier), new HashSet<>(Arrays.asList(scope.getId())), cached.getConfig(modelSupplier).get("defaultResourceType"), cached.getResourceServerId());
+// updated.removeScope(scope);
+// }
+
+// @Override
+// public void addAssociatedPolicy(Policy associatedPolicy) {
+// getDelegateForUpdate();
+// updated.addAssociatedPolicy(associatedPolicy);
+
+// }
+
+// @Override
+// public void removeAssociatedPolicy(Policy associatedPolicy) {
+// getDelegateForUpdate();
+// updated.removeAssociatedPolicy(associatedPolicy);
+
+// }
+
+// @Override
+// public void addResource(Resource resource) {
+// getDelegateForUpdate();
+// HashSet<String> resources = new HashSet<>();
+// resources.add(resource.getId());
+// cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), resources, cached.getScopesIds(modelSupplier), cached.getConfig(modelSupplier).get("defaultResourceType"), cached.getResourceServerId());
+// updated.addResource(resource);
+
+// }
+
+// @Override
+// public void removeResource(Resource resource) {
+// getDelegateForUpdate();
+// HashSet<String> resources = new HashSet<>();
+// resources.add(resource.getId());
+// cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), resources, cached.getScopesIds(modelSupplier), cached.getConfig(modelSupplier).get("defaultResourceType"), cached.getResourceServerId());
+// updated.removeResource(resource);
+
+// }
+
+// @Override
+// public boolean isFetched(String association) {
+// return modelSupplier.get().isFetched(association);
+// }
+
+// protected Set<Scope> scopes;
+
+// @Override
+// public Set<Scope> getScopes() {
+// if (isUpdated()) return updated.getScopes();
+// if (scopes != null) return scopes;
+// scopes = new HashSet<>();
+// ScopeStore scopeStore = cacheSession.getScopeStore();
+// String resourceServerId = cached.getResourceServerId();
+// for (String scopeId : cached.getScopesIds(modelSupplier)) {
+// Scope scope = scopeStore.findById(scopeId, resourceServerId);
+// cacheSession.cacheScope(scope);
+// scopes.add(scope);
+// }
+// return scopes = Collections.unmodifiableSet(scopes);
+// }
+
+// @Override
+// public String getOwner() {
+// if (isUpdated()) return updated.getOwner();
+// return cached.getOwner();
+// }
+
+// @Override
+// public void setOwner(String owner) {
+// getDelegateForUpdate();
+// cacheSession.registerPolicyInvalidation(cached.getId(), cached.getName(), cached.getResourcesIds(modelSupplier), cached.getScopesIds(modelSupplier), cached.getConfig(modelSupplier).get("defaultResourceType"), cached.getResourceServerId());
+// updated.setOwner(owner);
+// }
+
+// @Override
+// public boolean equals(Object o) {
+// if (this == o) return true;
+// if (o == null || !(o instanceof Policy)) return false;
+
+// Policy that = (Policy) o;
+// return that.getId().equals(getId());
+// }
+
+// @Override
+// public int hashCode() {
+// return getId().hashCode();
+// }
+
+// private Policy getPolicyModel() {
+// return cacheSession.getPolicyStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/ResourceAdapter.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/ResourceAdapter.java
index a22fa19..dd02e28 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/ResourceAdapter.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/ResourceAdapter.java
@@ -1,292 +1,292 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.keycloak.models.cache.infinispan.authorization;
-
-import org.keycloak.authorization.model.CachedModel;
-import org.keycloak.authorization.model.PermissionTicket;
-import org.keycloak.authorization.model.Resource;
-import org.keycloak.authorization.model.ResourceServer;
-import org.keycloak.authorization.model.Scope;
-import org.keycloak.authorization.store.PermissionTicketStore;
-import org.keycloak.authorization.store.PolicyStore;
-import org.keycloak.models.cache.infinispan.authorization.entities.CachedResource;
-
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class ResourceAdapter implements Resource, CachedModel<Resource> {
-
- private final Supplier<Resource> modelSupplier;
- protected final CachedResource cached;
- protected final StoreFactoryCacheSession cacheSession;
- protected Resource updated;
-
- public ResourceAdapter(CachedResource cached, StoreFactoryCacheSession cacheSession) {
- this.cached = cached;
- this.cacheSession = cacheSession;
- this.modelSupplier = this::getResourceModel;
- }
-
- @Override
- public Resource getDelegateForUpdate() {
- if (updated == null) {
- updated = modelSupplier.get();
- cacheSession.registerResourceInvalidation(cached.getId(), cached.getName(), cached.getType(), cached.getUris(modelSupplier), cached.getScopesIds(modelSupplier), cached.getResourceServerId(), cached.getOwner());
- if (updated == null) throw new IllegalStateException("Not found in database");
- }
- return updated;
- }
-
- protected boolean invalidated;
-
- protected void invalidateFlag() {
- invalidated = true;
-
- }
-
- @Override
- public void invalidate() {
- invalidated = true;
- getDelegateForUpdate();
- }
-
- @Override
- public long getCacheTimestamp() {
- return cached.getCacheTimestamp();
- }
-
- protected boolean isUpdated() {
- if (updated != null) return true;
- if (!invalidated) return false;
- updated = cacheSession.getResourceStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
- if (updated == null) throw new IllegalStateException("Not found in database");
- return true;
- }
-
-
- @Override
- public String getId() {
- if (isUpdated()) return updated.getId();
- return cached.getId();
- }
-
- @Override
- public String getName() {
- if (isUpdated()) return updated.getName();
- return cached.getName();
- }
-
- @Override
- public void setName(String name) {
- getDelegateForUpdate();
- cacheSession.registerResourceInvalidation(cached.getId(), name, cached.getType(), cached.getUris(modelSupplier), cached.getScopesIds(modelSupplier), cached.getResourceServerId(), cached.getOwner());
- updated.setName(name);
- }
-
- @Override
- public String getDisplayName() {
- if (isUpdated()) return updated.getDisplayName();
- return cached.getDisplayName();
- }
-
- @Override
- public void setDisplayName(String name) {
- getDelegateForUpdate();
- cacheSession.registerResourceInvalidation(cached.getId(), name, cached.getType(), cached.getUris(modelSupplier), cached.getScopesIds(modelSupplier), cached.getResourceServerId(), cached.getOwner());
- updated.setDisplayName(name);
- }
-
- @Override
- public String getIconUri() {
- if (isUpdated()) return updated.getIconUri();
- return cached.getIconUri();
- }
-
- @Override
- public void setIconUri(String iconUri) {
- getDelegateForUpdate();
- updated.setIconUri(iconUri);
-
- }
-
- @Override
- public ResourceServer getResourceServer() {
- return cacheSession.getResourceServerStore().findById(cached.getResourceServerId());
- }
-
- @Override
- public Set<String> getUris() {
- if (isUpdated()) return updated.getUris();
- return cached.getUris(modelSupplier);
- }
-
- @Override
- public void updateUris(Set<String> uris) {
- getDelegateForUpdate();
- cacheSession.registerResourceInvalidation(cached.getId(), cached.getName(), cached.getType(), uris, cached.getScopesIds(modelSupplier), cached.getResourceServerId(), cached.getOwner());
- updated.updateUris(uris);
- }
-
- @Override
- public String getType() {
- if (isUpdated()) return updated.getType();
- return cached.getType();
- }
-
- @Override
- public void setType(String type) {
- getDelegateForUpdate();
- cacheSession.registerResourceInvalidation(cached.getId(), cached.getName(), type, cached.getUris(modelSupplier), cached.getScopesIds(modelSupplier), cached.getResourceServerId(), cached.getOwner());
- updated.setType(type);
-
- }
-
- protected List<Scope> scopes;
-
- @Override
- public List<Scope> getScopes() {
- if (isUpdated()) return updated.getScopes();
- if (scopes != null) return scopes;
- scopes = new LinkedList<>();
- for (String scopeId : cached.getScopesIds(modelSupplier)) {
- scopes.add(cacheSession.getScopeStore().findById(scopeId, cached.getResourceServerId()));
- }
- return scopes = Collections.unmodifiableList(scopes);
- }
-
- @Override
- public String getOwner() {
- if (isUpdated()) return updated.getOwner();
- return cached.getOwner();
- }
-
- @Override
- public boolean isOwnerManagedAccess() {
- if (isUpdated()) return updated.isOwnerManagedAccess();
- return cached.isOwnerManagedAccess();
- }
-
- @Override
- public void setOwnerManagedAccess(boolean ownerManagedAccess) {
- getDelegateForUpdate();
- cacheSession.registerResourceInvalidation(cached.getId(), cached.getName(), cached.getType(), cached.getUris(modelSupplier), cached.getScopesIds(modelSupplier), cached.getResourceServerId(), cached.getOwner());
- updated.setOwnerManagedAccess(ownerManagedAccess);
- }
-
- @Override
- public void updateScopes(Set<Scope> scopes) {
- Resource updated = getDelegateForUpdate();
-
- for (Scope scope : updated.getScopes()) {
- if (!scopes.contains(scope)) {
- PermissionTicketStore permissionStore = cacheSession.getPermissionTicketStore();
- List<PermissionTicket> permissions = permissionStore.findByScope(scope.getId(), getResourceServer().getId());
-
- for (PermissionTicket permission : permissions) {
- permissionStore.delete(permission.getId());
- }
- }
- }
-
- PolicyStore policyStore = cacheSession.getPolicyStore();
-
- for (Scope scope : updated.getScopes()) {
- if (!scopes.contains(scope)) {
- policyStore.findByResource(getId(), getResourceServer().getId(), policy -> policy.removeScope(scope));
- }
- }
-
- cacheSession.registerResourceInvalidation(cached.getId(), cached.getName(), cached.getType(), cached.getUris(modelSupplier), scopes.stream().map(scope1 -> scope1.getId()).collect(Collectors.toSet()), cached.getResourceServerId(), cached.getOwner());
- updated.updateScopes(scopes);
- }
-
- @Override
- public Map<String, List<String>> getAttributes() {
- if (updated != null) return updated.getAttributes();
- return cached.getAttributes(modelSupplier);
- }
-
- @Override
- public String getSingleAttribute(String name) {
- if (updated != null) return updated.getSingleAttribute(name);
-
- List<String> values = cached.getAttributes(modelSupplier).getOrDefault(name, Collections.emptyList());
-
- if (values.isEmpty()) {
- return null;
- }
-
- return values.get(0);
- }
-
- @Override
- public List<String> getAttribute(String name) {
- if (updated != null) return updated.getAttribute(name);
-
- List<String> values = cached.getAttributes(modelSupplier).getOrDefault(name, Collections.emptyList());
-
- if (values.isEmpty()) {
- return null;
- }
-
- return Collections.unmodifiableList(values);
- }
-
- @Override
- public void setAttribute(String name, List<String> values) {
- getDelegateForUpdate();
- updated.setAttribute(name, values);
- }
-
- @Override
- public void removeAttribute(String name) {
- getDelegateForUpdate();
- updated.removeAttribute(name);
- }
-
- @Override
- public boolean isFetched(String association) {
- return modelSupplier.get().isFetched(association);
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || !(o instanceof Resource)) return false;
-
- Resource that = (Resource) o;
- return that.getId().equals(getId());
- }
-
- @Override
- public int hashCode() {
- return getId().hashCode();
- }
-
- private Resource getResourceModel() {
- return cacheSession.getResourceStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+// package org.keycloak.models.cache.infinispan.authorization;
+
+// import org.keycloak.authorization.model.CachedModel;
+// import org.keycloak.authorization.model.PermissionTicket;
+// import org.keycloak.authorization.model.Resource;
+// import org.keycloak.authorization.model.ResourceServer;
+// import org.keycloak.authorization.model.Scope;
+// import org.keycloak.authorization.store.PermissionTicketStore;
+// import org.keycloak.authorization.store.PolicyStore;
+// import org.keycloak.models.cache.infinispan.authorization.entities.CachedResource;
+
+// import java.util.Collections;
+// import java.util.LinkedList;
+// import java.util.List;
+// import java.util.Map;
+// import java.util.Set;
+// import java.util.function.Supplier;
+// import java.util.stream.Collectors;
+
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public class ResourceAdapter implements Resource, CachedModel<Resource> {
+
+// private final Supplier<Resource> modelSupplier;
+// protected final CachedResource cached;
+// protected final StoreFactoryCacheSession cacheSession;
+// protected Resource updated;
+
+// public ResourceAdapter(CachedResource cached, StoreFactoryCacheSession cacheSession) {
+// this.cached = cached;
+// this.cacheSession = cacheSession;
+// this.modelSupplier = this::getResourceModel;
+// }
+
+// @Override
+// public Resource getDelegateForUpdate() {
+// if (updated == null) {
+// updated = modelSupplier.get();
+// cacheSession.registerResourceInvalidation(cached.getId(), cached.getName(), cached.getType(), cached.getUris(modelSupplier), cached.getScopesIds(modelSupplier), cached.getResourceServerId(), cached.getOwner());
+// if (updated == null) throw new IllegalStateException("Not found in database");
+// }
+// return updated;
+// }
+
+// protected boolean invalidated;
+
+// protected void invalidateFlag() {
+// invalidated = true;
+
+// }
+
+// @Override
+// public void invalidate() {
+// invalidated = true;
+// getDelegateForUpdate();
+// }
+
+// // @Override
+// // public long getCacheTimestamp() {
+// // return cached.getCacheTimestamp();
+// // }
+
+// protected boolean isUpdated() {
+// if (updated != null) return true;
+// if (!invalidated) return false;
+// updated = cacheSession.getResourceStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
+// if (updated == null) throw new IllegalStateException("Not found in database");
+// return true;
+// }
+
+
+// @Override
+// public String getId() {
+// if (isUpdated()) return updated.getId();
+// return cached.getId();
+// }
+
+// @Override
+// public String getName() {
+// if (isUpdated()) return updated.getName();
+// return cached.getName();
+// }
+
+// @Override
+// public void setName(String name) {
+// getDelegateForUpdate();
+// cacheSession.registerResourceInvalidation(cached.getId(), name, cached.getType(), cached.getUris(modelSupplier), cached.getScopesIds(modelSupplier), cached.getResourceServerId(), cached.getOwner());
+// updated.setName(name);
+// }
+
+// @Override
+// public String getDisplayName() {
+// if (isUpdated()) return updated.getDisplayName();
+// return cached.getDisplayName();
+// }
+
+// @Override
+// public void setDisplayName(String name) {
+// getDelegateForUpdate();
+// cacheSession.registerResourceInvalidation(cached.getId(), name, cached.getType(), cached.getUris(modelSupplier), cached.getScopesIds(modelSupplier), cached.getResourceServerId(), cached.getOwner());
+// updated.setDisplayName(name);
+// }
+
+// @Override
+// public String getIconUri() {
+// if (isUpdated()) return updated.getIconUri();
+// return cached.getIconUri();
+// }
+
+// @Override
+// public void setIconUri(String iconUri) {
+// getDelegateForUpdate();
+// updated.setIconUri(iconUri);
+
+// }
+
+// @Override
+// public ResourceServer getResourceServer() {
+// return cacheSession.getResourceServerStore().findById(cached.getResourceServerId());
+// }
+
+// @Override
+// public Set<String> getUris() {
+// if (isUpdated()) return updated.getUris();
+// return cached.getUris(modelSupplier);
+// }
+
+// @Override
+// public void updateUris(Set<String> uris) {
+// getDelegateForUpdate();
+// cacheSession.registerResourceInvalidation(cached.getId(), cached.getName(), cached.getType(), uris, cached.getScopesIds(modelSupplier), cached.getResourceServerId(), cached.getOwner());
+// updated.updateUris(uris);
+// }
+
+// @Override
+// public String getType() {
+// if (isUpdated()) return updated.getType();
+// return cached.getType();
+// }
+
+// @Override
+// public void setType(String type) {
+// getDelegateForUpdate();
+// cacheSession.registerResourceInvalidation(cached.getId(), cached.getName(), type, cached.getUris(modelSupplier), cached.getScopesIds(modelSupplier), cached.getResourceServerId(), cached.getOwner());
+// updated.setType(type);
+
+// }
+
+// protected List<Scope> scopes;
+
+// @Override
+// public List<Scope> getScopes() {
+// if (isUpdated()) return updated.getScopes();
+// if (scopes != null) return scopes;
+// scopes = new LinkedList<>();
+// for (String scopeId : cached.getScopesIds(modelSupplier)) {
+// scopes.add(cacheSession.getScopeStore().findById(scopeId, cached.getResourceServerId()));
+// }
+// return scopes = Collections.unmodifiableList(scopes);
+// }
+
+// @Override
+// public String getOwner() {
+// if (isUpdated()) return updated.getOwner();
+// return cached.getOwner();
+// }
+
+// @Override
+// public boolean isOwnerManagedAccess() {
+// if (isUpdated()) return updated.isOwnerManagedAccess();
+// return cached.isOwnerManagedAccess();
+// }
+
+// @Override
+// public void setOwnerManagedAccess(boolean ownerManagedAccess) {
+// getDelegateForUpdate();
+// cacheSession.registerResourceInvalidation(cached.getId(), cached.getName(), cached.getType(), cached.getUris(modelSupplier), cached.getScopesIds(modelSupplier), cached.getResourceServerId(), cached.getOwner());
+// updated.setOwnerManagedAccess(ownerManagedAccess);
+// }
+
+// @Override
+// public void updateScopes(Set<Scope> scopes) {
+// Resource updated = getDelegateForUpdate();
+
+// for (Scope scope : updated.getScopes()) {
+// if (!scopes.contains(scope)) {
+// PermissionTicketStore permissionStore = cacheSession.getPermissionTicketStore();
+// List<PermissionTicket> permissions = permissionStore.findByScope(scope.getId(), getResourceServer().getId());
+
+// for (PermissionTicket permission : permissions) {
+// permissionStore.delete(permission.getId());
+// }
+// }
+// }
+
+// PolicyStore policyStore = cacheSession.getPolicyStore();
+
+// for (Scope scope : updated.getScopes()) {
+// if (!scopes.contains(scope)) {
+// policyStore.findByResource(getId(), getResourceServer().getId(), policy -> policy.removeScope(scope));
+// }
+// }
+
+// cacheSession.registerResourceInvalidation(cached.getId(), cached.getName(), cached.getType(), cached.getUris(modelSupplier), scopes.stream().map(scope1 -> scope1.getId()).collect(Collectors.toSet()), cached.getResourceServerId(), cached.getOwner());
+// updated.updateScopes(scopes);
+// }
+
+// @Override
+// public Map<String, List<String>> getAttributes() {
+// if (updated != null) return updated.getAttributes();
+// return cached.getAttributes(modelSupplier);
+// }
+
+// @Override
+// public String getSingleAttribute(String name) {
+// if (updated != null) return updated.getSingleAttribute(name);
+
+// List<String> values = cached.getAttributes(modelSupplier).getOrDefault(name, Collections.emptyList());
+
+// if (values.isEmpty()) {
+// return null;
+// }
+
+// return values.get(0);
+// }
+
+// @Override
+// public List<String> getAttribute(String name) {
+// if (updated != null) return updated.getAttribute(name);
+
+// List<String> values = cached.getAttributes(modelSupplier).getOrDefault(name, Collections.emptyList());
+
+// if (values.isEmpty()) {
+// return null;
+// }
+
+// return Collections.unmodifiableList(values);
+// }
+
+// @Override
+// public void setAttribute(String name, List<String> values) {
+// getDelegateForUpdate();
+// updated.setAttribute(name, values);
+// }
+
+// @Override
+// public void removeAttribute(String name) {
+// getDelegateForUpdate();
+// updated.removeAttribute(name);
+// }
+
+// @Override
+// public boolean isFetched(String association) {
+// return modelSupplier.get().isFetched(association);
+// }
+
+// @Override
+// public boolean equals(Object o) {
+// if (this == o) return true;
+// if (o == null || !(o instanceof Resource)) return false;
+
+// Resource that = (Resource) o;
+// return that.getId().equals(getId());
+// }
+
+// @Override
+// public int hashCode() {
+// return getId().hashCode();
+// }
+
+// private Resource getResourceModel() {
+// return cacheSession.getResourceStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/ResourceServerAdapter.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/ResourceServerAdapter.java
index 7d72c98..ff005fd 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/ResourceServerAdapter.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/ResourceServerAdapter.java
@@ -1,121 +1,121 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.keycloak.models.cache.infinispan.authorization;
-
-import org.keycloak.authorization.model.CachedModel;
-import org.keycloak.authorization.model.ResourceServer;
-import org.keycloak.models.cache.infinispan.authorization.entities.CachedResourceServer;
-import org.keycloak.representations.idm.authorization.PolicyEnforcementMode;
-
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class ResourceServerAdapter implements ResourceServer, CachedModel<ResourceServer> {
- protected CachedResourceServer cached;
- protected StoreFactoryCacheSession cacheSession;
- protected ResourceServer updated;
-
- public ResourceServerAdapter(CachedResourceServer cached, StoreFactoryCacheSession cacheSession) {
- this.cached = cached;
- this.cacheSession = cacheSession;
- }
-
- @Override
- public ResourceServer getDelegateForUpdate() {
- if (updated == null) {
- cacheSession.registerResourceServerInvalidation(cached.getId());
- updated = cacheSession.getResourceServerStoreDelegate().findById(cached.getId());
- if (updated == null) throw new IllegalStateException("Not found in database");
- }
- return updated;
- }
-
- protected boolean invalidated;
-
- protected void invalidateFlag() {
- invalidated = true;
-
- }
-
- @Override
- public void invalidate() {
- invalidated = true;
- getDelegateForUpdate();
- }
-
- @Override
- public long getCacheTimestamp() {
- return cached.getCacheTimestamp();
- }
-
- protected boolean isUpdated() {
- if (updated != null) return true;
- if (!invalidated) return false;
- updated = cacheSession.getResourceServerStoreDelegate().findById(cached.getId());
- if (updated == null) throw new IllegalStateException("Not found in database");
- return true;
- }
-
-
- @Override
- public String getId() {
- if (isUpdated()) return updated.getId();
- return cached.getId();
- }
-
- @Override
- public boolean isAllowRemoteResourceManagement() {
- if (isUpdated()) return updated.isAllowRemoteResourceManagement();
- return cached.isAllowRemoteResourceManagement();
- }
-
- @Override
- public void setAllowRemoteResourceManagement(boolean allowRemoteResourceManagement) {
- getDelegateForUpdate();
- updated.setAllowRemoteResourceManagement(allowRemoteResourceManagement);
- }
-
- @Override
- public PolicyEnforcementMode getPolicyEnforcementMode() {
- if (isUpdated()) return updated.getPolicyEnforcementMode();
- return cached.getPolicyEnforcementMode();
- }
-
- @Override
- public void setPolicyEnforcementMode(PolicyEnforcementMode enforcementMode) {
- getDelegateForUpdate();
- updated.setPolicyEnforcementMode(enforcementMode);
-
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || !(o instanceof ResourceServer)) return false;
-
- ResourceServer that = (ResourceServer) o;
- return that.getId().equals(getId());
- }
-
- @Override
- public int hashCode() {
- return getId().hashCode();
- }
-
-
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+// package org.keycloak.models.cache.infinispan.authorization;
+
+// import org.keycloak.authorization.model.CachedModel;
+// import org.keycloak.authorization.model.ResourceServer;
+// import org.keycloak.models.cache.infinispan.authorization.entities.CachedResourceServer;
+// import org.keycloak.representations.idm.authorization.PolicyEnforcementMode;
+
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public class ResourceServerAdapter implements ResourceServer{//, CachedModel<ResourceServer> {
+// protected CachedResourceServer cached;
+// protected StoreFactoryCacheSession cacheSession;
+// protected ResourceServer updated;
+
+// public ResourceServerAdapter(CachedResourceServer cached, StoreFactoryCacheSession cacheSession) {
+// this.cached = cached;
+// this.cacheSession = cacheSession;
+// }
+
+// @Override
+// public ResourceServer getDelegateForUpdate() {
+// if (updated == null) {
+// cacheSession.registerResourceServerInvalidation(cached.getId());
+// updated = cacheSession.getResourceServerStoreDelegate().findById(cached.getId());
+// if (updated == null) throw new IllegalStateException("Not found in database");
+// }
+// return updated;
+// }
+
+// protected boolean invalidated;
+
+// protected void invalidateFlag() {
+// invalidated = true;
+
+// }
+
+// @Override
+// public void invalidate() {
+// invalidated = true;
+// getDelegateForUpdate();
+// }
+
+// @Override
+// public long getCacheTimestamp() {
+// return cached.getCacheTimestamp();
+// }
+
+// protected boolean isUpdated() {
+// if (updated != null) return true;
+// if (!invalidated) return false;
+// updated = cacheSession.getResourceServerStoreDelegate().findById(cached.getId());
+// if (updated == null) throw new IllegalStateException("Not found in database");
+// return true;
+// }
+
+
+// @Override
+// public String getId() {
+// if (isUpdated()) return updated.getId();
+// return cached.getId();
+// }
+
+// @Override
+// public boolean isAllowRemoteResourceManagement() {
+// if (isUpdated()) return updated.isAllowRemoteResourceManagement();
+// return cached.isAllowRemoteResourceManagement();
+// }
+
+// @Override
+// public void setAllowRemoteResourceManagement(boolean allowRemoteResourceManagement) {
+// getDelegateForUpdate();
+// updated.setAllowRemoteResourceManagement(allowRemoteResourceManagement);
+// }
+
+// @Override
+// public PolicyEnforcementMode getPolicyEnforcementMode() {
+// if (isUpdated()) return updated.getPolicyEnforcementMode();
+// return cached.getPolicyEnforcementMode();
+// }
+
+// @Override
+// public void setPolicyEnforcementMode(PolicyEnforcementMode enforcementMode) {
+// getDelegateForUpdate();
+// updated.setPolicyEnforcementMode(enforcementMode);
+
+// }
+
+// @Override
+// public boolean equals(Object o) {
+// if (this == o) return true;
+// if (o == null || !(o instanceof ResourceServer)) return false;
+
+// ResourceServer that = (ResourceServer) o;
+// return that.getId().equals(getId());
+// }
+
+// @Override
+// public int hashCode() {
+// return getId().hashCode();
+// }
+
+
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/ScopeAdapter.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/ScopeAdapter.java
index a4492a7..a1d538f 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/ScopeAdapter.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/ScopeAdapter.java
@@ -1,139 +1,139 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.keycloak.models.cache.infinispan.authorization;
-
-import org.keycloak.authorization.model.CachedModel;
-import org.keycloak.authorization.model.ResourceServer;
-import org.keycloak.authorization.model.Scope;
-import org.keycloak.models.cache.infinispan.authorization.entities.CachedScope;
-
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class ScopeAdapter implements Scope, CachedModel<Scope> {
- protected CachedScope cached;
- protected StoreFactoryCacheSession cacheSession;
- protected Scope updated;
-
- public ScopeAdapter(CachedScope cached, StoreFactoryCacheSession cacheSession) {
- this.cached = cached;
- this.cacheSession = cacheSession;
- }
-
- @Override
- public Scope getDelegateForUpdate() {
- if (updated == null) {
- cacheSession.registerScopeInvalidation(cached.getId(), cached.getName(), cached.getResourceServerId());
- updated = cacheSession.getScopeStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
- if (updated == null) throw new IllegalStateException("Not found in database");
- }
- return updated;
- }
-
- protected boolean invalidated;
-
- protected void invalidateFlag() {
- invalidated = true;
-
- }
-
- @Override
- public void invalidate() {
- invalidated = true;
- getDelegateForUpdate();
- }
-
- @Override
- public long getCacheTimestamp() {
- return cached.getCacheTimestamp();
- }
-
- protected boolean isUpdated() {
- if (updated != null) return true;
- if (!invalidated) return false;
- updated = cacheSession.getScopeStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
- if (updated == null) throw new IllegalStateException("Not found in database");
- return true;
- }
-
-
- @Override
- public String getId() {
- if (isUpdated()) return updated.getId();
- return cached.getId();
- }
-
- @Override
- public String getName() {
- if (isUpdated()) return updated.getName();
- return cached.getName();
- }
-
- @Override
- public void setName(String name) {
- getDelegateForUpdate();
- updated.setName(name);
-
- }
-
- @Override
- public String getDisplayName() {
- if (isUpdated()) return updated.getDisplayName();
- return cached.getDisplayName();
- }
-
- @Override
- public void setDisplayName(String name) {
- getDelegateForUpdate();
- updated.setDisplayName(name);
- }
-
- @Override
- public String getIconUri() {
- if (isUpdated()) return updated.getIconUri();
- return cached.getIconUri();
- }
-
- @Override
- public void setIconUri(String iconUri) {
- getDelegateForUpdate();
- updated.setIconUri(iconUri);
-
- }
-
- @Override
- public ResourceServer getResourceServer() {
- return cacheSession.getResourceServerStore().findById(cached.getResourceServerId());
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || !(o instanceof Scope)) return false;
-
- Scope that = (Scope) o;
- return that.getId().equals(getId());
- }
-
- @Override
- public int hashCode() {
- return getId().hashCode();
- }
-
-
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+// package org.keycloak.models.cache.infinispan.authorization;
+
+// import org.keycloak.authorization.model.CachedModel;
+// import org.keycloak.authorization.model.ResourceServer;
+// import org.keycloak.authorization.model.Scope;
+// import org.keycloak.models.cache.infinispan.authorization.entities.CachedScope;
+
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public class ScopeAdapter implements Scope, CachedModel<Scope> {
+// protected CachedScope cached;
+// protected StoreFactoryCacheSession cacheSession;
+// protected Scope updated;
+
+// public ScopeAdapter(CachedScope cached, StoreFactoryCacheSession cacheSession) {
+// this.cached = cached;
+// this.cacheSession = cacheSession;
+// }
+
+// @Override
+// public Scope getDelegateForUpdate() {
+// if (updated == null) {
+// cacheSession.registerScopeInvalidation(cached.getId(), cached.getName(), cached.getResourceServerId());
+// updated = cacheSession.getScopeStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
+// if (updated == null) throw new IllegalStateException("Not found in database");
+// }
+// return updated;
+// }
+
+// protected boolean invalidated;
+
+// protected void invalidateFlag() {
+// invalidated = true;
+
+// }
+
+// @Override
+// public void invalidate() {
+// invalidated = true;
+// getDelegateForUpdate();
+// }
+
+// @Override
+// public long getCacheTimestamp() {
+// return cached.getCacheTimestamp();
+// }
+
+// protected boolean isUpdated() {
+// if (updated != null) return true;
+// if (!invalidated) return false;
+// updated = cacheSession.getScopeStoreDelegate().findById(cached.getId(), cached.getResourceServerId());
+// if (updated == null) throw new IllegalStateException("Not found in database");
+// return true;
+// }
+
+
+// @Override
+// public String getId() {
+// if (isUpdated()) return updated.getId();
+// return cached.getId();
+// }
+
+// @Override
+// public String getName() {
+// if (isUpdated()) return updated.getName();
+// return cached.getName();
+// }
+
+// @Override
+// public void setName(String name) {
+// getDelegateForUpdate();
+// updated.setName(name);
+
+// }
+
+// @Override
+// public String getDisplayName() {
+// if (isUpdated()) return updated.getDisplayName();
+// return cached.getDisplayName();
+// }
+
+// @Override
+// public void setDisplayName(String name) {
+// getDelegateForUpdate();
+// updated.setDisplayName(name);
+// }
+
+// @Override
+// public String getIconUri() {
+// if (isUpdated()) return updated.getIconUri();
+// return cached.getIconUri();
+// }
+
+// @Override
+// public void setIconUri(String iconUri) {
+// getDelegateForUpdate();
+// updated.setIconUri(iconUri);
+
+// }
+
+// @Override
+// public ResourceServer getResourceServer() {
+// return cacheSession.getResourceServerStore().findById(cached.getResourceServerId());
+// }
+
+// @Override
+// public boolean equals(Object o) {
+// if (this == o) return true;
+// if (o == null || !(o instanceof Scope)) return false;
+
+// Scope that = (Scope) o;
+// return that.getId().equals(getId());
+// }
+
+// @Override
+// public int hashCode() {
+// return getId().hashCode();
+// }
+
+
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/StoreFactoryCacheManager.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/StoreFactoryCacheManager.java
index 9b92678..03f2188 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/StoreFactoryCacheManager.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/StoreFactoryCacheManager.java
@@ -1,158 +1,158 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.keycloak.models.cache.infinispan.authorization;
-
-import org.infinispan.Cache;
-import org.jboss.logging.Logger;
-import org.keycloak.models.cache.infinispan.CacheManager;
-import org.keycloak.models.cache.infinispan.RealmCacheManager;
-import org.keycloak.models.cache.infinispan.authorization.events.AuthorizationCacheInvalidationEvent;
-import org.keycloak.models.cache.infinispan.authorization.stream.InResourcePredicate;
-import org.keycloak.models.cache.infinispan.authorization.stream.InResourceServerPredicate;
-import org.keycloak.models.cache.infinispan.authorization.stream.InScopePredicate;
-import org.keycloak.models.cache.infinispan.entities.Revisioned;
-import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
-
-import java.util.Objects;
-import java.util.Set;
-
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class StoreFactoryCacheManager extends CacheManager {
- private static final Logger logger = Logger.getLogger(StoreFactoryCacheManager.class);
-
- public StoreFactoryCacheManager(Cache<String, Revisioned> cache, Cache<String, Long> revisions) {
- super(cache, revisions);
- }
- @Override
- protected Logger getLogger() {
- return logger;
- }
-
- @Override
- protected void addInvalidationsFromEvent(InvalidationEvent event, Set<String> invalidations) {
- if (event instanceof AuthorizationCacheInvalidationEvent) {
- invalidations.add(event.getId());
-
- ((AuthorizationCacheInvalidationEvent) event).addInvalidations(this, invalidations);
- }
- }
-
- public void resourceServerUpdated(String id, Set<String> invalidations) {
- invalidations.add(id);
- invalidations.add(StoreFactoryCacheSession.getResourceServerByClientCacheKey(id));
- }
-
- public void resourceServerRemoval(String id, Set<String> invalidations) {
- resourceServerUpdated(id, invalidations);
-
- addInvalidations(InResourceServerPredicate.create().resourceServer(id), invalidations);
- }
-
- public void scopeUpdated(String id, String name, String serverId, Set<String> invalidations) {
- invalidations.add(id);
- invalidations.add(StoreFactoryCacheSession.getScopeByNameCacheKey(name, serverId));
- invalidations.add(StoreFactoryCacheSession.getResourceByScopeCacheKey(id, serverId));
- invalidations.add(StoreFactoryCacheSession.getPermissionTicketByScope(id, serverId));
- }
-
- public void scopeRemoval(String id, String name, String serverId, Set<String> invalidations) {
- scopeUpdated(id, name, serverId, invalidations);
- addInvalidations(InScopePredicate.create().scope(id), invalidations);
- }
-
- public void resourceUpdated(String id, String name, String type, Set<String> uris, Set<String> scopes, String serverId, String owner, Set<String> invalidations) {
- invalidations.add(id);
- invalidations.add(StoreFactoryCacheSession.getResourceByNameCacheKey(name, owner, serverId));
- invalidations.add(StoreFactoryCacheSession.getResourceByOwnerCacheKey(owner, serverId));
- invalidations.add(StoreFactoryCacheSession.getResourceByOwnerCacheKey(owner, null));
- invalidations.add(StoreFactoryCacheSession.getPermissionTicketByResource(id, serverId));
-
- if (type != null) {
- invalidations.add(StoreFactoryCacheSession.getResourceByTypeCacheKey(type, serverId));
- addInvalidations(InResourcePredicate.create().resource(type), invalidations);
- }
-
- if (uris != null) {
- for (String uri: uris) {
- invalidations.add(StoreFactoryCacheSession.getResourceByUriCacheKey(uri, serverId));
- }
- }
-
- if (scopes != null) {
- for (String scope : scopes) {
- invalidations.add(StoreFactoryCacheSession.getResourceByScopeCacheKey(scope, serverId));
- addInvalidations(InScopePredicate.create().scope(scope), invalidations);
- }
- }
- }
-
- public void resourceRemoval(String id, String name, String type, Set<String> uris, String owner, Set<String> scopes, String serverId, Set<String> invalidations) {
- resourceUpdated(id, name, type, uris, scopes, serverId, owner, invalidations);
- addInvalidations(InResourcePredicate.create().resource(id), invalidations);
- }
-
- public void policyUpdated(String id, String name, Set<String> resources, Set<String> resourceTypes, Set<String> scopes, String serverId, Set<String> invalidations) {
- invalidations.add(id);
- invalidations.add(StoreFactoryCacheSession.getPolicyByNameCacheKey(name, serverId));
-
- if (resources != null) {
- for (String resource : resources) {
- invalidations.add(StoreFactoryCacheSession.getPolicyByResource(resource, serverId));
- if (Objects.nonNull(scopes)) {
- for (String scope : scopes) {
- invalidations.add(StoreFactoryCacheSession.getPolicyByResourceScope(scope, resource, serverId));
- }
- }
- }
- }
-
- if (resourceTypes != null) {
- for (String type : resourceTypes) {
- invalidations.add(StoreFactoryCacheSession.getPolicyByResourceType(type, serverId));
- }
- }
-
- if (scopes != null) {
- for (String scope : scopes) {
- invalidations.add(StoreFactoryCacheSession.getPolicyByScope(scope, serverId));
- invalidations.add(StoreFactoryCacheSession.getPolicyByResourceScope(scope, null, serverId));
- }
- }
- }
-
- public void permissionTicketUpdated(String id, String owner, String requester, String resource, String scope, String serverId, Set<String> invalidations) {
- invalidations.add(id);
- invalidations.add(StoreFactoryCacheSession.getPermissionTicketByOwner(owner, serverId));
- invalidations.add(StoreFactoryCacheSession.getPermissionTicketByResource(resource, serverId));
- invalidations.add(StoreFactoryCacheSession.getPermissionTicketByGranted(requester, serverId));
- if (scope != null) {
- invalidations.add(StoreFactoryCacheSession.getPermissionTicketByScope(scope, serverId));
- }
- }
-
- public void policyRemoval(String id, String name, Set<String> resources, Set<String> resourceTypes, Set<String> scopes, String serverId, Set<String> invalidations) {
- policyUpdated(id, name, resources, resourceTypes, scopes, serverId, invalidations);
- }
-
- public void permissionTicketRemoval(String id, String owner, String requester, String resource, String scope, String serverId, Set<String> invalidations) {
- permissionTicketUpdated(id, owner, requester, resource, scope, serverId, invalidations);
- }
-
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+// package org.keycloak.models.cache.infinispan.authorization;
+
+// import org.infinispan.Cache;
+// import org.jboss.logging.Logger;
+// import org.keycloak.models.cache.infinispan.CacheManager;
+// import org.keycloak.models.cache.infinispan.RealmCacheManager;
+// import org.keycloak.models.cache.infinispan.authorization.events.AuthorizationCacheInvalidationEvent;
+// import org.keycloak.models.cache.infinispan.authorization.stream.InResourcePredicate;
+// import org.keycloak.models.cache.infinispan.authorization.stream.InResourceServerPredicate;
+// import org.keycloak.models.cache.infinispan.authorization.stream.InScopePredicate;
+// import org.keycloak.models.cache.infinispan.entities.Revisioned;
+// import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
+
+// import java.util.Objects;
+// import java.util.Set;
+
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public class StoreFactoryCacheManager extends CacheManager {
+// private static final Logger logger = Logger.getLogger(StoreFactoryCacheManager.class);
+
+// public StoreFactoryCacheManager(Cache<String, Revisioned> cache, Cache<String, Long> revisions) {
+// super(cache, revisions);
+// }
+// @Override
+// protected Logger getLogger() {
+// return logger;
+// }
+
+// @Override
+// protected void addInvalidationsFromEvent(InvalidationEvent event, Set<String> invalidations) {
+// if (event instanceof AuthorizationCacheInvalidationEvent) {
+// invalidations.add(event.getId());
+
+// ((AuthorizationCacheInvalidationEvent) event).addInvalidations(this, invalidations);
+// }
+// }
+
+// public void resourceServerUpdated(String id, Set<String> invalidations) {
+// invalidations.add(id);
+// invalidations.add(StoreFactoryCacheSession.getResourceServerByClientCacheKey(id));
+// }
+
+// public void resourceServerRemoval(String id, Set<String> invalidations) {
+// resourceServerUpdated(id, invalidations);
+
+// addInvalidations(InResourceServerPredicate.create().resourceServer(id), invalidations);
+// }
+
+// public void scopeUpdated(String id, String name, String serverId, Set<String> invalidations) {
+// invalidations.add(id);
+// invalidations.add(StoreFactoryCacheSession.getScopeByNameCacheKey(name, serverId));
+// invalidations.add(StoreFactoryCacheSession.getResourceByScopeCacheKey(id, serverId));
+// invalidations.add(StoreFactoryCacheSession.getPermissionTicketByScope(id, serverId));
+// }
+
+// public void scopeRemoval(String id, String name, String serverId, Set<String> invalidations) {
+// scopeUpdated(id, name, serverId, invalidations);
+// addInvalidations(InScopePredicate.create().scope(id), invalidations);
+// }
+
+// public void resourceUpdated(String id, String name, String type, Set<String> uris, Set<String> scopes, String serverId, String owner, Set<String> invalidations) {
+// invalidations.add(id);
+// invalidations.add(StoreFactoryCacheSession.getResourceByNameCacheKey(name, owner, serverId));
+// invalidations.add(StoreFactoryCacheSession.getResourceByOwnerCacheKey(owner, serverId));
+// invalidations.add(StoreFactoryCacheSession.getResourceByOwnerCacheKey(owner, null));
+// invalidations.add(StoreFactoryCacheSession.getPermissionTicketByResource(id, serverId));
+
+// if (type != null) {
+// invalidations.add(StoreFactoryCacheSession.getResourceByTypeCacheKey(type, serverId));
+// addInvalidations(InResourcePredicate.create().resource(type), invalidations);
+// }
+
+// if (uris != null) {
+// for (String uri: uris) {
+// invalidations.add(StoreFactoryCacheSession.getResourceByUriCacheKey(uri, serverId));
+// }
+// }
+
+// if (scopes != null) {
+// for (String scope : scopes) {
+// invalidations.add(StoreFactoryCacheSession.getResourceByScopeCacheKey(scope, serverId));
+// addInvalidations(InScopePredicate.create().scope(scope), invalidations);
+// }
+// }
+// }
+
+// public void resourceRemoval(String id, String name, String type, Set<String> uris, String owner, Set<String> scopes, String serverId, Set<String> invalidations) {
+// resourceUpdated(id, name, type, uris, scopes, serverId, owner, invalidations);
+// addInvalidations(InResourcePredicate.create().resource(id), invalidations);
+// }
+
+// public void policyUpdated(String id, String name, Set<String> resources, Set<String> resourceTypes, Set<String> scopes, String serverId, Set<String> invalidations) {
+// invalidations.add(id);
+// invalidations.add(StoreFactoryCacheSession.getPolicyByNameCacheKey(name, serverId));
+
+// if (resources != null) {
+// for (String resource : resources) {
+// invalidations.add(StoreFactoryCacheSession.getPolicyByResource(resource, serverId));
+// if (Objects.nonNull(scopes)) {
+// for (String scope : scopes) {
+// invalidations.add(StoreFactoryCacheSession.getPolicyByResourceScope(scope, resource, serverId));
+// }
+// }
+// }
+// }
+
+// if (resourceTypes != null) {
+// for (String type : resourceTypes) {
+// invalidations.add(StoreFactoryCacheSession.getPolicyByResourceType(type, serverId));
+// }
+// }
+
+// if (scopes != null) {
+// for (String scope : scopes) {
+// invalidations.add(StoreFactoryCacheSession.getPolicyByScope(scope, serverId));
+// invalidations.add(StoreFactoryCacheSession.getPolicyByResourceScope(scope, null, serverId));
+// }
+// }
+// }
+
+// public void permissionTicketUpdated(String id, String owner, String requester, String resource, String scope, String serverId, Set<String> invalidations) {
+// invalidations.add(id);
+// invalidations.add(StoreFactoryCacheSession.getPermissionTicketByOwner(owner, serverId));
+// invalidations.add(StoreFactoryCacheSession.getPermissionTicketByResource(resource, serverId));
+// invalidations.add(StoreFactoryCacheSession.getPermissionTicketByGranted(requester, serverId));
+// if (scope != null) {
+// invalidations.add(StoreFactoryCacheSession.getPermissionTicketByScope(scope, serverId));
+// }
+// }
+
+// public void policyRemoval(String id, String name, Set<String> resources, Set<String> resourceTypes, Set<String> scopes, String serverId, Set<String> invalidations) {
+// policyUpdated(id, name, resources, resourceTypes, scopes, serverId, invalidations);
+// }
+
+// public void permissionTicketRemoval(String id, String owner, String requester, String resource, String scope, String serverId, Set<String> invalidations) {
+// permissionTicketUpdated(id, owner, requester, resource, scope, serverId, invalidations);
+// }
+
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/StoreFactoryCacheSession.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/StoreFactoryCacheSession.java
index 7689816..0cda3f2 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/StoreFactoryCacheSession.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/authorization/StoreFactoryCacheSession.java
@@ -1,1148 +1,1152 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.keycloak.models.cache.infinispan.authorization;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Set;
-import java.util.function.BiFunction;
-import java.util.function.Consumer;
-import java.util.function.Supplier;
-import java.util.stream.Collectors;
-
-import org.jboss.logging.Logger;
-import org.keycloak.authorization.UserManagedPermissionUtil;
-import org.keycloak.authorization.model.PermissionTicket;
-import org.keycloak.authorization.model.Policy;
-import org.keycloak.authorization.model.Resource;
-import org.keycloak.authorization.model.ResourceServer;
-import org.keycloak.authorization.model.Scope;
-import org.keycloak.authorization.store.PermissionTicketStore;
-import org.keycloak.authorization.store.PolicyStore;
-import org.keycloak.authorization.store.ResourceServerStore;
-import org.keycloak.authorization.store.ResourceStore;
-import org.keycloak.authorization.store.ScopeStore;
-import org.keycloak.authorization.store.StoreFactory;
-import org.keycloak.models.KeycloakSession;
-import org.keycloak.models.KeycloakTransaction;
-import org.keycloak.models.ModelException;
-import org.keycloak.models.cache.authorization.CachedStoreFactoryProvider;
-import org.keycloak.models.cache.infinispan.authorization.entities.CachedPermissionTicket;
-import org.keycloak.models.cache.infinispan.authorization.entities.CachedPolicy;
-import org.keycloak.models.cache.infinispan.authorization.entities.CachedResource;
-import org.keycloak.models.cache.infinispan.authorization.entities.CachedResourceServer;
-import org.keycloak.models.cache.infinispan.authorization.entities.CachedScope;
-import org.keycloak.models.cache.infinispan.authorization.entities.PermissionTicketListQuery;
-import org.keycloak.models.cache.infinispan.authorization.entities.PermissionTicketQuery;
-import org.keycloak.models.cache.infinispan.authorization.entities.PermissionTicketResourceListQuery;
-import org.keycloak.models.cache.infinispan.authorization.entities.PermissionTicketScopeListQuery;
-import org.keycloak.models.cache.infinispan.authorization.entities.PolicyListQuery;
-import org.keycloak.models.cache.infinispan.authorization.entities.PolicyQuery;
-import org.keycloak.models.cache.infinispan.authorization.entities.PolicyResourceListQuery;
-import org.keycloak.models.cache.infinispan.authorization.entities.PolicyScopeListQuery;
-import org.keycloak.models.cache.infinispan.authorization.entities.ResourceListQuery;
-import org.keycloak.models.cache.infinispan.authorization.entities.ResourceQuery;
-import org.keycloak.models.cache.infinispan.authorization.entities.ResourceScopeListQuery;
-import org.keycloak.models.cache.infinispan.authorization.entities.ScopeListQuery;
-import org.keycloak.models.cache.infinispan.authorization.events.PermissionTicketRemovedEvent;
-import org.keycloak.models.cache.infinispan.authorization.events.PermissionTicketUpdatedEvent;
-import org.keycloak.models.cache.infinispan.authorization.events.PolicyRemovedEvent;
-import org.keycloak.models.cache.infinispan.authorization.events.PolicyUpdatedEvent;
-import org.keycloak.models.cache.infinispan.authorization.events.ResourceRemovedEvent;
-import org.keycloak.models.cache.infinispan.authorization.events.ResourceServerRemovedEvent;
-import org.keycloak.models.cache.infinispan.authorization.events.ResourceServerUpdatedEvent;
-import org.keycloak.models.cache.infinispan.authorization.events.ResourceUpdatedEvent;
-import org.keycloak.models.cache.infinispan.authorization.events.ScopeRemovedEvent;
-import org.keycloak.models.cache.infinispan.authorization.events.ScopeUpdatedEvent;
-import org.keycloak.models.cache.infinispan.entities.NonExistentItem;
-import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
-import org.keycloak.representations.idm.authorization.AbstractPolicyRepresentation;
-import org.keycloak.storage.StorageId;
-
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
- protected static final Logger logger = Logger.getLogger(StoreFactoryCacheSession.class);
-
- protected StoreFactoryCacheManager cache;
- protected boolean transactionActive;
- protected boolean setRollbackOnly;
-
- protected Map<String, ResourceServerAdapter> managedResourceServers = new HashMap<>();
- protected Map<String, ScopeAdapter> managedScopes = new HashMap<>();
- protected Map<String, ResourceAdapter> managedResources = new HashMap<>();
- protected Map<String, PolicyAdapter> managedPolicies = new HashMap<>();
- protected Map<String, PermissionTicketAdapter> managedPermissionTickets = new HashMap<>();
- protected Set<String> invalidations = new HashSet<>();
- protected Set<InvalidationEvent> invalidationEvents = new HashSet<>(); // Events to be sent across cluster
-
- protected boolean clearAll;
- protected final long startupRevision;
- protected StoreFactory delegate;
- protected KeycloakSession session;
- protected ResourceServerCache resourceServerCache;
- protected ScopeCache scopeCache;
- protected ResourceCache resourceCache;
- protected PolicyCache policyCache;
- protected PermissionTicketCache permissionTicketCache;
-
- public StoreFactoryCacheSession(StoreFactoryCacheManager cache, KeycloakSession session) {
- this.cache = cache;
- this.startupRevision = cache.getCurrentCounter();
- this.session = session;
- this.resourceServerCache = new ResourceServerCache();
- this.scopeCache = new ScopeCache();
- this.resourceCache = new ResourceCache();
- this.policyCache = new PolicyCache();
- this.permissionTicketCache = new PermissionTicketCache();
- session.getTransactionManager().enlistPrepare(getPrepareTransaction());
- session.getTransactionManager().enlistAfterCompletion(getAfterTransaction());
- }
-
- @Override
- public ResourceServerStore getResourceServerStore() {
- return resourceServerCache;
- }
-
- @Override
- public ScopeStore getScopeStore() {
- return scopeCache;
- }
-
- @Override
- public ResourceStore getResourceStore() {
- return resourceCache;
- }
-
- @Override
- public PolicyStore getPolicyStore() {
- return policyCache;
- }
-
- @Override
- public PermissionTicketStore getPermissionTicketStore() {
- return permissionTicketCache;
- }
-
- @Override
- public void setReadOnly(boolean readOnly) {
- getDelegate().setReadOnly(readOnly);
- }
-
- @Override
- public boolean isReadOnly() {
- return getDelegate().isReadOnly();
- }
-
- public void close() {
- if (delegate != null) {
- delegate.close();
- }
- }
-
- private KeycloakTransaction getPrepareTransaction() {
- return new KeycloakTransaction() {
- @Override
- public void begin() {
- transactionActive = true;
- }
-
- @Override
- public void commit() {
- }
-
- @Override
- public void rollback() {
- setRollbackOnly = true;
- transactionActive = false;
- }
-
- @Override
- public void setRollbackOnly() {
- setRollbackOnly = true;
- }
-
- @Override
- public boolean getRollbackOnly() {
- return setRollbackOnly;
- }
-
- @Override
- public boolean isActive() {
- return transactionActive;
- }
- };
- }
-
- private KeycloakTransaction getAfterTransaction() {
- return new KeycloakTransaction() {
- @Override
- public void begin() {
- transactionActive = true;
- }
-
- @Override
- public void commit() {
- try {
- runInvalidations();
- transactionActive = false;
- } finally {
- cache.endRevisionBatch();
- }
- }
-
- @Override
- public void rollback() {
- try {
- setRollbackOnly = true;
- runInvalidations();
- transactionActive = false;
- } finally {
- cache.endRevisionBatch();
- }
- }
-
- @Override
- public void setRollbackOnly() {
- setRollbackOnly = true;
- }
-
- @Override
- public boolean getRollbackOnly() {
- return setRollbackOnly;
- }
-
- @Override
- public boolean isActive() {
- return transactionActive;
- }
- };
- }
-
- protected void runInvalidations() {
- for (String id : invalidations) {
- cache.invalidateObject(id);
- }
-
- cache.sendInvalidationEvents(session, invalidationEvents, InfinispanCacheStoreFactoryProviderFactory.AUTHORIZATION_INVALIDATION_EVENTS);
- }
-
-
-
- public long getStartupRevision() {
- return startupRevision;
- }
-
- public boolean isInvalid(String id) {
- return invalidations.contains(id);
- }
-
- public void registerResourceServerInvalidation(String id) {
- cache.resourceServerUpdated(id, invalidations);
- ResourceServerAdapter adapter = managedResourceServers.get(id);
- if (adapter != null) adapter.invalidateFlag();
-
- invalidationEvents.add(ResourceServerUpdatedEvent.create(id));
- }
-
- public void registerScopeInvalidation(String id, String name, String serverId) {
- cache.scopeUpdated(id, name, serverId, invalidations);
- ScopeAdapter adapter = managedScopes.get(id);
- if (adapter != null) adapter.invalidateFlag();
-
- invalidationEvents.add(ScopeUpdatedEvent.create(id, name, serverId));
- }
-
- public void registerResourceInvalidation(String id, String name, String type, Set<String> uris, Set<String> scopes, String serverId, String owner) {
- cache.resourceUpdated(id, name, type, uris, scopes, serverId, owner, invalidations);
- ResourceAdapter adapter = managedResources.get(id);
- if (adapter != null) adapter.invalidateFlag();
-
- invalidationEvents.add(ResourceUpdatedEvent.create(id, name, type, uris, scopes, serverId, owner));
- }
-
- public void registerPolicyInvalidation(String id, String name, Set<String> resources, Set<String> scopes, String defaultResourceType, String serverId) {
- Set<String> resourceTypes = getResourceTypes(resources, serverId);
- if (Objects.nonNull(defaultResourceType)) {
- resourceTypes.add(defaultResourceType);
- }
- cache.policyUpdated(id, name, resources, resourceTypes, scopes, serverId, invalidations);
- PolicyAdapter adapter = managedPolicies.get(id);
- if (adapter != null) adapter.invalidateFlag();
-
- invalidationEvents.add(PolicyUpdatedEvent.create(id, name, resources, resourceTypes, scopes, serverId));
- }
-
- public void registerPermissionTicketInvalidation(String id, String owner, String requester, String resource, String scope, String serverId) {
- cache.permissionTicketUpdated(id, owner, requester, resource, scope, serverId, invalidations);
- PermissionTicketAdapter adapter = managedPermissionTickets.get(id);
- if (adapter != null) adapter.invalidateFlag();
-
- invalidationEvents.add(PermissionTicketUpdatedEvent.create(id, owner, requester, resource, scope, serverId));
- }
-
- private Set<String> getResourceTypes(Set<String> resources, String serverId) {
- if (resources == null) {
- return Collections.emptySet();
- }
-
- return resources.stream().map(resourceId -> {
- Resource resource = getResourceStore().findById(resourceId, serverId);
- String type = resource.getType();
-
- if (type != null) {
- return type;
- }
-
- return null;
- }).filter(Objects::nonNull).collect(Collectors.toSet());
- }
-
- public ResourceServerStore getResourceServerStoreDelegate() {
- return getDelegate().getResourceServerStore();
- }
-
- public ScopeStore getScopeStoreDelegate() {
- return getDelegate().getScopeStore();
- }
-
- public ResourceStore getResourceStoreDelegate() {
- return getDelegate().getResourceStore();
- }
-
- public PolicyStore getPolicyStoreDelegate() {
- return getDelegate().getPolicyStore();
- }
-
- public PermissionTicketStore getPermissionTicketStoreDelegate() {
- return getDelegate().getPermissionTicketStore();
- }
-
- public static String getResourceServerByClientCacheKey(String clientId) {
- return "resource.server.client.id." + clientId;
- }
-
- public static String getScopeByNameCacheKey(String name, String serverId) {
- return "scope.name." + name + "." + serverId;
- }
-
- public static String getResourceByNameCacheKey(String name, String ownerId, String serverId) {
- return "resource.name." + name + "." + ownerId + "." + serverId;
- }
-
- public static String getResourceByOwnerCacheKey(String owner, String serverId) {
- return "resource.owner." + owner + "." + serverId;
- }
-
- public static String getResourceByTypeCacheKey(String type, String serverId) {
- return "resource.type." + type + "." + serverId;
- }
-
- public static String getResourceByUriCacheKey(String uri, String serverId) {
- return "resource.uri." + uri + "." + serverId;
- }
-
- public static String getResourceByScopeCacheKey(String scopeId, String serverId) {
- return "resource.scope." + scopeId + "." + serverId;
- }
-
- public static String getPolicyByNameCacheKey(String name, String serverId) {
- return "policy.name." + name + "." + serverId;
- }
-
- public static String getPolicyByResource(String resourceId, String serverId) {
- return "policy.resource." + resourceId + "." + serverId;
- }
-
- public static String getPolicyByResourceType(String type, String serverId) {
- return "policy.resource.type." + type + "." + serverId;
- }
-
- public static String getPolicyByScope(String scope, String serverId) {
- return "policy.scope." + scope + "." + serverId;
- }
-
- public static String getPolicyByResourceScope(String scope, String resourceId, String serverId) {
- return "policy.resource. " + resourceId + ".scope." + scope + "." + serverId;
- }
-
- public static String getPermissionTicketByResource(String resourceId, String serverId) {
- return "permission.ticket.resource." + resourceId + "." + serverId;
- }
-
- public static String getPermissionTicketByScope(String scopeId, String serverId) {
- return "permission.ticket.scope." + scopeId + "." + serverId;
- }
-
- public static String getPermissionTicketByGranted(String userId, String serverId) {
- return "permission.ticket.granted." + userId + "." + serverId;
- }
-
- public static String getPermissionTicketByOwner(String owner, String serverId) {
- return "permission.ticket.owner." + owner + "." + serverId;
- }
-
- public StoreFactory getDelegate() {
- if (delegate != null) return delegate;
- delegate = session.getProvider(StoreFactory.class);
- return delegate;
- }
-
- private void setModelDoesNotExists(String id, Long loaded) {
- if (! invalidations.contains(id)) {
- cache.addRevisioned(new NonExistentItem(id, loaded), startupRevision);
- }
- }
-
- boolean modelMightExist(String id) {
- return invalidations.contains(id) || cache.get(id, NonExistentItem.class) == null;
- }
-
- protected class ResourceServerCache implements ResourceServerStore {
- @Override
- public ResourceServer create(String clientId) {
- if (!StorageId.isLocalStorage(clientId)) {
- throw new ModelException("Creating resource server from federated ClientModel not supported");
- }
- ResourceServer server = getResourceServerStoreDelegate().create(clientId);
- registerResourceServerInvalidation(server.getId());
- return server;
- }
-
- @Override
- public void delete(String id) {
- if (id == null) return;
- ResourceServer server = findById(id);
- if (server == null) return;
-
- cache.invalidateObject(id);
- invalidationEvents.add(ResourceServerRemovedEvent.create(id, server.getId()));
- cache.resourceServerRemoval(id, invalidations);
- getResourceServerStoreDelegate().delete(id);
-
- }
-
- @Override
- public ResourceServer findById(String id) {
- if (id == null) return null;
- CachedResourceServer cached = cache.get(id, CachedResourceServer.class);
- if (cached != null) {
- logger.tracev("by id cache hit: {0}", cached.getId());
- }
-
- if (cached == null) {
- Long loaded = cache.getCurrentRevision(id);
- if (! modelMightExist(id)) return null;
- ResourceServer model = getResourceServerStoreDelegate().findById(id);
- if (model == null) {
- setModelDoesNotExists(id, loaded);
- return null;
- }
- if (invalidations.contains(id)) return model;
- cached = new CachedResourceServer(loaded, model);
- cache.addRevisioned(cached, startupRevision);
- } else if (invalidations.contains(id)) {
- return getResourceServerStoreDelegate().findById(id);
- } else if (managedResourceServers.containsKey(id)) {
- return managedResourceServers.get(id);
- }
- ResourceServerAdapter adapter = new ResourceServerAdapter(cached, StoreFactoryCacheSession.this);
- managedResourceServers.put(id, adapter);
- return adapter;
- }
- }
-
- protected class ScopeCache implements ScopeStore {
- @Override
- public Scope create(String name, ResourceServer resourceServer) {
- return create(null, name, resourceServer);
- }
-
- @Override
- public Scope create(String id, String name, ResourceServer resourceServer) {
- Scope scope = getScopeStoreDelegate().create(id, name, resourceServer);
- registerScopeInvalidation(scope.getId(), scope.getName(), resourceServer.getId());
- return scope;
- }
-
- @Override
- public void delete(String id) {
- if (id == null) return;
- Scope scope = findById(id, null);
- if (scope == null) return;
-
- cache.invalidateObject(id);
- invalidationEvents.add(ScopeRemovedEvent.create(id, scope.getName(), scope.getResourceServer().getId()));
- cache.scopeRemoval(id, scope.getName(), scope.getResourceServer().getId(), invalidations);
- getScopeStoreDelegate().delete(id);
- }
-
- @Override
- public Scope findById(String id, String resourceServerId) {
- if (id == null) return null;
- CachedScope cached = cache.get(id, CachedScope.class);
- if (cached != null) {
- logger.tracev("by id cache hit: {0}", cached.getId());
- }
- if (cached == null) {
- Long loaded = cache.getCurrentRevision(id);
- if (! modelMightExist(id)) return null;
- Scope model = getScopeStoreDelegate().findById(id, resourceServerId);
- if (model == null) {
- setModelDoesNotExists(id, loaded);
- return null;
- }
- if (invalidations.contains(id)) return model;
- cached = new CachedScope(loaded, model);
- cache.addRevisioned(cached, startupRevision);
- } else if (invalidations.contains(id)) {
- return getScopeStoreDelegate().findById(id, resourceServerId);
- } else if (managedScopes.containsKey(id)) {
- return managedScopes.get(id);
- }
- ScopeAdapter adapter = new ScopeAdapter(cached, StoreFactoryCacheSession.this);
- managedScopes.put(id, adapter);
- return adapter;
- }
-
- @Override
- public Scope findByName(String name, String resourceServerId) {
- if (name == null) return null;
- String cacheKey = getScopeByNameCacheKey(name, resourceServerId);
- ScopeListQuery query = cache.get(cacheKey, ScopeListQuery.class);
- if (query != null) {
- logger.tracev("scope by name cache hit: {0}", name);
- }
- if (query == null) {
- Long loaded = cache.getCurrentRevision(cacheKey);
- Scope model = getScopeStoreDelegate().findByName(name, resourceServerId);
- if (model == null) return null;
- if (invalidations.contains(model.getId())) return model;
- query = new ScopeListQuery(loaded, cacheKey, model.getId(), resourceServerId);
- cache.addRevisioned(query, startupRevision);
- return model;
- } else if (invalidations.contains(cacheKey)) {
- return getScopeStoreDelegate().findByName(name, resourceServerId);
- } else {
- String id = query.getScopes().iterator().next();
- if (invalidations.contains(id)) {
- return getScopeStoreDelegate().findByName(name, resourceServerId);
- }
- return findById(id, query.getResourceServerId());
- }
- }
-
- @Override
- public List<Scope> findByResourceServer(String id) {
- return getScopeStoreDelegate().findByResourceServer(id);
- }
-
- @Override
- public List<Scope> findByResourceServer(Map<String, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
- return getScopeStoreDelegate().findByResourceServer(attributes, resourceServerId, firstResult, maxResult);
- }
- }
-
- protected class ResourceCache implements ResourceStore {
- @Override
- public Resource create(String name, ResourceServer resourceServer, String owner) {
- return create(null, name, resourceServer, owner);
- }
-
- @Override
- public Resource create(String id, String name, ResourceServer resourceServer, String owner) {
- Resource resource = getResourceStoreDelegate().create(id, name, resourceServer, owner);
- Resource cached = findById(resource.getId(), resourceServer.getId());
- registerResourceInvalidation(resource.getId(), resource.getName(), resource.getType(), resource.getUris(), resource.getScopes().stream().map(scope -> scope.getId()).collect(Collectors.toSet()), resourceServer.getId(), resource.getOwner());
- if (cached == null) {
- cached = findById(resource.getId(), resourceServer.getId());
- }
- return cached;
- }
-
- @Override
- public void delete(String id) {
- if (id == null) return;
- Resource resource = findById(id, null);
- if (resource == null) return;
-
- cache.invalidateObject(id);
- invalidationEvents.add(ResourceRemovedEvent.create(id, resource.getName(), resource.getType(), resource.getUris(), resource.getOwner(), resource.getScopes().stream().map(scope -> scope.getId()).collect(Collectors.toSet()), resource.getResourceServer().getId()));
- cache.resourceRemoval(id, resource.getName(), resource.getType(), resource.getUris(), resource.getOwner(), resource.getScopes().stream().map(scope -> scope.getId()).collect(Collectors.toSet()), resource.getResourceServer().getId(), invalidations);
- getResourceStoreDelegate().delete(id);
-
- }
-
- @Override
- public Resource findById(String id, String resourceServerId) {
- if (id == null) return null;
- CachedResource cached = cache.get(id, CachedResource.class);
- if (cached != null) {
- logger.tracev("by id cache hit: {0}", cached.getId());
- }
- if (cached == null) {
- Long loaded = cache.getCurrentRevision(id);
- if (! modelMightExist(id)) return null;
- Resource model = getResourceStoreDelegate().findById(id, resourceServerId);
- if (model == null) {
- setModelDoesNotExists(id, loaded);
- return null;
- }
- if (invalidations.contains(id)) return model;
- cached = new CachedResource(loaded, model);
- cache.addRevisioned(cached, startupRevision);
- } else if (invalidations.contains(id)) {
- return getResourceStoreDelegate().findById(id, resourceServerId);
- } else if (managedResources.containsKey(id)) {
- return managedResources.get(id);
- }
- ResourceAdapter adapter = new ResourceAdapter(cached, StoreFactoryCacheSession.this);
- managedResources.put(id, adapter);
- return adapter;
- }
-
- @Override
- public Resource findByName(String name, String resourceServerId) {
- return findByName(name, resourceServerId, resourceServerId);
- }
-
- @Override
- public Resource findByName(String name, String ownerId, String resourceServerId) {
- if (name == null) return null;
- String cacheKey = getResourceByNameCacheKey(name, ownerId, resourceServerId);
- List<Resource> result = cacheQuery(cacheKey, ResourceListQuery.class, () -> {
- Resource resource = getResourceStoreDelegate().findByName(name, ownerId, resourceServerId);
-
- if (resource == null) {
- return Collections.emptyList();
- }
-
- return Arrays.asList(resource);
- },
- (revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
-
- if (result.isEmpty()) {
- return null;
- }
-
- return result.get(0);
- }
-
- @Override
- public List<Resource> findByOwner(String ownerId, String resourceServerId) {
- String cacheKey = getResourceByOwnerCacheKey(ownerId, resourceServerId);
- return cacheQuery(cacheKey, ResourceListQuery.class, () -> getResourceStoreDelegate().findByOwner(ownerId, resourceServerId),
- (revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
- }
-
- @Override
- public void findByOwner(String ownerId, String resourceServerId, Consumer<Resource> consumer) {
- String cacheKey = getResourceByOwnerCacheKey(ownerId, resourceServerId);
- cacheQuery(cacheKey, ResourceListQuery.class, () -> getResourceStoreDelegate().findByOwner(ownerId, resourceServerId),
- (revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, consumer);
- }
-
- @Override
- public List<Resource> findByUri(String uri, String resourceServerId) {
- if (uri == null) return null;
- String cacheKey = getResourceByUriCacheKey(uri, resourceServerId);
- return cacheQuery(cacheKey, ResourceListQuery.class, () -> getResourceStoreDelegate().findByUri(uri, resourceServerId),
- (revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
- }
-
- @Override
- public List<Resource> findByResourceServer(String resourceServerId) {
- return getResourceStoreDelegate().findByResourceServer(resourceServerId);
- }
-
- @Override
- public List<Resource> findByResourceServer(Map<String, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
- return getResourceStoreDelegate().findByResourceServer(attributes, resourceServerId, firstResult, maxResult);
- }
-
- @Override
- public List<Resource> findByScope(List<String> ids, String resourceServerId) {
- if (ids == null) return null;
- List<Resource> result = new ArrayList<>();
-
- for (String id : ids) {
- String cacheKey = getResourceByScopeCacheKey(id, resourceServerId);
- result.addAll(cacheQuery(cacheKey, ResourceScopeListQuery.class, () -> getResourceStoreDelegate().findByScope(Arrays.asList(id), resourceServerId), (revision, resources) -> new ResourceScopeListQuery(revision, cacheKey, id, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId));
- }
-
- return result;
- }
-
- @Override
- public void findByScope(List<String> ids, String resourceServerId, Consumer<Resource> consumer) {
- if (ids == null) return;
-
- for (String id : ids) {
- String cacheKey = getResourceByScopeCacheKey(id, resourceServerId);
- cacheQuery(cacheKey, ResourceScopeListQuery.class, () -> getResourceStoreDelegate().findByScope(Arrays.asList(id), resourceServerId), (revision, resources) -> new ResourceScopeListQuery(revision, cacheKey, id, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, consumer);
- }
- }
-
- @Override
- public List<Resource> findByType(String type, String resourceServerId) {
- if (type == null) return Collections.emptyList();
- String cacheKey = getResourceByTypeCacheKey(type, resourceServerId);
- return cacheQuery(cacheKey, ResourceListQuery.class, () -> getResourceStoreDelegate().findByType(type, resourceServerId),
- (revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
- }
-
- @Override
- public void findByType(String type, String resourceServerId, Consumer<Resource> consumer) {
- if (type == null) return;
- String cacheKey = getResourceByTypeCacheKey(type, resourceServerId);
- cacheQuery(cacheKey, ResourceListQuery.class, () -> getResourceStoreDelegate().findByType(type, resourceServerId),
- (revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, consumer);
- }
-
- private <R extends Resource, Q extends ResourceQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, String resourceServerId) {
- return cacheQuery(cacheKey, queryType, resultSupplier, querySupplier, resourceServerId, null);
- }
-
- private <R extends Resource, Q extends ResourceQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, String resourceServerId, Consumer<R> consumer) {
- Q query = cache.get(cacheKey, queryType);
- if (query != null) {
- logger.tracev("cache hit for key: {0}", cacheKey);
- }
- if (query == null) {
- Long loaded = cache.getCurrentRevision(cacheKey);
- List<R> model = resultSupplier.get();
- if (model == null) return null;
- if (invalidations.contains(cacheKey)) {
- if (consumer != null) {
- for (R policy: model) {
- consumer.accept(policy);
- }
- }
- return model;
- };
- query = querySupplier.apply(loaded, model);
- cache.addRevisioned(query, startupRevision);
- if (consumer != null) {
- for (R resource : model) {
- consumer.andThen(r -> cacheResource(resource)).accept(resource);
- }
- }
- return model;
- } else if (query.isInvalid(invalidations)) {
- List<R> result = resultSupplier.get();
-
- if (consumer != null) {
- for (R resource : result) {
- consumer.accept(resource);
- }
- }
-
- return result;
- } else {
- Set<String> resources = query.getResources();
-
- if (consumer != null) {
- resources.stream().map(resourceId -> (R) findById(resourceId, resourceServerId)).forEach(consumer);
- return Collections.emptyList();
- }
-
- return resources.stream().map(resourceId -> (R) findById(resourceId, resourceServerId)).collect(Collectors.toList());
- }
- }
- }
-
- protected class PolicyCache implements PolicyStore {
- @Override
- public Policy create(AbstractPolicyRepresentation representation, ResourceServer resourceServer) {
- Policy policy = getPolicyStoreDelegate().create(representation, resourceServer);
- Policy cached = findById(policy.getId(), resourceServer.getId());
- registerPolicyInvalidation(policy.getId(), representation.getName(), representation.getResources(), representation.getScopes(), null, resourceServer.getId());
- if (cached == null) {
- cached = findById(policy.getId(), resourceServer.getId());
- }
- return cached;
- }
-
- @Override
- public void delete(String id) {
- if (id == null) return;
- Policy policy = findById(id, null);
- if (policy == null) return;
-
- cache.invalidateObject(id);
- Set<String> resources = policy.getResources().stream().map(resource -> resource.getId()).collect(Collectors.toSet());
- ResourceServer resourceServer = policy.getResourceServer();
- Set<String> resourceTypes = getResourceTypes(resources, resourceServer.getId());
- String defaultResourceType = policy.getConfig().get("defaultResourceType");
- if (Objects.nonNull(defaultResourceType)) {
- resourceTypes.add(defaultResourceType);
- }
- Set<String> scopes = policy.getScopes().stream().map(scope -> scope.getId()).collect(Collectors.toSet());
- invalidationEvents.add(PolicyRemovedEvent.create(id, policy.getName(), resources, resourceTypes, scopes, resourceServer.getId()));
- cache.policyRemoval(id, policy.getName(), resources, resourceTypes, scopes, resourceServer.getId(), invalidations);
- getPolicyStoreDelegate().delete(id);
-
- }
-
- @Override
- public Policy findById(String id, String resourceServerId) {
- if (id == null) return null;
-
- CachedPolicy cached = cache.get(id, CachedPolicy.class);
- if (cached != null) {
- logger.tracev("by id cache hit: {0}", cached.getId());
- }
- if (cached == null) {
- if (! modelMightExist(id)) return null;
- Policy model = getPolicyStoreDelegate().findById(id, resourceServerId);
- Long loaded = cache.getCurrentRevision(id);
- if (model == null) {
- setModelDoesNotExists(id, loaded);
- return null;
- }
- if (invalidations.contains(id)) return model;
- cached = new CachedPolicy(loaded, model);
- cache.addRevisioned(cached, startupRevision);
- } else if (invalidations.contains(id)) {
- return getPolicyStoreDelegate().findById(id, resourceServerId);
- } else if (managedPolicies.containsKey(id)) {
- return managedPolicies.get(id);
- }
- PolicyAdapter adapter = new PolicyAdapter(cached, StoreFactoryCacheSession.this);
- managedPolicies.put(id, adapter);
- return adapter;
- }
-
- @Override
- public Policy findByName(String name, String resourceServerId) {
- if (name == null) return null;
- String cacheKey = getPolicyByNameCacheKey(name, resourceServerId);
- List<Policy> result = cacheQuery(cacheKey, PolicyListQuery.class, () -> {
- Policy policy = getPolicyStoreDelegate().findByName(name, resourceServerId);
-
- if (policy == null) {
- return Collections.emptyList();
- }
-
- return Arrays.asList(policy);
- }, (revision, policies) -> new PolicyListQuery(revision, cacheKey, policies.stream().map(policy -> policy.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, null);
-
- if (result.isEmpty()) {
- return null;
- }
-
- return result.get(0);
- }
-
- @Override
- public List<Policy> findByResourceServer(String resourceServerId) {
- return getPolicyStoreDelegate().findByResourceServer(resourceServerId);
- }
-
- @Override
- public List<Policy> findByResourceServer(Map<String, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
- return getPolicyStoreDelegate().findByResourceServer(attributes, resourceServerId, firstResult, maxResult);
- }
-
- @Override
- public List<Policy> findByResource(String resourceId, String resourceServerId) {
- String cacheKey = getPolicyByResource(resourceId, resourceServerId);
- return cacheQuery(cacheKey, PolicyResourceListQuery.class, () -> getPolicyStoreDelegate().findByResource(resourceId, resourceServerId),
- (revision, policies) -> new PolicyResourceListQuery(revision, cacheKey, resourceId, policies.stream().map(policy -> policy.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, null);
- }
-
- @Override
- public void findByResource(String resourceId, String resourceServerId, Consumer<Policy> consumer) {
- String cacheKey = getPolicyByResource(resourceId, resourceServerId);
- cacheQuery(cacheKey, PolicyResourceListQuery.class, () -> getPolicyStoreDelegate().findByResource(resourceId, resourceServerId),
- (revision, policies) -> new PolicyResourceListQuery(revision, cacheKey, resourceId, policies.stream().map(policy -> policy.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, consumer);
- }
-
- @Override
- public List<Policy> findByResourceType(String resourceType, String resourceServerId) {
- String cacheKey = getPolicyByResourceType(resourceType, resourceServerId);
- return cacheQuery(cacheKey, PolicyResourceListQuery.class, () -> getPolicyStoreDelegate().findByResourceType(resourceType, resourceServerId),
- (revision, policies) -> new PolicyResourceListQuery(revision, cacheKey, resourceType, policies.stream().map(policy -> policy.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, null);
- }
-
- @Override
- public void findByResourceType(String resourceType, String resourceServerId, Consumer<Policy> consumer) {
- String cacheKey = getPolicyByResourceType(resourceType, resourceServerId);
- cacheQuery(cacheKey, PolicyResourceListQuery.class, () -> getPolicyStoreDelegate().findByResourceType(resourceType, resourceServerId),
- (revision, policies) -> new PolicyResourceListQuery(revision, cacheKey, resourceType, policies.stream().map(policy -> policy.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, consumer);
- }
-
- @Override
- public List<Policy> findByScopeIds(List<String> scopeIds, String resourceServerId) {
- if (scopeIds == null) return null;
- Set<Policy> result = new HashSet<>();
-
- for (String id : scopeIds) {
- String cacheKey = getPolicyByScope(id, resourceServerId);
- result.addAll(cacheQuery(cacheKey, PolicyScopeListQuery.class, () -> getPolicyStoreDelegate().findByScopeIds(Arrays.asList(id), resourceServerId), (revision, resources) -> new PolicyScopeListQuery(revision, cacheKey, id, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, null));
- }
-
- return new ArrayList<>(result);
- }
-
- @Override
- public List<Policy> findByScopeIds(List<String> scopeIds, String resourceId, String resourceServerId) {
- if (scopeIds == null) return null;
- Set<Policy> result = new HashSet<>();
-
- for (String id : scopeIds) {
- String cacheKey = getPolicyByResourceScope(id, resourceId, resourceServerId);
- result.addAll(cacheQuery(cacheKey, PolicyScopeListQuery.class, () -> getPolicyStoreDelegate().findByScopeIds(Arrays.asList(id), resourceId, resourceServerId), (revision, resources) -> new PolicyScopeListQuery(revision, cacheKey, id, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, null));
- }
-
- return new ArrayList<>(result);
- }
-
- @Override
- public void findByScopeIds(List<String> scopeIds, String resourceId, String resourceServerId, Consumer<Policy> consumer) {
- for (String id : scopeIds) {
- String cacheKey = getPolicyByResourceScope(id, resourceId, resourceServerId);
- cacheQuery(cacheKey, PolicyScopeListQuery.class, () -> getPolicyStoreDelegate().findByScopeIds(Arrays.asList(id), resourceId, resourceServerId), (revision, resources) -> new PolicyScopeListQuery(revision, cacheKey, id, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, consumer);
- }
- }
-
- @Override
- public List<Policy> findByType(String type, String resourceServerId) {
- return getPolicyStoreDelegate().findByType(type, resourceServerId);
- }
-
- @Override
- public List<Policy> findDependentPolicies(String id, String resourceServerId) {
- return getPolicyStoreDelegate().findDependentPolicies(id, resourceServerId);
- }
-
- private <R extends Policy, Q extends PolicyQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, String resourceServerId, Consumer<R> consumer) {
- Q query = cache.get(cacheKey, queryType);
- if (query != null) {
- logger.tracev("cache hit for key: {0}", cacheKey);
- }
- if (query == null) {
- Long loaded = cache.getCurrentRevision(cacheKey);
- List<R> model = resultSupplier.get();
- if (model == null) return null;
- if (invalidations.contains(cacheKey)) {
- if (consumer != null) {
- for (R policy: model) {
- consumer.accept(policy);
- }
- }
- return model;
- };
- query = querySupplier.apply(loaded, model);
- cache.addRevisioned(query, startupRevision);
- if (consumer != null) {
- for (R policy: model) {
- consumer.andThen(r -> cachePolicy(policy)).accept(policy);
- }
- }
- return model;
- } else if (query.isInvalid(invalidations)) {
- List<R> policies = resultSupplier.get();
-
- if (consumer != null) {
- for (R policy : policies) {
- consumer.accept(policy);
- }
- }
-
- return policies;
- } else {
- Set<String> policies = query.getPolicies();
-
- if (consumer != null) {
- for (String id : policies) {
- consumer.accept((R) findById(id, resourceServerId));
- }
-
- return null;
- }
-
- return policies.stream().map(resourceId -> (R) findById(resourceId, resourceServerId)).collect(Collectors.toList());
- }
- }
- }
-
- protected class PermissionTicketCache implements PermissionTicketStore {
- @Override
- public PermissionTicket create(String resourceId, String scopeId, String requester, ResourceServer resourceServer) {
- PermissionTicket created = getPermissionTicketStoreDelegate().create(resourceId, scopeId, requester, resourceServer);
- registerPermissionTicketInvalidation(created.getId(), created.getOwner(), created.getRequester(), created.getResource().getId(), scopeId, created.getResourceServer().getId());
- return created;
- }
-
- @Override
- public void delete(String id) {
- if (id == null) return;
- PermissionTicket permission = findById(id, null);
- if (permission == null) return;
-
- cache.invalidateObject(id);
- String scopeId = null;
- if (permission.getScope() != null) {
- scopeId = permission.getScope().getId();
- }
- invalidationEvents.add(PermissionTicketRemovedEvent.create(id, permission.getOwner(), permission.getRequester(), permission.getResource().getId(), scopeId, permission.getResourceServer().getId()));
- cache.permissionTicketRemoval(id, permission.getOwner(), permission.getRequester(), permission.getResource().getId(), scopeId, permission.getResourceServer().getId(), invalidations);
- getPermissionTicketStoreDelegate().delete(id);
- UserManagedPermissionUtil.removePolicy(permission, StoreFactoryCacheSession.this);
-
- }
-
- @Override
- public PermissionTicket findById(String id, String resourceServerId) {
- if (id == null) return null;
-
- CachedPermissionTicket cached = cache.get(id, CachedPermissionTicket.class);
- if (cached != null) {
- logger.tracev("by id cache hit: {0}", cached.getId());
- }
- if (cached == null) {
- Long loaded = cache.getCurrentRevision(id);
- if (! modelMightExist(id)) return null;
- PermissionTicket model = getPermissionTicketStoreDelegate().findById(id, resourceServerId);
- if (model == null) {
- setModelDoesNotExists(id, loaded);
- return null;
- }
- if (invalidations.contains(id)) return model;
- cached = new CachedPermissionTicket(loaded, model);
- cache.addRevisioned(cached, startupRevision);
- } else if (invalidations.contains(id)) {
- return getPermissionTicketStoreDelegate().findById(id, resourceServerId);
- } else if (managedPermissionTickets.containsKey(id)) {
- return managedPermissionTickets.get(id);
- }
- PermissionTicketAdapter adapter = new PermissionTicketAdapter(cached, StoreFactoryCacheSession.this);
- managedPermissionTickets.put(id, adapter);
- return adapter;
- }
-
- @Override
- public List<PermissionTicket> findByResourceServer(String resourceServerId) {
- return getPermissionTicketStoreDelegate().findByResourceServer(resourceServerId);
- }
-
- @Override
- public List<PermissionTicket> findByResource(String resourceId, String resourceServerId) {
- String cacheKey = getPermissionTicketByResource(resourceId, resourceServerId);
- return cacheQuery(cacheKey, PermissionTicketResourceListQuery.class, () -> getPermissionTicketStoreDelegate().findByResource(resourceId, resourceServerId),
- (revision, permissions) -> new PermissionTicketResourceListQuery(revision, cacheKey, resourceId, permissions.stream().map(permission -> permission.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
- }
-
- @Override
- public List<PermissionTicket> findByScope(String scopeId, String resourceServerId) {
- String cacheKey = getPermissionTicketByScope(scopeId, resourceServerId);
- return cacheQuery(cacheKey, PermissionTicketScopeListQuery.class, () -> getPermissionTicketStoreDelegate().findByScope(scopeId, resourceServerId),
- (revision, permissions) -> new PermissionTicketScopeListQuery(revision, cacheKey, scopeId, permissions.stream().map(permission -> permission.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
- }
-
- @Override
- public List<PermissionTicket> find(Map<String, String> attributes, String resourceServerId, int firstResult, int maxResult) {
- return getPermissionTicketStoreDelegate().find(attributes, resourceServerId, firstResult, maxResult);
- }
-
- @Override
- public List<PermissionTicket> findGranted(String userId, String resourceServerId) {
- String cacheKey = getPermissionTicketByGranted(userId, resourceServerId);
- return cacheQuery(cacheKey, PermissionTicketListQuery.class, () -> getPermissionTicketStoreDelegate().findGranted(userId, resourceServerId),
- (revision, permissions) -> new PermissionTicketListQuery(revision, cacheKey, permissions.stream().map(permission -> permission.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
- }
-
- @Override
- public List<PermissionTicket> findByOwner(String owner, String resourceServerId) {
- String cacheKey = getPermissionTicketByOwner(owner, resourceServerId);
- return cacheQuery(cacheKey, PermissionTicketListQuery.class, () -> getPermissionTicketStoreDelegate().findByOwner(owner, resourceServerId),
- (revision, permissions) -> new PermissionTicketListQuery(revision, cacheKey, permissions.stream().map(permission -> permission.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
- }
-
- private <R, Q extends PermissionTicketQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, String resourceServerId) {
- Q query = cache.get(cacheKey, queryType);
- if (query != null) {
- logger.tracev("cache hit for key: {0}", cacheKey);
- }
- if (query == null) {
- Long loaded = cache.getCurrentRevision(cacheKey);
- List<R> model = resultSupplier.get();
- if (model == null) return null;
- if (invalidations.contains(cacheKey)) return model;
- query = querySupplier.apply(loaded, model);
- cache.addRevisioned(query, startupRevision);
- return model;
- } else if (query.isInvalid(invalidations)) {
- return resultSupplier.get();
- } else {
- return query.getPermissions().stream().map(resourceId -> (R) findById(resourceId, resourceServerId)).collect(Collectors.toList());
- }
- }
- }
-
- void cachePolicy(Policy model) {
- String id = model.getId();
- if (cache.getCache().containsKey(id)) {
- return;
- }
- if (!modelMightExist(id)) {
- return;
- }
- if (invalidations.contains(id)) return;
- cache.addRevisioned(createCachedPolicy(model, id), startupRevision);
- }
-
- CachedPolicy createCachedPolicy(Policy model, String id) {
- Long loaded = cache.getCurrentRevision(id);
- return new CachedPolicy(loaded, model);
- }
-
- void cacheResource(Resource model) {
- String id = model.getId();
- if (cache.getCache().containsKey(id)) {
- return;
- }
- Long loaded = cache.getCurrentRevision(id);
- if (!modelMightExist(id)) {
- return;
- }
- if (invalidations.contains(id)) return;
- cache.addRevisioned(new CachedResource(loaded, model), startupRevision);
- }
-
- void cacheScope(Scope model) {
- String id = model.getId();
- if (cache.getCache().containsKey(id)) {
- return;
- }
- Long loaded = cache.getCurrentRevision(id);
- if (!modelMightExist(id)) {
- return;
- }
- if (invalidations.contains(id)) return;
- cache.addRevisioned(new CachedScope(loaded, model), startupRevision);
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+// package org.keycloak.models.cache.infinispan.authorization;
+
+// import java.util.ArrayList;
+// import java.util.Arrays;
+// import java.util.Collections;
+// import java.util.HashMap;
+// import java.util.HashSet;
+// import java.util.List;
+// import java.util.Map;
+// import java.util.Objects;
+// import java.util.Set;
+// import java.util.function.BiFunction;
+// import java.util.function.Consumer;
+// import java.util.function.Supplier;
+// import java.util.stream.Collectors;
+
+// import org.jboss.logging.Logger;
+// import org.keycloak.authorization.UserManagedPermissionUtil;
+// import org.keycloak.authorization.model.PermissionTicket;
+// import org.keycloak.authorization.model.Policy;
+// import org.keycloak.authorization.model.Resource;
+// import org.keycloak.authorization.model.ResourceServer;
+// import org.keycloak.authorization.model.Scope;
+// import org.keycloak.authorization.store.PermissionTicketStore;
+// import org.keycloak.authorization.store.PolicyStore;
+// import org.keycloak.authorization.store.ResourceServerStore;
+// import org.keycloak.authorization.store.ResourceStore;
+// import org.keycloak.authorization.store.ScopeStore;
+// import org.keycloak.authorization.store.StoreFactory;
+// import org.keycloak.models.KeycloakSession;
+// import org.keycloak.models.KeycloakTransaction;
+// import org.keycloak.models.ModelException;
+// import org.keycloak.models.cache.authorization.CachedStoreFactoryProvider;
+// // import org.keycloak.models.cache.infinispan.authorization.entities.CachedPermissionTicket;
+// // import org.keycloak.models.cache.infinispan.authorization.entities.CachedPolicy;
+// // import org.keycloak.models.cache.infinispan.authorization.entities.CachedResource;
+// // import org.keycloak.models.cache.infinispan.authorization.entities.CachedResourceServer;
+// // import org.keycloak.models.cache.infinispan.authorization.entities.CachedScope;
+// import org.keycloak.models.cache.infinispan.authorization.entities.PermissionTicketListQuery;
+// import org.keycloak.models.cache.infinispan.authorization.entities.PermissionTicketQuery;
+// import org.keycloak.models.cache.infinispan.authorization.entities.PermissionTicketResourceListQuery;
+// import org.keycloak.models.cache.infinispan.authorization.entities.PermissionTicketScopeListQuery;
+// import org.keycloak.models.cache.infinispan.authorization.entities.PolicyListQuery;
+// import org.keycloak.models.cache.infinispan.authorization.entities.PolicyQuery;
+// import org.keycloak.models.cache.infinispan.authorization.entities.PolicyResourceListQuery;
+// import org.keycloak.models.cache.infinispan.authorization.entities.PolicyScopeListQuery;
+// import org.keycloak.models.cache.infinispan.authorization.entities.ResourceListQuery;
+// import org.keycloak.models.cache.infinispan.authorization.entities.ResourceQuery;
+// import org.keycloak.models.cache.infinispan.authorization.entities.ResourceScopeListQuery;
+// import org.keycloak.models.cache.infinispan.authorization.entities.ScopeListQuery;
+// import org.keycloak.models.cache.infinispan.authorization.events.PermissionTicketRemovedEvent;
+// import org.keycloak.models.cache.infinispan.authorization.events.PermissionTicketUpdatedEvent;
+// import org.keycloak.models.cache.infinispan.authorization.events.PolicyRemovedEvent;
+// import org.keycloak.models.cache.infinispan.authorization.events.PolicyUpdatedEvent;
+// import org.keycloak.models.cache.infinispan.authorization.events.ResourceRemovedEvent;
+// import org.keycloak.models.cache.infinispan.authorization.events.ResourceServerRemovedEvent;
+// import org.keycloak.models.cache.infinispan.authorization.events.ResourceServerUpdatedEvent;
+// import org.keycloak.models.cache.infinispan.authorization.events.ResourceUpdatedEvent;
+// import org.keycloak.models.cache.infinispan.authorization.events.ScopeRemovedEvent;
+// import org.keycloak.models.cache.infinispan.authorization.events.ScopeUpdatedEvent;
+// import org.keycloak.models.cache.infinispan.entities.NonExistentItem;
+// import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
+// import org.keycloak.representations.idm.authorization.AbstractPolicyRepresentation;
+// import org.keycloak.storage.StorageId;
+
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public class StoreFactoryCacheSession implements CachedStoreFactoryProvider {
+// protected static final Logger logger = Logger.getLogger(StoreFactoryCacheSession.class);
+
+// // protected StoreFactoryCacheManager cache;
+// protected boolean transactionActive;
+// protected boolean setRollbackOnly;
+
+// // protected Map<String, ResourceServerAdapter> managedResourceServers = new HashMap<>();
+// // protected Map<String, ScopeAdapter> managedScopes = new HashMap<>();
+// // protected Map<String, ResourceAdapter> managedResources = new HashMap<>();
+// // protected Map<String, PolicyAdapter> managedPolicies = new HashMap<>();
+// // protected Map<String, PermissionTicketAdapter> managedPermissionTickets = new HashMap<>();
+// // protected Set<String> invalidations = new HashSet<>();
+// // protected Set<InvalidationEvent> invalidationEvents = new HashSet<>(); // Events to be sent across cluster
+
+// // protected boolean clearAll;
+// // protected final long startupRevision;
+// // protected StoreFactory delegate;
+// // protected KeycloakSession session;
+// // protected ResourceServerCache resourceServerCache;
+// // protected ScopeCache scopeCache;
+// // protected ResourceCache resourceCache;
+// // protected PolicyCache policyCache;
+// // protected PermissionTicketCache permissionTicketCache;
+
+// public StoreFactoryCacheSession(StoreFactoryCacheManager cache, KeycloakSession session) {
+// // this.cache = cache;
+// // this.startupRevision = cache.getCurrentCounter();
+// // this.session = session;
+// // this.resourceServerCache = new ResourceServerCache();
+// // this.scopeCache = new ScopeCache();
+// // this.resourceCache = new ResourceCache();
+// // this.policyCache = new PolicyCache();
+// // this.permissionTicketCache = new PermissionTicketCache();
+// session.getTransactionManager().enlistPrepare(getPrepareTransaction());
+// session.getTransactionManager().enlistAfterCompletion(getAfterTransaction());
+// }
+
+// @Override
+// public ResourceServerStore getResourceServerStore() {
+// return resourceServerCache;
+// }
+
+// @Override
+// public ScopeStore getScopeStore() {
+// return scopeCache;
+// }
+
+// @Override
+// public ResourceStore getResourceStore() {
+// return resourceCache;
+// }
+
+// @Override
+// public PolicyStore getPolicyStore() {
+// return policyCache;
+// }
+
+// @Override
+// public PermissionTicketStore getPermissionTicketStore() {
+// return permissionTicketCache;
+// }
+
+// @Override
+// public void setReadOnly(boolean readOnly) {
+// getDelegate().setReadOnly(readOnly);
+// }
+
+// @Override
+// public boolean isReadOnly() {
+// return getDelegate().isReadOnly();
+// }
+
+// public void close() {
+// if (delegate != null) {
+// delegate.close();
+// }
+// }
+
+// private KeycloakTransaction getPrepareTransaction() {
+// return new KeycloakTransaction() {
+// @Override
+// public void begin() {
+// transactionActive = true;
+// }
+
+// @Override
+// public void commit() {
+// }
+
+// @Override
+// public void rollback() {
+// setRollbackOnly = true;
+// transactionActive = false;
+// }
+
+// @Override
+// public void setRollbackOnly() {
+// setRollbackOnly = true;
+// }
+
+// @Override
+// public boolean getRollbackOnly() {
+// return setRollbackOnly;
+// }
+
+// @Override
+// public boolean isActive() {
+// return transactionActive;
+// }
+// };
+// }
+
+// private KeycloakTransaction getAfterTransaction() {
+// return new KeycloakTransaction() {
+// @Override
+// public void begin() {
+// transactionActive = true;
+// }
+
+// @Override
+// public void commit() {
+// try {
+// runInvalidations();
+// transactionActive = false;
+// } finally {
+// // cache.endRevisionBatch();
+// }
+// }
+
+// @Override
+// public void rollback() {
+// try {
+// setRollbackOnly = true;
+// runInvalidations();
+// transactionActive = false;
+// } finally {
+// // cache.endRevisionBatch();
+// }
+// }
+
+// @Override
+// public void setRollbackOnly() {
+// setRollbackOnly = true;
+// }
+
+// @Override
+// public boolean getRollbackOnly() {
+// return setRollbackOnly;
+// }
+
+// @Override
+// public boolean isActive() {
+// return transactionActive;
+// }
+// };
+// }
+
+// // protected void runInvalidations() {
+// // for (String id : invalidations) {
+// // cache.invalidateObject(id);
+// // }
+
+// // cache.sendInvalidationEvents(session, invalidationEvents, InfinispanCacheStoreFactoryProviderFactory.AUTHORIZATION_INVALIDATION_EVENTS);
+// // }
+
+
+
+// public long getStartupRevision() {
+// return startupRevision;
+// }
+
+// public boolean isInvalid(String id) {
+// return invalidations.contains(id);
+// }
+
+// // public void registerResourceServerInvalidation(String id) {
+// // cache.resourceServerUpdated(id, invalidations);
+// // ResourceServerAdapter adapter = managedResourceServers.get(id);
+// // if (adapter != null) adapter.invalidateFlag();
+
+// // invalidationEvents.add(ResourceServerUpdatedEvent.create(id));
+// // }
+
+// // public void registerScopeInvalidation(String id, String name, String serverId) {
+// // cache.scopeUpdated(id, name, serverId, invalidations);
+// // ScopeAdapter adapter = managedScopes.get(id);
+// // if (adapter != null) adapter.invalidateFlag();
+
+// // invalidationEvents.add(ScopeUpdatedEvent.create(id, name, serverId));
+// // }
+
+// // public void registerResourceInvalidation(String id, String name, String type, Set<String> uris, Set<String> scopes, String serverId, String owner) {
+// // cache.resourceUpdated(id, name, type, uris, scopes, serverId, owner, invalidations);
+// // ResourceAdapter adapter = managedResources.get(id);
+// // if (adapter != null) adapter.invalidateFlag();
+
+// // invalidationEvents.add(ResourceUpdatedEvent.create(id, name, type, uris, scopes, serverId, owner));
+// // }
+
+// // public void registerPolicyInvalidation(String id, String name, Set<String> resources, Set<String> scopes, String defaultResourceType, String serverId) {
+// // Set<String> resourceTypes = getResourceTypes(resources, serverId);
+// // if (Objects.nonNull(defaultResourceType)) {
+// // resourceTypes.add(defaultResourceType);
+// // }
+// // cache.policyUpdated(id, name, resources, resourceTypes, scopes, serverId, invalidations);
+// // PolicyAdapter adapter = managedPolicies.get(id);
+// // if (adapter != null) adapter.invalidateFlag();
+
+// // invalidationEvents.add(PolicyUpdatedEvent.create(id, name, resources, resourceTypes, scopes, serverId));
+// // }
+
+// // public void registerPermissionTicketInvalidation(String id, String owner, String requester, String resource, String scope, String serverId) {
+// // cache.permissionTicketUpdated(id, owner, requester, resource, scope, serverId, invalidations);
+// // PermissionTicketAdapter adapter = managedPermissionTickets.get(id);
+// // if (adapter != null) adapter.invalidateFlag();
+
+// // invalidationEvents.add(PermissionTicketUpdatedEvent.create(id, owner, requester, resource, scope, serverId));
+// // }
+
+// private Set<String> getResourceTypes(Set<String> resources, String serverId) {
+// if (resources == null) {
+// return Collections.emptySet();
+// }
+
+// return resources.stream().map(resourceId -> {
+// Resource resource = getResourceStore().findById(resourceId, serverId);
+// String type = resource.getType();
+
+// if (type != null) {
+// return type;
+// }
+
+// return null;
+// }).filter(Objects::nonNull).collect(Collectors.toSet());
+// }
+
+// public ResourceServerStore getResourceServerStoreDelegate() {
+// return getDelegate().getResourceServerStore();
+// }
+
+// public ScopeStore getScopeStoreDelegate() {
+// return getDelegate().getScopeStore();
+// }
+
+// public ResourceStore getResourceStoreDelegate() {
+// return getDelegate().getResourceStore();
+// }
+
+// public PolicyStore getPolicyStoreDelegate() {
+// return getDelegate().getPolicyStore();
+// }
+
+// public PermissionTicketStore getPermissionTicketStoreDelegate() {
+// return getDelegate().getPermissionTicketStore();
+// }
+
+// public static String getResourceServerByClientCacheKey(String clientId) {
+// return "resource.server.client.id." + clientId;
+// }
+
+// public static String getScopeByNameCacheKey(String name, String serverId) {
+// return "scope.name." + name + "." + serverId;
+// }
+
+// public static String getResourceByNameCacheKey(String name, String ownerId, String serverId) {
+// return "resource.name." + name + "." + ownerId + "." + serverId;
+// }
+
+// public static String getResourceByOwnerCacheKey(String owner, String serverId) {
+// return "resource.owner." + owner + "." + serverId;
+// }
+
+// public static String getResourceByTypeCacheKey(String type, String serverId) {
+// return "resource.type." + type + "." + serverId;
+// }
+
+// public static String getResourceByUriCacheKey(String uri, String serverId) {
+// return "resource.uri." + uri + "." + serverId;
+// }
+
+// public static String getResourceByScopeCacheKey(String scopeId, String serverId) {
+// return "resource.scope." + scopeId + "." + serverId;
+// }
+
+// public static String getPolicyByNameCacheKey(String name, String serverId) {
+// return "policy.name." + name + "." + serverId;
+// }
+
+// public static String getPolicyByResource(String resourceId, String serverId) {
+// return "policy.resource." + resourceId + "." + serverId;
+// }
+
+// public static String getPolicyByResourceType(String type, String serverId) {
+// return "policy.resource.type." + type + "." + serverId;
+// }
+
+// public static String getPolicyByScope(String scope, String serverId) {
+// return "policy.scope." + scope + "." + serverId;
+// }
+
+// public static String getPolicyByResourceScope(String scope, String resourceId, String serverId) {
+// return "policy.resource. " + resourceId + ".scope." + scope + "." + serverId;
+// }
+
+// public static String getPermissionTicketByResource(String resourceId, String serverId) {
+// return "permission.ticket.resource." + resourceId + "." + serverId;
+// }
+
+// public static String getPermissionTicketByScope(String scopeId, String serverId) {
+// return "permission.ticket.scope." + scopeId + "." + serverId;
+// }
+
+// public static String getPermissionTicketByGranted(String userId, String serverId) {
+// return "permission.ticket.granted." + userId + "." + serverId;
+// }
+
+// public static String getPermissionTicketByOwner(String owner, String serverId) {
+// return "permission.ticket.owner." + owner + "." + serverId;
+// }
+
+// public StoreFactory getDelegate() {
+// if (delegate != null) return delegate;
+// delegate = session.getProvider(StoreFactory.class);
+// return delegate;
+// }
+
+// // private void setModelDoesNotExists(String id, Long loaded) {
+// // if (! invalidations.contains(id)) {
+// // cache.addRevisioned(new NonExistentItem(id, loaded), startupRevision);
+// // }
+// // }
+
+// // boolean modelMightExist(String id) {
+// // return invalidations.contains(id) || cache.get(id, NonExistentItem.class) == null;
+// // }
+
+// protected class ResourceServerCache implements ResourceServerStore {
+// @Override
+// public ResourceServer create(String clientId) {
+// if (!StorageId.isLocalStorage(clientId)) {
+// throw new ModelException("Creating resource server from federated ClientModel not supported");
+// }
+// ResourceServer server = getResourceServerStoreDelegate().create(clientId);
+// registerResourceServerInvalidation(server.getId());
+// return server;
+// }
+
+// @Override
+// public void delete(String id) {
+// if (id == null) return;
+// ResourceServer server = findById(id);
+// if (server == null) return;
+
+// // cache.invalidateObject(id);
+// invalidationEvents.add(ResourceServerRemovedEvent.create(id, server.getId()));
+// // cache.resourceServerRemoval(id, invalidations);
+// getResourceServerStoreDelegate().delete(id);
+
+// }
+
+// @Override
+// public ResourceServer findById(String id) {
+// if (id == null) return null;
+// // CachedResourceServer cached = cache.get(id, CachedResourceServer.class);
+// // if (cached != null) {
+// // logger.tracev("by id cache hit: {0}", cached.getId());
+// // }
+
+// // if (cached == null) {
+// // Long loaded = cache.getCurrentRevision(id);
+// // if (! modelMightExist(id)) return null;
+// ResourceServer model = getResourceServerStoreDelegate().findById(id);
+// if (model == null) {
+// setModelDoesNotExists(id, loaded);
+// return null;
+// }
+// // if (invalidations.contains(id)) return model;
+// // cached = new CachedResourceServer(loaded, model);
+// // cache.addRevisioned(cached, startupRevision);
+// // } else if (invalidations.contains(id)) {
+// // return getResourceServerStoreDelegate().findById(id);
+// // } else if (managedResourceServers.containsKey(id)) {
+// // return managedResourceServers.get(id);
+// // }
+// // ResourceServerAdapter adapter = new ResourceServerAdapter(cached, StoreFactoryCacheSession.this);
+// // managedResourceServers.put(id, adapter);
+// // return adapter;
+// }
+// }
+
+// protected class ScopeCache implements ScopeStore {
+// @Override
+// public Scope create(String name, ResourceServer resourceServer) {
+// return create(null, name, resourceServer);
+// }
+
+// @Override
+// public Scope create(String id, String name, ResourceServer resourceServer) {
+// Scope scope = getScopeStoreDelegate().create(id, name, resourceServer);
+// registerScopeInvalidation(scope.getId(), scope.getName(), resourceServer.getId());
+// return scope;
+// }
+
+// @Override
+// public void delete(String id) {
+// if (id == null) return;
+// Scope scope = findById(id, null);
+// if (scope == null) return;
+
+// // cache.invalidateObject(id);
+// invalidationEvents.add(ScopeRemovedEvent.create(id, scope.getName(), scope.getResourceServer().getId()));
+// // cache.scopeRemoval(id, scope.getName(), scope.getResourceServer().getId(), invalidations);
+// getScopeStoreDelegate().delete(id);
+// }
+
+// @Override
+// public Scope findById(String id, String resourceServerId) {
+// if (id == null) return null;
+// // CachedScope cached = cache.get(id, CachedScope.class);
+// // if (cached != null) {
+// // logger.tracev("by id cache hit: {0}", cached.getId());
+// // }
+// // if (cached == null) {
+// // Long loaded = cache.getCurrentRevision(id);
+// if (! modelMightExist(id)) return null;
+// Scope model = getScopeStoreDelegate().findById(id, resourceServerId);
+// if (model == null) {
+// setModelDoesNotExists(id, loaded);
+// return null;
+// }
+// return model; // ADDED BY MELOCA
+// // if (invalidations.contains(id)) return model;
+// // cached = new CachedScope(loaded, model);
+// // cache.addRevisioned(cached, startupRevision);
+// // } else if (invalidations.contains(id)) {
+// // return getScopeStoreDelegate().findById(id, resourceServerId);
+// // } else if (managedScopes.containsKey(id)) {
+// // return managedScopes.get(id);
+// // }
+// // ScopeAdapter adapter = new ScopeAdapter(cached, StoreFactoryCacheSession.this);
+// // managedScopes.put(id, adapter);
+// // return adapter;
+// }
+
+// @Override
+// public Scope findByName(String name, String resourceServerId) {
+// if (name == null) return null;
+// // String cacheKey = getScopeByNameCacheKey(name, resourceServerId);
+// // ScopeListQuery query = cache.get(cacheKey, ScopeListQuery.class);
+// // if (query != null) {
+// // logger.tracev("scope by name cache hit: {0}", name);
+// // }
+// // if (query == null) {
+// // Long loaded = cache.getCurrentRevision(cacheKey);
+// Scope model = getScopeStoreDelegate().findByName(name, resourceServerId);
+// if (model == null) return null;
+// // if (invalidations.contains(model.getId())) return model;
+// query = new ScopeListQuery(loaded, cacheKey, model.getId(), resourceServerId);
+// // cache.addRevisioned(query, startupRevision);
+// return model;
+// // } else if (invalidations.contains(cacheKey)) {
+// // return getScopeStoreDelegate().findByName(name, resourceServerId);
+// // } else {
+// // String id = query.getScopes().iterator().next();
+// // if (invalidations.contains(id)) {
+// // return getScopeStoreDelegate().findByName(name, resourceServerId);
+// // }
+// // return findById(id, query.getResourceServerId());
+// // }
+// }
+
+// @Override
+// public List<Scope> findByResourceServer(String id) {
+// return getScopeStoreDelegate().findByResourceServer(id);
+// }
+
+// @Override
+// public List<Scope> findByResourceServer(Map<String, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
+// return getScopeStoreDelegate().findByResourceServer(attributes, resourceServerId, firstResult, maxResult);
+// }
+// }
+
+// protected class ResourceCache implements ResourceStore {
+// @Override
+// public Resource create(String name, ResourceServer resourceServer, String owner) {
+// return create(null, name, resourceServer, owner);
+// }
+
+// @Override
+// public Resource create(String id, String name, ResourceServer resourceServer, String owner) {
+// Resource resource = getResourceStoreDelegate().create(id, name, resourceServer, owner);
+// Resource cached = findById(resource.getId(), resourceServer.getId());
+// registerResourceInvalidation(resource.getId(), resource.getName(), resource.getType(), resource.getUris(), resource.getScopes().stream().map(scope -> scope.getId()).collect(Collectors.toSet()), resourceServer.getId(), resource.getOwner());
+// if (cached == null) {
+// cached = findById(resource.getId(), resourceServer.getId());
+// }
+// return cached;
+// }
+
+// @Override
+// public void delete(String id) {
+// if (id == null) return;
+// Resource resource = findById(id, null);
+// if (resource == null) return;
+
+// // cache.invalidateObject(id);
+// invalidationEvents.add(ResourceRemovedEvent.create(id, resource.getName(), resource.getType(), resource.getUris(), resource.getOwner(), resource.getScopes().stream().map(scope -> scope.getId()).collect(Collectors.toSet()), resource.getResourceServer().getId()));
+// // cache.resourceRemoval(id, resource.getName(), resource.getType(), resource.getUris(), resource.getOwner(), resource.getScopes().stream().map(scope -> scope.getId()).collect(Collectors.toSet()), resource.getResourceServer().getId(), invalidations);
+// getResourceStoreDelegate().delete(id);
+
+// }
+
+// @Override
+// public Resource findById(String id, String resourceServerId) {
+// if (id == null) return null;
+// // CachedResource cached = cache.get(id, CachedResource.class);
+// // if (cached != null) {
+// // logger.tracev("by id cache hit: {0}", cached.getId());
+// // }
+// // if (cached == null) {
+// // Long loaded = cache.getCurrentRevision(id);
+// if (! modelMightExist(id)) return null;
+// Resource model = getResourceStoreDelegate().findById(id, resourceServerId);
+// if (model == null) {
+// setModelDoesNotExists(id, loaded);
+// return null;
+// }
+// return model; // ADDED BY MELOCA
+// // if (invalidations.contains(id)) return model;
+// // cached = new CachedResource(loaded, model);
+// // cache.addRevisioned(cached, startupRevision);
+// // } else if (invalidations.contains(id)) {
+// // return getResourceStoreDelegate().findById(id, resourceServerId);
+// // } else if (managedResources.containsKey(id)) {
+// // return managedResources.get(id);
+// // }
+// // ResourceAdapter adapter = new ResourceAdapter(cached, StoreFactoryCacheSession.this);
+// // managedResources.put(id, adapter);
+// // return adapter;
+// }
+
+// @Override
+// public Resource findByName(String name, String resourceServerId) {
+// return findByName(name, resourceServerId, resourceServerId);
+// }
+
+// @Override
+// public Resource findByName(String name, String ownerId, String resourceServerId) {
+// if (name == null) return null;
+// String cacheKey = getResourceByNameCacheKey(name, ownerId, resourceServerId);
+// List<Resource> result = cacheQuery(cacheKey, ResourceListQuery.class, () -> {
+// Resource resource = getResourceStoreDelegate().findByName(name, ownerId, resourceServerId);
+
+// if (resource == null) {
+// return Collections.emptyList();
+// }
+
+// return Arrays.asList(resource);
+// },
+// (revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
+
+// if (result.isEmpty()) {
+// return null;
+// }
+
+// return result.get(0);
+// }
+
+// @Override
+// public List<Resource> findByOwner(String ownerId, String resourceServerId) {
+// String cacheKey = getResourceByOwnerCacheKey(ownerId, resourceServerId);
+// return cacheQuery(cacheKey, ResourceListQuery.class, () -> getResourceStoreDelegate().findByOwner(ownerId, resourceServerId),
+// (revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
+// }
+
+// @Override
+// public void findByOwner(String ownerId, String resourceServerId, Consumer<Resource> consumer) {
+// String cacheKey = getResourceByOwnerCacheKey(ownerId, resourceServerId);
+// cacheQuery(cacheKey, ResourceListQuery.class, () -> getResourceStoreDelegate().findByOwner(ownerId, resourceServerId),
+// (revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, consumer);
+// }
+
+// @Override
+// public List<Resource> findByUri(String uri, String resourceServerId) {
+// if (uri == null) return null;
+// String cacheKey = getResourceByUriCacheKey(uri, resourceServerId);
+// return cacheQuery(cacheKey, ResourceListQuery.class, () -> getResourceStoreDelegate().findByUri(uri, resourceServerId),
+// (revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
+// }
+
+// @Override
+// public List<Resource> findByResourceServer(String resourceServerId) {
+// return getResourceStoreDelegate().findByResourceServer(resourceServerId);
+// }
+
+// @Override
+// public List<Resource> findByResourceServer(Map<String, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
+// return getResourceStoreDelegate().findByResourceServer(attributes, resourceServerId, firstResult, maxResult);
+// }
+
+// @Override
+// public List<Resource> findByScope(List<String> ids, String resourceServerId) {
+// if (ids == null) return null;
+// List<Resource> result = new ArrayList<>();
+
+// for (String id : ids) {
+// String cacheKey = getResourceByScopeCacheKey(id, resourceServerId);
+// result.addAll(cacheQuery(cacheKey, ResourceScopeListQuery.class, () -> getResourceStoreDelegate().findByScope(Arrays.asList(id), resourceServerId), (revision, resources) -> new ResourceScopeListQuery(revision, cacheKey, id, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId));
+// }
+
+// return result;
+// }
+
+// @Override
+// public void findByScope(List<String> ids, String resourceServerId, Consumer<Resource> consumer) {
+// if (ids == null) return;
+
+// for (String id : ids) {
+// String cacheKey = getResourceByScopeCacheKey(id, resourceServerId);
+// cacheQuery(cacheKey, ResourceScopeListQuery.class, () -> getResourceStoreDelegate().findByScope(Arrays.asList(id), resourceServerId), (revision, resources) -> new ResourceScopeListQuery(revision, cacheKey, id, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, consumer);
+// }
+// }
+
+// @Override
+// public List<Resource> findByType(String type, String resourceServerId) {
+// if (type == null) return Collections.emptyList();
+// String cacheKey = getResourceByTypeCacheKey(type, resourceServerId);
+// return cacheQuery(cacheKey, ResourceListQuery.class, () -> getResourceStoreDelegate().findByType(type, resourceServerId),
+// (revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
+// }
+
+// @Override
+// public void findByType(String type, String resourceServerId, Consumer<Resource> consumer) {
+// if (type == null) return;
+// String cacheKey = getResourceByTypeCacheKey(type, resourceServerId);
+// cacheQuery(cacheKey, ResourceListQuery.class, () -> getResourceStoreDelegate().findByType(type, resourceServerId),
+// (revision, resources) -> new ResourceListQuery(revision, cacheKey, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, consumer);
+// }
+
+// // private <R extends Resource, Q extends ResourceQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, String resourceServerId) {
+// // return cacheQuery(cacheKey, queryType, resultSupplier, querySupplier, resourceServerId, null);
+// // }
+
+// private <R extends Resource, Q extends ResourceQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, String resourceServerId, Consumer<R> consumer) {
+// Q query = cache.get(cacheKey, queryType);
+// if (query != null) {
+// logger.tracev("cache hit for key: {0}", cacheKey);
+// }
+// if (query == null) {
+// Long loaded = cache.getCurrentRevision(cacheKey);
+// List<R> model = resultSupplier.get();
+// if (model == null) return null;
+// if (invalidations.contains(cacheKey)) {
+// if (consumer != null) {
+// for (R policy: model) {
+// consumer.accept(policy);
+// }
+// }
+// return model;
+// };
+// query = querySupplier.apply(loaded, model);
+// cache.addRevisioned(query, startupRevision);
+// if (consumer != null) {
+// for (R resource : model) {
+// consumer.andThen(r -> cacheResource(resource)).accept(resource);
+// }
+// }
+// return model;
+// } else if (query.isInvalid(invalidations)) {
+// List<R> result = resultSupplier.get();
+
+// if (consumer != null) {
+// for (R resource : result) {
+// consumer.accept(resource);
+// }
+// }
+
+// return result;
+// } else {
+// Set<String> resources = query.getResources();
+
+// if (consumer != null) {
+// resources.stream().map(resourceId -> (R) findById(resourceId, resourceServerId)).forEach(consumer);
+// return Collections.emptyList();
+// }
+
+// return resources.stream().map(resourceId -> (R) findById(resourceId, resourceServerId)).collect(Collectors.toList());
+// }
+// }
+// }
+
+// protected class PolicyCache implements PolicyStore {
+// @Override
+// public Policy create(AbstractPolicyRepresentation representation, ResourceServer resourceServer) {
+// Policy policy = getPolicyStoreDelegate().create(representation, resourceServer);
+// Policy cached = findById(policy.getId(), resourceServer.getId());
+// registerPolicyInvalidation(policy.getId(), representation.getName(), representation.getResources(), representation.getScopes(), null, resourceServer.getId());
+// if (cached == null) {
+// cached = findById(policy.getId(), resourceServer.getId());
+// }
+// return cached;
+// }
+
+// @Override
+// public void delete(String id) {
+// if (id == null) return;
+// Policy policy = findById(id, null);
+// if (policy == null) return;
+
+// cache.invalidateObject(id);
+// Set<String> resources = policy.getResources().stream().map(resource -> resource.getId()).collect(Collectors.toSet());
+// ResourceServer resourceServer = policy.getResourceServer();
+// Set<String> resourceTypes = getResourceTypes(resources, resourceServer.getId());
+// String defaultResourceType = policy.getConfig().get("defaultResourceType");
+// if (Objects.nonNull(defaultResourceType)) {
+// resourceTypes.add(defaultResourceType);
+// }
+// Set<String> scopes = policy.getScopes().stream().map(scope -> scope.getId()).collect(Collectors.toSet());
+// invalidationEvents.add(PolicyRemovedEvent.create(id, policy.getName(), resources, resourceTypes, scopes, resourceServer.getId()));
+// cache.policyRemoval(id, policy.getName(), resources, resourceTypes, scopes, resourceServer.getId(), invalidations);
+// getPolicyStoreDelegate().delete(id);
+
+// }
+
+// @Override
+// public Policy findById(String id, String resourceServerId) {
+// if (id == null) return null;
+
+// // CachedPolicy cached = cache.get(id, CachedPolicy.class);
+// // if (cached != null) {
+// // logger.tracev("by id cache hit: {0}", cached.getId());
+// // }
+// // if (cached == null) {
+// if (! modelMightExist(id)) return null;
+// Policy model = getPolicyStoreDelegate().findById(id, resourceServerId);
+// Long loaded = cache.getCurrentRevision(id);
+// if (model == null) {
+// setModelDoesNotExists(id, loaded);
+// return null;
+// }
+// // if (invalidations.contains(id)) return model;
+// return model; // ADDED BY MELOCA
+// // cached = new CachedPolicy(loaded, model);
+// // cache.addRevisioned(cached, startupRevision);
+// // } else if (invalidations.contains(id)) {
+// // return getPolicyStoreDelegate().findById(id, resourceServerId);
+// // } else if (managedPolicies.containsKey(id)) {
+// // return managedPolicies.get(id);
+// // }
+// // PolicyAdapter adapter = new PolicyAdapter(cached, StoreFactoryCacheSession.this);
+// // managedPolicies.put(id, adapter);
+// // return adapter;
+// }
+
+// @Override
+// public Policy findByName(String name, String resourceServerId) {
+// if (name == null) return null;
+// String cacheKey = getPolicyByNameCacheKey(name, resourceServerId);
+// List<Policy> result = cacheQuery(cacheKey, PolicyListQuery.class, () -> {
+// Policy policy = getPolicyStoreDelegate().findByName(name, resourceServerId);
+
+// if (policy == null) {
+// return Collections.emptyList();
+// }
+
+// return Arrays.asList(policy);
+// }, (revision, policies) -> new PolicyListQuery(revision, cacheKey, policies.stream().map(policy -> policy.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, null);
+
+// if (result.isEmpty()) {
+// return null;
+// }
+
+// return result.get(0);
+// }
+
+// @Override
+// public List<Policy> findByResourceServer(String resourceServerId) {
+// return getPolicyStoreDelegate().findByResourceServer(resourceServerId);
+// }
+
+// @Override
+// public List<Policy> findByResourceServer(Map<String, String[]> attributes, String resourceServerId, int firstResult, int maxResult) {
+// return getPolicyStoreDelegate().findByResourceServer(attributes, resourceServerId, firstResult, maxResult);
+// }
+
+// @Override
+// public List<Policy> findByResource(String resourceId, String resourceServerId) {
+// String cacheKey = getPolicyByResource(resourceId, resourceServerId);
+// return cacheQuery(cacheKey, PolicyResourceListQuery.class, () -> getPolicyStoreDelegate().findByResource(resourceId, resourceServerId),
+// (revision, policies) -> new PolicyResourceListQuery(revision, cacheKey, resourceId, policies.stream().map(policy -> policy.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, null);
+// }
+
+// @Override
+// public void findByResource(String resourceId, String resourceServerId, Consumer<Policy> consumer) {
+// String cacheKey = getPolicyByResource(resourceId, resourceServerId);
+// cacheQuery(cacheKey, PolicyResourceListQuery.class, () -> getPolicyStoreDelegate().findByResource(resourceId, resourceServerId),
+// (revision, policies) -> new PolicyResourceListQuery(revision, cacheKey, resourceId, policies.stream().map(policy -> policy.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, consumer);
+// }
+
+// @Override
+// public List<Policy> findByResourceType(String resourceType, String resourceServerId) {
+// String cacheKey = getPolicyByResourceType(resourceType, resourceServerId);
+// return cacheQuery(cacheKey, PolicyResourceListQuery.class, () -> getPolicyStoreDelegate().findByResourceType(resourceType, resourceServerId),
+// (revision, policies) -> new PolicyResourceListQuery(revision, cacheKey, resourceType, policies.stream().map(policy -> policy.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, null);
+// }
+
+// @Override
+// public void findByResourceType(String resourceType, String resourceServerId, Consumer<Policy> consumer) {
+// String cacheKey = getPolicyByResourceType(resourceType, resourceServerId);
+// cacheQuery(cacheKey, PolicyResourceListQuery.class, () -> getPolicyStoreDelegate().findByResourceType(resourceType, resourceServerId),
+// (revision, policies) -> new PolicyResourceListQuery(revision, cacheKey, resourceType, policies.stream().map(policy -> policy.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, consumer);
+// }
+
+// @Override
+// public List<Policy> findByScopeIds(List<String> scopeIds, String resourceServerId) {
+// if (scopeIds == null) return null;
+// Set<Policy> result = new HashSet<>();
+
+// for (String id : scopeIds) {
+// String cacheKey = getPolicyByScope(id, resourceServerId);
+// result.addAll(cacheQuery(cacheKey, PolicyScopeListQuery.class, () -> getPolicyStoreDelegate().findByScopeIds(Arrays.asList(id), resourceServerId), (revision, resources) -> new PolicyScopeListQuery(revision, cacheKey, id, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, null));
+// }
+
+// return new ArrayList<>(result);
+// }
+
+// @Override
+// public List<Policy> findByScopeIds(List<String> scopeIds, String resourceId, String resourceServerId) {
+// if (scopeIds == null) return null;
+// Set<Policy> result = new HashSet<>();
+
+// for (String id : scopeIds) {
+// String cacheKey = getPolicyByResourceScope(id, resourceId, resourceServerId);
+// result.addAll(cacheQuery(cacheKey, PolicyScopeListQuery.class, () -> getPolicyStoreDelegate().findByScopeIds(Arrays.asList(id), resourceId, resourceServerId), (revision, resources) -> new PolicyScopeListQuery(revision, cacheKey, id, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, null));
+// }
+
+// return new ArrayList<>(result);
+// }
+
+// @Override
+// public void findByScopeIds(List<String> scopeIds, String resourceId, String resourceServerId, Consumer<Policy> consumer) {
+// for (String id : scopeIds) {
+// String cacheKey = getPolicyByResourceScope(id, resourceId, resourceServerId);
+// cacheQuery(cacheKey, PolicyScopeListQuery.class, () -> getPolicyStoreDelegate().findByScopeIds(Arrays.asList(id), resourceId, resourceServerId), (revision, resources) -> new PolicyScopeListQuery(revision, cacheKey, id, resources.stream().map(resource -> resource.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId, consumer);
+// }
+// }
+
+// @Override
+// public List<Policy> findByType(String type, String resourceServerId) {
+// return getPolicyStoreDelegate().findByType(type, resourceServerId);
+// }
+
+// @Override
+// public List<Policy> findDependentPolicies(String id, String resourceServerId) {
+// return getPolicyStoreDelegate().findDependentPolicies(id, resourceServerId);
+// }
+
+// private <R extends Policy, Q extends PolicyQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, String resourceServerId, Consumer<R> consumer) {
+// Q query = cache.get(cacheKey, queryType);
+// if (query != null) {
+// logger.tracev("cache hit for key: {0}", cacheKey);
+// }
+// if (query == null) {
+// Long loaded = cache.getCurrentRevision(cacheKey);
+// List<R> model = resultSupplier.get();
+// if (model == null) return null;
+// if (invalidations.contains(cacheKey)) {
+// if (consumer != null) {
+// for (R policy: model) {
+// consumer.accept(policy);
+// }
+// }
+// return model;
+// };
+// query = querySupplier.apply(loaded, model);
+// cache.addRevisioned(query, startupRevision);
+// if (consumer != null) {
+// for (R policy: model) {
+// consumer.andThen(r -> cachePolicy(policy)).accept(policy);
+// }
+// }
+// return model;
+// } else if (query.isInvalid(invalidations)) {
+// List<R> policies = resultSupplier.get();
+
+// if (consumer != null) {
+// for (R policy : policies) {
+// consumer.accept(policy);
+// }
+// }
+
+// return policies;
+// } else {
+// Set<String> policies = query.getPolicies();
+
+// if (consumer != null) {
+// for (String id : policies) {
+// consumer.accept((R) findById(id, resourceServerId));
+// }
+
+// return null;
+// }
+
+// return policies.stream().map(resourceId -> (R) findById(resourceId, resourceServerId)).collect(Collectors.toList());
+// }
+// }
+// }
+
+// protected class PermissionTicketCache implements PermissionTicketStore {
+// @Override
+// public PermissionTicket create(String resourceId, String scopeId, String requester, ResourceServer resourceServer) {
+// PermissionTicket created = getPermissionTicketStoreDelegate().create(resourceId, scopeId, requester, resourceServer);
+// registerPermissionTicketInvalidation(created.getId(), created.getOwner(), created.getRequester(), created.getResource().getId(), scopeId, created.getResourceServer().getId());
+// return created;
+// }
+
+// @Override
+// public void delete(String id) {
+// if (id == null) return;
+// PermissionTicket permission = findById(id, null);
+// if (permission == null) return;
+
+// cache.invalidateObject(id);
+// String scopeId = null;
+// if (permission.getScope() != null) {
+// scopeId = permission.getScope().getId();
+// }
+// invalidationEvents.add(PermissionTicketRemovedEvent.create(id, permission.getOwner(), permission.getRequester(), permission.getResource().getId(), scopeId, permission.getResourceServer().getId()));
+// cache.permissionTicketRemoval(id, permission.getOwner(), permission.getRequester(), permission.getResource().getId(), scopeId, permission.getResourceServer().getId(), invalidations);
+// getPermissionTicketStoreDelegate().delete(id);
+// UserManagedPermissionUtil.removePolicy(permission, StoreFactoryCacheSession.this);
+
+// }
+
+// @Override
+// public PermissionTicket findById(String id, String resourceServerId) {
+// if (id == null) return null;
+
+// // CachedPermissionTicket cached = cache.get(id, CachedPermissionTicket.class);
+// // if (cached != null) {
+// // logger.tracev("by id cache hit: {0}", cached.getId());
+// // }
+// // if (cached == null) {
+// Long loaded = cache.getCurrentRevision(id);
+// if (! modelMightExist(id)) return null;
+// PermissionTicket model = getPermissionTicketStoreDelegate().findById(id, resourceServerId);
+// if (model == null) {
+// setModelDoesNotExists(id, loaded);
+// return null;
+// }
+// return model; // ADDED BY MELOCA
+// // if (invalidations.contains(id)) return model;
+// // cached = new CachedPermissionTicket(loaded, model);
+// // cache.addRevisioned(cached, startupRevision);
+// // } else if (invalidations.contains(id)) {
+// // return getPermissionTicketStoreDelegate().findById(id, resourceServerId);
+// // } else if (managedPermissionTickets.containsKey(id)) {
+// // return managedPermissionTickets.get(id);
+// // }
+// // PermissionTicketAdapter adapter = new PermissionTicketAdapter(cached, StoreFactoryCacheSession.this);
+// // managedPermissionTickets.put(id, adapter);
+// // return adapter;
+// }
+
+// @Override
+// public List<PermissionTicket> findByResourceServer(String resourceServerId) {
+// return getPermissionTicketStoreDelegate().findByResourceServer(resourceServerId);
+// }
+
+// @Override
+// public List<PermissionTicket> findByResource(String resourceId, String resourceServerId) {
+// String cacheKey = getPermissionTicketByResource(resourceId, resourceServerId);
+// return cacheQuery(cacheKey, PermissionTicketResourceListQuery.class, () -> getPermissionTicketStoreDelegate().findByResource(resourceId, resourceServerId),
+// (revision, permissions) -> new PermissionTicketResourceListQuery(revision, cacheKey, resourceId, permissions.stream().map(permission -> permission.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
+// }
+
+// @Override
+// public List<PermissionTicket> findByScope(String scopeId, String resourceServerId) {
+// String cacheKey = getPermissionTicketByScope(scopeId, resourceServerId);
+// return cacheQuery(cacheKey, PermissionTicketScopeListQuery.class, () -> getPermissionTicketStoreDelegate().findByScope(scopeId, resourceServerId),
+// (revision, permissions) -> new PermissionTicketScopeListQuery(revision, cacheKey, scopeId, permissions.stream().map(permission -> permission.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
+// }
+
+// @Override
+// public List<PermissionTicket> find(Map<String, String> attributes, String resourceServerId, int firstResult, int maxResult) {
+// return getPermissionTicketStoreDelegate().find(attributes, resourceServerId, firstResult, maxResult);
+// }
+
+// @Override
+// public List<PermissionTicket> findGranted(String userId, String resourceServerId) {
+// String cacheKey = getPermissionTicketByGranted(userId, resourceServerId);
+// return cacheQuery(cacheKey, PermissionTicketListQuery.class, () -> getPermissionTicketStoreDelegate().findGranted(userId, resourceServerId),
+// (revision, permissions) -> new PermissionTicketListQuery(revision, cacheKey, permissions.stream().map(permission -> permission.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
+// }
+
+// @Override
+// public List<PermissionTicket> findByOwner(String owner, String resourceServerId) {
+// String cacheKey = getPermissionTicketByOwner(owner, resourceServerId);
+// return cacheQuery(cacheKey, PermissionTicketListQuery.class, () -> getPermissionTicketStoreDelegate().findByOwner(owner, resourceServerId),
+// (revision, permissions) -> new PermissionTicketListQuery(revision, cacheKey, permissions.stream().map(permission -> permission.getId()).collect(Collectors.toSet()), resourceServerId), resourceServerId);
+// }
+
+// private <R, Q extends PermissionTicketQuery> List<R> cacheQuery(String cacheKey, Class<Q> queryType, Supplier<List<R>> resultSupplier, BiFunction<Long, List<R>, Q> querySupplier, String resourceServerId) {
+// Q query = cache.get(cacheKey, queryType);
+// if (query != null) {
+// logger.tracev("cache hit for key: {0}", cacheKey);
+// }
+// if (query == null) {
+// Long loaded = cache.getCurrentRevision(cacheKey);
+// List<R> model = resultSupplier.get();
+// if (model == null) return null;
+// if (invalidations.contains(cacheKey)) return model;
+// query = querySupplier.apply(loaded, model);
+// cache.addRevisioned(query, startupRevision);
+// return model;
+// } else if (query.isInvalid(invalidations)) {
+// return resultSupplier.get();
+// } else {
+// return query.getPermissions().stream().map(resourceId -> (R) findById(resourceId, resourceServerId)).collect(Collectors.toList());
+// }
+// }
+// }
+
+// // void cachePolicy(Policy model) {
+// // String id = model.getId();
+// // if (cache.getCache().containsKey(id)) {
+// // return;
+// // }
+// // if (!modelMightExist(id)) {
+// // return;
+// // }
+// // if (invalidations.contains(id)) return;
+// // cache.addRevisioned(createCachedPolicy(model, id), startupRevision);
+// // }
+
+// // CachedPolicy createCachedPolicy(Policy model, String id) {
+// // Long loaded = cache.getCurrentRevision(id);
+// // return new CachedPolicy(loaded, model);
+// // }
+
+// // void cacheResource(Resource model) {
+// // String id = model.getId();
+// // if (cache.getCache().containsKey(id)) {
+// // return;
+// // }
+// // Long loaded = cache.getCurrentRevision(id);
+// // if (!modelMightExist(id)) {
+// // return;
+// // }
+// // if (invalidations.contains(id)) return;
+// // cache.addRevisioned(new CachedResource(loaded, model), startupRevision);
+// // }
+
+// // void cacheScope(Scope model) {
+// // String id = model.getId();
+// // if (cache.getCache().containsKey(id)) {
+// // return;
+// // }
+// // Long loaded = cache.getCurrentRevision(id);
+// // if (!modelMightExist(id)) {
+// // return;
+// // }
+// // if (invalidations.contains(id)) return;
+// // cache.addRevisioned(new CachedScope(loaded, model), startupRevision);
+// // }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/CacheManager.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/CacheManager.java
index 92116b4..3ac02b7 100755
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/CacheManager.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/CacheManager.java
@@ -1,225 +1,225 @@
-package org.keycloak.models.cache.infinispan;
-
-import org.infinispan.Cache;
-import org.jboss.logging.Logger;
-import org.keycloak.cluster.ClusterProvider;
-import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
-import org.keycloak.models.KeycloakSession;
-import org.keycloak.models.cache.infinispan.entities.Revisioned;
-
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.TimeUnit;
-import java.util.function.Predicate;
-
-/**
- *
- * Some notes on how this works:
-
- * This implementation manages optimistic locking and version checks itself. The reason is Infinispan just does behave
- * the way we need it to. Not saying Infinispan is bad, just that we have specific caching requirements!
- *
- * This is an invalidation cache implementation and requires to caches:
- * Cache 1 is an Invalidation Cache
- * Cache 2 is a local-only revision number cache.
- *
- *
- * Each node in the cluster maintains its own revision number cache for each entry in the main invalidation cache. This revision
- * cache holds the version counter for each cached entity.
- *
- * Cache listeners do not receive a @CacheEntryInvalidated event if that node does not have an entry for that item. So, consider the following.
-
- 1. Node 1 gets current counter for user. There currently isn't one as this user isn't cached.
- 2. Node 1 reads user from DB
- 3. Node 2 updates user
- 4. Node 2 calls cache.remove(user). This does not result in an invalidation listener event to node 1!
- 5. node 1 checks version counter, checks pass. Stale entry is cached.
-
- The issue is that Node 1 doesn't have an entry for the user, so it never receives an invalidation listener event from Node 2 thus it can't bump the version. So, when node 1 goes to cache the user it is stale as the version number was never bumped.
-
- So how is this issue fixed? here is pseudo code:
-
- 1. Node 1 calls cacheManager.getCurrentRevision() to get the current local version counter of that User
- 2. Node 1 getCurrentRevision() pulls current counter for that user
- 3. Node 1 getCurrentRevision() adds a "invalidation.key.userid" to invalidation cache. Its just a marker. nothing else
- 4. Node 2 update user
- 5. Node 2 does a cache.remove(user) cache.remove(invalidation.key.userid)
- 6. Node 1 receives invalidation event for invalidation.key.userid. Bumps the version counter for that user
- 7. node 1 version check fails, it doesn't cache the user
- *
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public abstract class CacheManager {
-
- protected final Cache<String, Long> revisions;
- protected final Cache<String, Revisioned> cache;
- protected final UpdateCounter counter = new UpdateCounter();
-
- public CacheManager(Cache<String, Revisioned> cache, Cache<String, Long> revisions) {
- this.cache = cache;
- this.revisions = revisions;
- }
-
- protected abstract Logger getLogger();
-
- public Cache<String, Revisioned> getCache() {
- return cache;
- }
-
- public long getCurrentCounter() {
- return counter.current();
- }
-
- public Long getCurrentRevision(String id) {
- Long revision = revisions.get(id);
- if (revision == null) {
- revision = counter.current();
- }
-
- return revision;
- }
-
- public void endRevisionBatch() {
- try {
- revisions.endBatch(true);
- } catch (Exception e) {
- }
-
- }
-
- public <T extends Revisioned> T get(String id, Class<T> type) {
- Revisioned o = (Revisioned)cache.get(id);
- if (o == null) {
- return null;
- }
- Long rev = revisions.get(id);
- if (rev == null) {
- if (getLogger().isTraceEnabled()) {
- getLogger().tracev("get() missing rev {0}", id);
- }
- return null;
- }
- long oRev = o.getRevision() == null ? -1L : o.getRevision().longValue();
- if (rev > oRev) {
- if (getLogger().isTraceEnabled()) {
- getLogger().tracev("get() rev: {0} o.rev: {1}", rev.longValue(), oRev);
- }
- return null;
- }
- return o != null && type.isInstance(o) ? type.cast(o) : null;
- }
-
- public Object invalidateObject(String id) {
- Revisioned removed = (Revisioned)cache.remove(id);
-
- if (getLogger().isTraceEnabled()) {
- getLogger().tracef("Removed key='%s', value='%s' from cache", id, removed);
- }
-
- bumpVersion(id);
- return removed;
- }
-
- protected void bumpVersion(String id) {
- long next = counter.next();
- Object rev = revisions.put(id, next);
- }
-
- public void addRevisioned(Revisioned object, long startupRevision) {
- addRevisioned(object, startupRevision, -1);
- }
-
- public void addRevisioned(Revisioned object, long startupRevision, long lifespan) {
- //startRevisionBatch();
- String id = object.getId();
- try {
- //revisions.getAdvancedCache().lock(id);
- Long rev = revisions.get(id);
- if (rev == null) {
- rev = counter.current();
- revisions.put(id, rev);
- }
- revisions.startBatch();
- if (!revisions.getAdvancedCache().lock(id)) {
- if (getLogger().isTraceEnabled()) {
- getLogger().tracev("Could not obtain version lock: {0}", id);
- }
- return;
- }
- rev = revisions.get(id);
- if (rev == null) {
- return;
- }
- if (rev > startupRevision) { // revision is ahead transaction start. Other transaction updated in the meantime. Don't cache
- if (getLogger().isTraceEnabled()) {
- getLogger().tracev("Skipped cache. Current revision {0}, Transaction start revision {1}", object.getRevision(), startupRevision);
- }
- return;
- }
- if (rev.equals(object.getRevision())) {
- cache.putForExternalRead(id, object);
- return;
- }
- if (rev > object.getRevision()) { // revision is ahead, don't cache
- if (getLogger().isTraceEnabled()) getLogger().tracev("Skipped cache. Object revision {0}, Cache revision {1}", object.getRevision(), rev);
- return;
- }
- // revisions cache has a lower value than the object.revision, so update revision and add it to cache
- revisions.put(id, object.getRevision());
- if (lifespan < 0) cache.putForExternalRead(id, object);
- else cache.putForExternalRead(id, object, lifespan, TimeUnit.MILLISECONDS);
- } finally {
- endRevisionBatch();
- }
-
- }
-
- public void clear() {
- cache.clear();
- revisions.clear();
- }
-
- public void addInvalidations(Predicate<Map.Entry<String, Revisioned>> predicate, Set<String> invalidations) {
- Iterator<Map.Entry<String, Revisioned>> it = getEntryIterator(predicate);
- while (it.hasNext()) {
- invalidations.add(it.next().getKey());
- }
- }
-
- private Iterator<Map.Entry<String, Revisioned>> getEntryIterator(Predicate<Map.Entry<String, Revisioned>> predicate) {
- return cache
- .entrySet()
- .stream()
- .filter(predicate).iterator();
- }
-
-
- public void sendInvalidationEvents(KeycloakSession session, Collection<InvalidationEvent> invalidationEvents, String eventKey) {
- ClusterProvider clusterProvider = session.getProvider(ClusterProvider.class);
-
- // Maybe add InvalidationEvent, which will be collection of all invalidationEvents? That will reduce cluster traffic even more.
- for (InvalidationEvent event : invalidationEvents) {
- clusterProvider.notify(eventKey, event, true, ClusterProvider.DCNotify.ALL_DCS);
- }
- }
-
-
- public void invalidationEventReceived(InvalidationEvent event) {
- Set<String> invalidations = new HashSet<>();
-
- addInvalidationsFromEvent(event, invalidations);
-
- getLogger().debugf("[%s] Invalidating %d cache items after received event %s", cache.getCacheManager().getAddress(), invalidations.size(), event);
-
- for (String invalidation : invalidations) {
- invalidateObject(invalidation);
- }
- }
-
- protected abstract void addInvalidationsFromEvent(InvalidationEvent event, Set<String> invalidations);
-
-}
+// package org.keycloak.models.cache.infinispan;
+
+// import org.infinispan.Cache;
+// import org.jboss.logging.Logger;
+// import org.keycloak.cluster.ClusterProvider;
+// import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
+// import org.keycloak.models.KeycloakSession;
+// import org.keycloak.models.cache.infinispan.entities.Revisioned;
+
+// import java.util.Collection;
+// import java.util.HashSet;
+// import java.util.Iterator;
+// import java.util.Map;
+// import java.util.Set;
+// import java.util.concurrent.TimeUnit;
+// import java.util.function.Predicate;
+
+// /**
+// *
+// * Some notes on how this works:
+
+// * This implementation manages optimistic locking and version checks itself. The reason is Infinispan just does behave
+// * the way we need it to. Not saying Infinispan is bad, just that we have specific caching requirements!
+// *
+// * This is an invalidation cache implementation and requires to caches:
+// * Cache 1 is an Invalidation Cache
+// * Cache 2 is a local-only revision number cache.
+// *
+// *
+// * Each node in the cluster maintains its own revision number cache for each entry in the main invalidation cache. This revision
+// * cache holds the version counter for each cached entity.
+// *
+// * Cache listeners do not receive a @CacheEntryInvalidated event if that node does not have an entry for that item. So, consider the following.
+
+// 1. Node 1 gets current counter for user. There currently isn't one as this user isn't cached.
+// 2. Node 1 reads user from DB
+// 3. Node 2 updates user
+// 4. Node 2 calls cache.remove(user). This does not result in an invalidation listener event to node 1!
+// 5. node 1 checks version counter, checks pass. Stale entry is cached.
+
+// The issue is that Node 1 doesn't have an entry for the user, so it never receives an invalidation listener event from Node 2 thus it can't bump the version. So, when node 1 goes to cache the user it is stale as the version number was never bumped.
+
+// So how is this issue fixed? here is pseudo code:
+
+// 1. Node 1 calls cacheManager.getCurrentRevision() to get the current local version counter of that User
+// 2. Node 1 getCurrentRevision() pulls current counter for that user
+// 3. Node 1 getCurrentRevision() adds a "invalidation.key.userid" to invalidation cache. Its just a marker. nothing else
+// 4. Node 2 update user
+// 5. Node 2 does a cache.remove(user) cache.remove(invalidation.key.userid)
+// 6. Node 1 receives invalidation event for invalidation.key.userid. Bumps the version counter for that user
+// 7. node 1 version check fails, it doesn't cache the user
+// *
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public abstract class CacheManager {
+
+// protected final Cache<String, Long> revisions;
+// protected final Cache<String, Revisioned> cache;
+// protected final UpdateCounter counter = new UpdateCounter();
+
+// public CacheManager(Cache<String, Revisioned> cache, Cache<String, Long> revisions) {
+// this.cache = cache;
+// this.revisions = revisions;
+// }
+
+// protected abstract Logger getLogger();
+
+// public Cache<String, Revisioned> getCache() {
+// return cache;
+// }
+
+// public long getCurrentCounter() {
+// return counter.current();
+// }
+
+// public Long getCurrentRevision(String id) {
+// Long revision = revisions.get(id);
+// if (revision == null) {
+// revision = counter.current();
+// }
+
+// return revision;
+// }
+
+// public void endRevisionBatch() {
+// try {
+// revisions.endBatch(true);
+// } catch (Exception e) {
+// }
+
+// }
+
+// public <T extends Revisioned> T get(String id, Class<T> type) {
+// Revisioned o = (Revisioned)cache.get(id);
+// if (o == null) {
+// return null;
+// }
+// Long rev = revisions.get(id);
+// if (rev == null) {
+// if (getLogger().isTraceEnabled()) {
+// getLogger().tracev("get() missing rev {0}", id);
+// }
+// return null;
+// }
+// long oRev = o.getRevision() == null ? -1L : o.getRevision().longValue();
+// if (rev > oRev) {
+// if (getLogger().isTraceEnabled()) {
+// getLogger().tracev("get() rev: {0} o.rev: {1}", rev.longValue(), oRev);
+// }
+// return null;
+// }
+// return o != null && type.isInstance(o) ? type.cast(o) : null;
+// }
+
+// public Object invalidateObject(String id) {
+// Revisioned removed = (Revisioned)cache.remove(id);
+
+// if (getLogger().isTraceEnabled()) {
+// getLogger().tracef("Removed key='%s', value='%s' from cache", id, removed);
+// }
+
+// bumpVersion(id);
+// return removed;
+// }
+
+// protected void bumpVersion(String id) {
+// long next = counter.next();
+// Object rev = revisions.put(id, next);
+// }
+
+// public void addRevisioned(Revisioned object, long startupRevision) {
+// addRevisioned(object, startupRevision, -1);
+// }
+
+// public void addRevisioned(Revisioned object, long startupRevision, long lifespan) {
+// //startRevisionBatch();
+// String id = object.getId();
+// try {
+// //revisions.getAdvancedCache().lock(id);
+// Long rev = revisions.get(id);
+// if (rev == null) {
+// rev = counter.current();
+// revisions.put(id, rev);
+// }
+// revisions.startBatch();
+// if (!revisions.getAdvancedCache().lock(id)) {
+// if (getLogger().isTraceEnabled()) {
+// getLogger().tracev("Could not obtain version lock: {0}", id);
+// }
+// return;
+// }
+// rev = revisions.get(id);
+// if (rev == null) {
+// return;
+// }
+// if (rev > startupRevision) { // revision is ahead transaction start. Other transaction updated in the meantime. Don't cache
+// if (getLogger().isTraceEnabled()) {
+// getLogger().tracev("Skipped cache. Current revision {0}, Transaction start revision {1}", object.getRevision(), startupRevision);
+// }
+// return;
+// }
+// if (rev.equals(object.getRevision())) {
+// cache.putForExternalRead(id, object);
+// return;
+// }
+// if (rev > object.getRevision()) { // revision is ahead, don't cache
+// if (getLogger().isTraceEnabled()) getLogger().tracev("Skipped cache. Object revision {0}, Cache revision {1}", object.getRevision(), rev);
+// return;
+// }
+// // revisions cache has a lower value than the object.revision, so update revision and add it to cache
+// revisions.put(id, object.getRevision());
+// if (lifespan < 0) cache.putForExternalRead(id, object);
+// else cache.putForExternalRead(id, object, lifespan, TimeUnit.MILLISECONDS);
+// } finally {
+// endRevisionBatch();
+// }
+
+// }
+
+// public void clear() {
+// cache.clear();
+// revisions.clear();
+// }
+
+// public void addInvalidations(Predicate<Map.Entry<String, Revisioned>> predicate, Set<String> invalidations) {
+// Iterator<Map.Entry<String, Revisioned>> it = getEntryIterator(predicate);
+// while (it.hasNext()) {
+// invalidations.add(it.next().getKey());
+// }
+// }
+
+// private Iterator<Map.Entry<String, Revisioned>> getEntryIterator(Predicate<Map.Entry<String, Revisioned>> predicate) {
+// return cache
+// .entrySet()
+// .stream()
+// .filter(predicate).iterator();
+// }
+
+
+// public void sendInvalidationEvents(KeycloakSession session, Collection<InvalidationEvent> invalidationEvents, String eventKey) {
+// ClusterProvider clusterProvider = session.getProvider(ClusterProvider.class);
+
+// // Maybe add InvalidationEvent, which will be collection of all invalidationEvents? That will reduce cluster traffic even more.
+// for (InvalidationEvent event : invalidationEvents) {
+// clusterProvider.notify(eventKey, event, true, ClusterProvider.DCNotify.ALL_DCS);
+// }
+// }
+
+
+// public void invalidationEventReceived(InvalidationEvent event) {
+// Set<String> invalidations = new HashSet<>();
+
+// addInvalidationsFromEvent(event, invalidations);
+
+// getLogger().debugf("[%s] Invalidating %d cache items after received event %s", cache.getCacheManager().getAddress(), invalidations.size(), event);
+
+// for (String invalidation : invalidations) {
+// invalidateObject(invalidation);
+// }
+// }
+
+// protected abstract void addInvalidationsFromEvent(InvalidationEvent event, Set<String> invalidations);
+
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/ClientAdapter.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/ClientAdapter.java
index a406f23..3f5f732 100755
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/ClientAdapter.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/ClientAdapter.java
@@ -1,669 +1,669 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan;
-
-import org.keycloak.models.ClientModel;
-import org.keycloak.models.ClientScopeModel;
-import org.keycloak.models.ProtocolMapperModel;
-import org.keycloak.models.RealmModel;
-import org.keycloak.models.RoleContainerModel;
-import org.keycloak.models.RoleModel;
-import org.keycloak.models.cache.CachedObject;
-import org.keycloak.models.cache.infinispan.entities.CachedClient;
-
-import java.security.MessageDigest;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class ClientAdapter implements ClientModel, CachedObject {
- protected RealmCacheSession cacheSession;
- protected RealmModel cachedRealm;
-
- protected ClientModel updated;
- protected CachedClient cached;
-
- public ClientAdapter(RealmModel cachedRealm, CachedClient cached, RealmCacheSession cacheSession) {
- this.cachedRealm = cachedRealm;
- this.cacheSession = cacheSession;
- this.cached = cached;
- }
-
- private void getDelegateForUpdate() {
- if (updated == null) {
- cacheSession.registerClientInvalidation(cached.getId(), cached.getClientId(), cachedRealm.getId());
- updated = cacheSession.getRealmDelegate().getClientById(cached.getId(), cachedRealm);
- if (updated == null) throw new IllegalStateException("Not found in database");
- }
- }
- protected boolean invalidated;
- public void invalidate() {
- invalidated = true;
- }
-
- protected boolean isUpdated() {
- if (updated != null) return true;
- if (!invalidated) return false;
- updated = cacheSession.getRealmDelegate().getClientById(cached.getId(), cachedRealm);
- if (updated == null) throw new IllegalStateException("Not found in database");
- return true;
- }
-
- @Override
- public long getCacheTimestamp() {
- return cached.getCacheTimestamp();
- }
-
- @Override
- public void updateClient() {
- if (updated != null) updated.updateClient();
- }
-
- @Override
- public String getId() {
- if (isUpdated()) return updated.getId();
- return cached.getId();
- }
-
- public Set<String> getWebOrigins() {
- if (isUpdated()) return updated.getWebOrigins();
- return cached.getWebOrigins();
- }
-
- public void setWebOrigins(Set<String> webOrigins) {
- getDelegateForUpdate();
- updated.setWebOrigins(webOrigins);
- }
-
- @Override
- public void addClientScope(ClientScopeModel clientScope, boolean defaultScope) {
- getDelegateForUpdate();
- updated.addClientScope(clientScope, defaultScope);
- }
-
- @Override
- public void removeClientScope(ClientScopeModel clientScope) {
- getDelegateForUpdate();
- updated.removeClientScope(clientScope);
- }
-
- @Override
- public Map<String, ClientScopeModel> getClientScopes(boolean defaultScope, boolean filterByProtocol) {
- if (isUpdated()) return updated.getClientScopes(defaultScope, filterByProtocol);
- List<String> clientScopeIds = defaultScope ? cached.getDefaultClientScopesIds() : cached.getOptionalClientScopesIds();
-
- // Defaults to openid-connect
- String clientProtocol = getProtocol() == null ? "openid-connect" : getProtocol();
-
- Map<String, ClientScopeModel> clientScopes = new HashMap<>();
- for (String scopeId : clientScopeIds) {
- ClientScopeModel clientScope = cacheSession.getClientScopeById(scopeId, cachedRealm);
- if (clientScope != null) {
- if (!filterByProtocol || clientScope.getProtocol().equals(clientProtocol)) {
- clientScopes.put(clientScope.getName(), clientScope);
- }
- }
- }
- return clientScopes;
- }
-
- public void addWebOrigin(String webOrigin) {
- getDelegateForUpdate();
- updated.addWebOrigin(webOrigin);
- }
-
- public void removeWebOrigin(String webOrigin) {
- getDelegateForUpdate();
- updated.removeWebOrigin(webOrigin);
- }
-
- public Set<String> getRedirectUris() {
- if (isUpdated()) return updated.getRedirectUris();
- return cached.getRedirectUris();
- }
-
- public void setRedirectUris(Set<String> redirectUris) {
- getDelegateForUpdate();
- updated.setRedirectUris(redirectUris);
- }
-
- public void addRedirectUri(String redirectUri) {
- getDelegateForUpdate();
- updated.addRedirectUri(redirectUri);
- }
-
- public void removeRedirectUri(String redirectUri) {
- getDelegateForUpdate();
- updated.removeRedirectUri(redirectUri);
- }
-
- public boolean isEnabled() {
- if (isUpdated()) return updated.isEnabled();
- return cached.isEnabled();
- }
-
- public void setEnabled(boolean enabled) {
- getDelegateForUpdate();
- updated.setEnabled(enabled);
- }
-
- @Override
- public String getClientAuthenticatorType() {
- if (isUpdated()) return updated.getClientAuthenticatorType();
- return cached.getClientAuthenticatorType();
- }
-
- @Override
- public void setClientAuthenticatorType(String clientAuthenticatorType) {
- getDelegateForUpdate();
- updated.setClientAuthenticatorType(clientAuthenticatorType);
- }
-
- public boolean validateSecret(String secret) {
- return MessageDigest.isEqual(secret.getBytes(), getSecret().getBytes());
- }
-
- public String getSecret() {
- if (isUpdated()) return updated.getSecret();
- return cached.getSecret();
- }
-
- public void setSecret(String secret) {
- getDelegateForUpdate();
- updated.setSecret(secret);
- }
- public String getRegistrationToken() {
- if (isUpdated()) return updated.getRegistrationToken();
- return cached.getRegistrationToken();
- }
-
- public void setRegistrationToken(String registrationToken) {
- getDelegateForUpdate();
- updated.setRegistrationToken(registrationToken);
- }
-
- public boolean isPublicClient() {
- if (isUpdated()) return updated.isPublicClient();
- return cached.isPublicClient();
- }
-
- public void setPublicClient(boolean flag) {
- getDelegateForUpdate();
- updated.setPublicClient(flag);
- }
-
- public boolean isFrontchannelLogout() {
- if (isUpdated()) return updated.isPublicClient();
- return cached.isFrontchannelLogout();
- }
-
- public void setFrontchannelLogout(boolean flag) {
- getDelegateForUpdate();
- updated.setFrontchannelLogout(flag);
- }
-
- @Override
- public boolean isFullScopeAllowed() {
- if (isUpdated()) return updated.isFullScopeAllowed();
- return cached.isFullScopeAllowed();
- }
-
- @Override
- public void setFullScopeAllowed(boolean value) {
- getDelegateForUpdate();
- updated.setFullScopeAllowed(value);
-
- }
-
- public Set<RoleModel> getScopeMappings() {
- if (isUpdated()) return updated.getScopeMappings();
- Set<RoleModel> roles = new HashSet<RoleModel>();
- for (String id : cached.getScope()) {
- roles.add(cacheSession.getRoleById(id, getRealm()));
-
- }
- return roles;
- }
-
- public void addScopeMapping(RoleModel role) {
- getDelegateForUpdate();
- updated.addScopeMapping(role);
- }
-
- public void deleteScopeMapping(RoleModel role) {
- getDelegateForUpdate();
- updated.deleteScopeMapping(role);
- }
-
- public Set<RoleModel> getRealmScopeMappings() {
- Set<RoleModel> roleMappings = getScopeMappings();
-
- Set<RoleModel> appRoles = new HashSet<RoleModel>();
- for (RoleModel role : roleMappings) {
- RoleContainerModel container = role.getContainer();
- if (container instanceof RealmModel) {
- if (((RealmModel) container).getId().equals(cachedRealm.getId())) {
- appRoles.add(role);
- }
- }
- }
-
- return appRoles;
- }
-
- public RealmModel getRealm() {
- return cachedRealm;
- }
-
- public int getNotBefore() {
- if (isUpdated()) return updated.getNotBefore();
- return cached.getNotBefore();
- }
-
- public void setNotBefore(int notBefore) {
- getDelegateForUpdate();
- updated.setNotBefore(notBefore);
- }
-
- @Override
- public String getProtocol() {
- if (isUpdated()) return updated.getProtocol();
- return cached.getProtocol();
- }
-
- @Override
- public void setProtocol(String protocol) {
- getDelegateForUpdate();
- updated.setProtocol(protocol);
- }
-
- @Override
- public void setAttribute(String name, String value) {
- getDelegateForUpdate();
- updated.setAttribute(name, value);
-
- }
-
- @Override
- public void removeAttribute(String name) {
- getDelegateForUpdate();
- updated.removeAttribute(name);
-
- }
-
- @Override
- public String getAttribute(String name) {
- if (isUpdated()) return updated.getAttribute(name);
- return cached.getAttributes().get(name);
- }
-
- @Override
- public Map<String, String> getAttributes() {
- if (isUpdated()) return updated.getAttributes();
- Map<String, String> copy = new HashMap<String, String>();
- copy.putAll(cached.getAttributes());
- return copy;
- }
-
- @Override
- public void setAuthenticationFlowBindingOverride(String name, String value) {
- getDelegateForUpdate();
- updated.setAuthenticationFlowBindingOverride(name, value);
-
- }
-
- @Override
- public void removeAuthenticationFlowBindingOverride(String name) {
- getDelegateForUpdate();
- updated.removeAuthenticationFlowBindingOverride(name);
-
- }
-
- @Override
- public String getAuthenticationFlowBindingOverride(String name) {
- if (isUpdated()) return updated.getAuthenticationFlowBindingOverride(name);
- return cached.getAuthFlowBindings().get(name);
- }
-
- @Override
- public Map<String, String> getAuthenticationFlowBindingOverrides() {
- if (isUpdated()) return updated.getAuthenticationFlowBindingOverrides();
- Map<String, String> copy = new HashMap<String, String>();
- copy.putAll(cached.getAuthFlowBindings());
- return copy;
- }
-
- @Override
- public Set<ProtocolMapperModel> getProtocolMappers() {
- if (isUpdated()) return updated.getProtocolMappers();
- return cached.getProtocolMappers();
- }
-
- @Override
- public ProtocolMapperModel addProtocolMapper(ProtocolMapperModel model) {
- getDelegateForUpdate();
- return updated.addProtocolMapper(model);
- }
-
- @Override
- public void removeProtocolMapper(ProtocolMapperModel mapping) {
- getDelegateForUpdate();
- updated.removeProtocolMapper(mapping);
-
- }
-
- @Override
- public void updateProtocolMapper(ProtocolMapperModel mapping) {
- getDelegateForUpdate();
- updated.updateProtocolMapper(mapping);
-
- }
-
- @Override
- public ProtocolMapperModel getProtocolMapperById(String id) {
- for (ProtocolMapperModel mapping : cached.getProtocolMappers()) {
- if (mapping.getId().equals(id)) return mapping;
- }
- return null;
- }
-
- @Override
- public ProtocolMapperModel getProtocolMapperByName(String protocol, String name) {
- for (ProtocolMapperModel mapping : cached.getProtocolMappers()) {
- if (mapping.getProtocol().equals(protocol) && mapping.getName().equals(name)) return mapping;
- }
- return null;
- }
-
- @Override
- public String getClientId() {
- if (isUpdated()) return updated.getClientId();
- return cached.getClientId();
- }
-
- @Override
- public void setClientId(String clientId) {
- getDelegateForUpdate();
- updated.setClientId(clientId);
- }
-
- @Override
- public String getName() {
- if (isUpdated()) return updated.getName();
- return cached.getName();
- }
-
- @Override
- public void setName(String name) {
- getDelegateForUpdate();
- updated.setName(name);
- }
-
- @Override
- public String getDescription() {
- if (isUpdated()) return updated.getDescription();
- return cached.getDescription();
- }
-
- @Override
- public void setDescription(String description) {
- getDelegateForUpdate();
- updated.setDescription(description);
- }
-
- @Override
- public boolean isSurrogateAuthRequired() {
- if (isUpdated()) return updated.isSurrogateAuthRequired();
- return cached.isSurrogateAuthRequired();
- }
-
- @Override
- public void setSurrogateAuthRequired(boolean surrogateAuthRequired) {
- getDelegateForUpdate();
- updated.setSurrogateAuthRequired(surrogateAuthRequired);
- }
-
- @Override
- public String getManagementUrl() {
- if (isUpdated()) return updated.getManagementUrl();
- return cached.getManagementUrl();
- }
-
- @Override
- public void setManagementUrl(String url) {
- getDelegateForUpdate();
- updated.setManagementUrl(url);
- }
-
- @Override
- public String getRootUrl() {
- if (isUpdated()) return updated.getRootUrl();
- return cached.getRootUrl();
- }
-
- @Override
- public void setRootUrl(String url) {
- getDelegateForUpdate();
- updated.setRootUrl(url);
- }
-
- @Override
- public String getBaseUrl() {
- if (isUpdated()) return updated.getBaseUrl();
- return cached.getBaseUrl();
- }
-
- @Override
- public void setBaseUrl(String url) {
- getDelegateForUpdate();
- updated.setBaseUrl(url);
- }
-
- @Override
- public List<String> getDefaultRoles() {
- if (isUpdated()) return updated.getDefaultRoles();
- return cached.getDefaultRoles();
- }
-
- @Override
- public void addDefaultRole(String name) {
- getDelegateForUpdate();
- updated.addDefaultRole(name);
- }
-
- @Override
- public void updateDefaultRoles(String... defaultRoles) {
- getDelegateForUpdate();
- updated.updateDefaultRoles(defaultRoles);
- }
-
- @Override
- public void removeDefaultRoles(String... defaultRoles) {
- getDelegateForUpdate();
- updated.removeDefaultRoles(defaultRoles);
-
- }
-
- @Override
- public boolean isBearerOnly() {
- if (isUpdated()) return updated.isBearerOnly();
- return cached.isBearerOnly();
- }
-
- @Override
- public void setBearerOnly(boolean only) {
- getDelegateForUpdate();
- updated.setBearerOnly(only);
- }
-
- @Override
- public boolean isConsentRequired() {
- if (isUpdated()) return updated.isConsentRequired();
- return cached.isConsentRequired();
- }
-
- @Override
- public void setConsentRequired(boolean consentRequired) {
- getDelegateForUpdate();
- updated.setConsentRequired(consentRequired);
- }
-
- @Override
- public boolean isStandardFlowEnabled() {
- if (isUpdated()) return updated.isStandardFlowEnabled();
- return cached.isStandardFlowEnabled();
- }
-
- @Override
- public void setStandardFlowEnabled(boolean standardFlowEnabled) {
- getDelegateForUpdate();
- updated.setStandardFlowEnabled(standardFlowEnabled);
- }
-
- @Override
- public boolean isImplicitFlowEnabled() {
- if (isUpdated()) return updated.isImplicitFlowEnabled();
- return cached.isImplicitFlowEnabled();
- }
-
- @Override
- public void setImplicitFlowEnabled(boolean implicitFlowEnabled) {
- getDelegateForUpdate();
- updated.setImplicitFlowEnabled(implicitFlowEnabled);
- }
-
- @Override
- public boolean isDirectAccessGrantsEnabled() {
- if (isUpdated()) return updated.isDirectAccessGrantsEnabled();
- return cached.isDirectAccessGrantsEnabled();
- }
-
- @Override
- public void setDirectAccessGrantsEnabled(boolean directAccessGrantsEnabled) {
- getDelegateForUpdate();
- updated.setDirectAccessGrantsEnabled(directAccessGrantsEnabled);
- }
-
- @Override
- public boolean isServiceAccountsEnabled() {
- if (isUpdated()) return updated.isServiceAccountsEnabled();
- return cached.isServiceAccountsEnabled();
- }
-
- @Override
- public void setServiceAccountsEnabled(boolean serviceAccountsEnabled) {
- getDelegateForUpdate();
- updated.setServiceAccountsEnabled(serviceAccountsEnabled);
- }
-
- @Override
- public RoleModel getRole(String name) {
- return cacheSession.getClientRole(getRealm(), this, name);
- }
-
- @Override
- public RoleModel addRole(String name) {
- return cacheSession.addClientRole(getRealm(), this, name);
- }
-
- @Override
- public RoleModel addRole(String id, String name) {
- return cacheSession.addClientRole(getRealm(), this, id, name);
- }
-
- @Override
- public boolean removeRole(RoleModel role) {
- return cacheSession.removeRole(cachedRealm, role);
- }
-
- @Override
- public Set<RoleModel> getRoles() {
- return cacheSession.getClientRoles(cachedRealm, this);
- }
-
- @Override
- public int getNodeReRegistrationTimeout() {
- if (isUpdated()) return updated.getNodeReRegistrationTimeout();
- return cached.getNodeReRegistrationTimeout();
- }
-
- @Override
- public void setNodeReRegistrationTimeout(int timeout) {
- getDelegateForUpdate();
- updated.setNodeReRegistrationTimeout(timeout);
- }
-
- @Override
- public Map<String, Integer> getRegisteredNodes() {
- if (isUpdated()) return updated.getRegisteredNodes();
- return cached.getRegisteredNodes();
- }
-
- @Override
- public void registerNode(String nodeHost, int registrationTime) {
- getDelegateForUpdate();
- updated.registerNode(nodeHost, registrationTime);
- }
-
- @Override
- public void unregisterNode(String nodeHost) {
- getDelegateForUpdate();
- updated.unregisterNode(nodeHost);
- }
-
- @Override
- public boolean hasScope(RoleModel role) {
- if (isUpdated()) return updated.hasScope(role);
- if (cached.isFullScopeAllowed() || cached.getScope().contains(role.getId())) return true;
-
- Set<RoleModel> roles = getScopeMappings();
-
- for (RoleModel mapping : roles) {
- if (mapping.hasRole(role)) return true;
- }
-
- roles = getRoles();
- if (roles.contains(role)) return true;
-
- for (RoleModel mapping : roles) {
- if (mapping.hasRole(role)) return true;
- }
- return false;
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || !(o instanceof ClientModel)) return false;
-
- ClientModel that = (ClientModel) o;
- return that.getId().equals(getId());
- }
-
- @Override
- public int hashCode() {
- return getId().hashCode();
- }
-
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan;
+
+// import org.keycloak.models.ClientModel;
+// import org.keycloak.models.ClientScopeModel;
+// import org.keycloak.models.ProtocolMapperModel;
+// import org.keycloak.models.RealmModel;
+// import org.keycloak.models.RoleContainerModel;
+// import org.keycloak.models.RoleModel;
+// import org.keycloak.models.cache.CachedObject;
+// import org.keycloak.models.cache.infinispan.entities.CachedClient;
+
+// import java.security.MessageDigest;
+// import java.util.HashMap;
+// import java.util.HashSet;
+// import java.util.List;
+// import java.util.Map;
+// import java.util.Set;
+
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public class ClientAdapter implements ClientModel, CachedObject {
+// protected RealmCacheSession cacheSession;
+// protected RealmModel cachedRealm;
+
+// protected ClientModel updated;
+// protected CachedClient cached;
+
+// public ClientAdapter(RealmModel cachedRealm, CachedClient cached, RealmCacheSession cacheSession) {
+// this.cachedRealm = cachedRealm;
+// this.cacheSession = cacheSession;
+// this.cached = cached;
+// }
+
+// private void getDelegateForUpdate() {
+// if (updated == null) {
+// cacheSession.registerClientInvalidation(cached.getId(), cached.getClientId(), cachedRealm.getId());
+// updated = cacheSession.getRealmDelegate().getClientById(cached.getId(), cachedRealm);
+// if (updated == null) throw new IllegalStateException("Not found in database");
+// }
+// }
+// protected boolean invalidated;
+// public void invalidate() {
+// invalidated = true;
+// }
+
+// protected boolean isUpdated() {
+// if (updated != null) return true;
+// if (!invalidated) return false;
+// updated = cacheSession.getRealmDelegate().getClientById(cached.getId(), cachedRealm);
+// if (updated == null) throw new IllegalStateException("Not found in database");
+// return true;
+// }
+
+// @Override
+// public long getCacheTimestamp() {
+// return cached.getCacheTimestamp();
+// }
+
+// @Override
+// public void updateClient() {
+// if (updated != null) updated.updateClient();
+// }
+
+// @Override
+// public String getId() {
+// if (isUpdated()) return updated.getId();
+// return cached.getId();
+// }
+
+// public Set<String> getWebOrigins() {
+// if (isUpdated()) return updated.getWebOrigins();
+// return cached.getWebOrigins();
+// }
+
+// public void setWebOrigins(Set<String> webOrigins) {
+// getDelegateForUpdate();
+// updated.setWebOrigins(webOrigins);
+// }
+
+// @Override
+// public void addClientScope(ClientScopeModel clientScope, boolean defaultScope) {
+// getDelegateForUpdate();
+// updated.addClientScope(clientScope, defaultScope);
+// }
+
+// @Override
+// public void removeClientScope(ClientScopeModel clientScope) {
+// getDelegateForUpdate();
+// updated.removeClientScope(clientScope);
+// }
+
+// @Override
+// public Map<String, ClientScopeModel> getClientScopes(boolean defaultScope, boolean filterByProtocol) {
+// if (isUpdated()) return updated.getClientScopes(defaultScope, filterByProtocol);
+// List<String> clientScopeIds = defaultScope ? cached.getDefaultClientScopesIds() : cached.getOptionalClientScopesIds();
+
+// // Defaults to openid-connect
+// String clientProtocol = getProtocol() == null ? "openid-connect" : getProtocol();
+
+// Map<String, ClientScopeModel> clientScopes = new HashMap<>();
+// for (String scopeId : clientScopeIds) {
+// ClientScopeModel clientScope = cacheSession.getClientScopeById(scopeId, cachedRealm);
+// if (clientScope != null) {
+// if (!filterByProtocol || clientScope.getProtocol().equals(clientProtocol)) {
+// clientScopes.put(clientScope.getName(), clientScope);
+// }
+// }
+// }
+// return clientScopes;
+// }
+
+// public void addWebOrigin(String webOrigin) {
+// getDelegateForUpdate();
+// updated.addWebOrigin(webOrigin);
+// }
+
+// public void removeWebOrigin(String webOrigin) {
+// getDelegateForUpdate();
+// updated.removeWebOrigin(webOrigin);
+// }
+
+// public Set<String> getRedirectUris() {
+// if (isUpdated()) return updated.getRedirectUris();
+// return cached.getRedirectUris();
+// }
+
+// public void setRedirectUris(Set<String> redirectUris) {
+// getDelegateForUpdate();
+// updated.setRedirectUris(redirectUris);
+// }
+
+// public void addRedirectUri(String redirectUri) {
+// getDelegateForUpdate();
+// updated.addRedirectUri(redirectUri);
+// }
+
+// public void removeRedirectUri(String redirectUri) {
+// getDelegateForUpdate();
+// updated.removeRedirectUri(redirectUri);
+// }
+
+// public boolean isEnabled() {
+// if (isUpdated()) return updated.isEnabled();
+// return cached.isEnabled();
+// }
+
+// public void setEnabled(boolean enabled) {
+// getDelegateForUpdate();
+// updated.setEnabled(enabled);
+// }
+
+// @Override
+// public String getClientAuthenticatorType() {
+// if (isUpdated()) return updated.getClientAuthenticatorType();
+// return cached.getClientAuthenticatorType();
+// }
+
+// @Override
+// public void setClientAuthenticatorType(String clientAuthenticatorType) {
+// getDelegateForUpdate();
+// updated.setClientAuthenticatorType(clientAuthenticatorType);
+// }
+
+// public boolean validateSecret(String secret) {
+// return MessageDigest.isEqual(secret.getBytes(), getSecret().getBytes());
+// }
+
+// public String getSecret() {
+// if (isUpdated()) return updated.getSecret();
+// return cached.getSecret();
+// }
+
+// public void setSecret(String secret) {
+// getDelegateForUpdate();
+// updated.setSecret(secret);
+// }
+// public String getRegistrationToken() {
+// if (isUpdated()) return updated.getRegistrationToken();
+// return cached.getRegistrationToken();
+// }
+
+// public void setRegistrationToken(String registrationToken) {
+// getDelegateForUpdate();
+// updated.setRegistrationToken(registrationToken);
+// }
+
+// public boolean isPublicClient() {
+// if (isUpdated()) return updated.isPublicClient();
+// return cached.isPublicClient();
+// }
+
+// public void setPublicClient(boolean flag) {
+// getDelegateForUpdate();
+// updated.setPublicClient(flag);
+// }
+
+// public boolean isFrontchannelLogout() {
+// if (isUpdated()) return updated.isPublicClient();
+// return cached.isFrontchannelLogout();
+// }
+
+// public void setFrontchannelLogout(boolean flag) {
+// getDelegateForUpdate();
+// updated.setFrontchannelLogout(flag);
+// }
+
+// @Override
+// public boolean isFullScopeAllowed() {
+// if (isUpdated()) return updated.isFullScopeAllowed();
+// return cached.isFullScopeAllowed();
+// }
+
+// @Override
+// public void setFullScopeAllowed(boolean value) {
+// getDelegateForUpdate();
+// updated.setFullScopeAllowed(value);
+
+// }
+
+// public Set<RoleModel> getScopeMappings() {
+// if (isUpdated()) return updated.getScopeMappings();
+// Set<RoleModel> roles = new HashSet<RoleModel>();
+// for (String id : cached.getScope()) {
+// roles.add(cacheSession.getRoleById(id, getRealm()));
+
+// }
+// return roles;
+// }
+
+// public void addScopeMapping(RoleModel role) {
+// getDelegateForUpdate();
+// updated.addScopeMapping(role);
+// }
+
+// public void deleteScopeMapping(RoleModel role) {
+// getDelegateForUpdate();
+// updated.deleteScopeMapping(role);
+// }
+
+// public Set<RoleModel> getRealmScopeMappings() {
+// Set<RoleModel> roleMappings = getScopeMappings();
+
+// Set<RoleModel> appRoles = new HashSet<RoleModel>();
+// for (RoleModel role : roleMappings) {
+// RoleContainerModel container = role.getContainer();
+// if (container instanceof RealmModel) {
+// if (((RealmModel) container).getId().equals(cachedRealm.getId())) {
+// appRoles.add(role);
+// }
+// }
+// }
+
+// return appRoles;
+// }
+
+// public RealmModel getRealm() {
+// return cachedRealm;
+// }
+
+// public int getNotBefore() {
+// if (isUpdated()) return updated.getNotBefore();
+// return cached.getNotBefore();
+// }
+
+// public void setNotBefore(int notBefore) {
+// getDelegateForUpdate();
+// updated.setNotBefore(notBefore);
+// }
+
+// @Override
+// public String getProtocol() {
+// if (isUpdated()) return updated.getProtocol();
+// return cached.getProtocol();
+// }
+
+// @Override
+// public void setProtocol(String protocol) {
+// getDelegateForUpdate();
+// updated.setProtocol(protocol);
+// }
+
+// @Override
+// public void setAttribute(String name, String value) {
+// getDelegateForUpdate();
+// updated.setAttribute(name, value);
+
+// }
+
+// @Override
+// public void removeAttribute(String name) {
+// getDelegateForUpdate();
+// updated.removeAttribute(name);
+
+// }
+
+// @Override
+// public String getAttribute(String name) {
+// if (isUpdated()) return updated.getAttribute(name);
+// return cached.getAttributes().get(name);
+// }
+
+// @Override
+// public Map<String, String> getAttributes() {
+// if (isUpdated()) return updated.getAttributes();
+// Map<String, String> copy = new HashMap<String, String>();
+// copy.putAll(cached.getAttributes());
+// return copy;
+// }
+
+// @Override
+// public void setAuthenticationFlowBindingOverride(String name, String value) {
+// getDelegateForUpdate();
+// updated.setAuthenticationFlowBindingOverride(name, value);
+
+// }
+
+// @Override
+// public void removeAuthenticationFlowBindingOverride(String name) {
+// getDelegateForUpdate();
+// updated.removeAuthenticationFlowBindingOverride(name);
+
+// }
+
+// @Override
+// public String getAuthenticationFlowBindingOverride(String name) {
+// if (isUpdated()) return updated.getAuthenticationFlowBindingOverride(name);
+// return cached.getAuthFlowBindings().get(name);
+// }
+
+// @Override
+// public Map<String, String> getAuthenticationFlowBindingOverrides() {
+// if (isUpdated()) return updated.getAuthenticationFlowBindingOverrides();
+// Map<String, String> copy = new HashMap<String, String>();
+// copy.putAll(cached.getAuthFlowBindings());
+// return copy;
+// }
+
+// @Override
+// public Set<ProtocolMapperModel> getProtocolMappers() {
+// if (isUpdated()) return updated.getProtocolMappers();
+// return cached.getProtocolMappers();
+// }
+
+// @Override
+// public ProtocolMapperModel addProtocolMapper(ProtocolMapperModel model) {
+// getDelegateForUpdate();
+// return updated.addProtocolMapper(model);
+// }
+
+// @Override
+// public void removeProtocolMapper(ProtocolMapperModel mapping) {
+// getDelegateForUpdate();
+// updated.removeProtocolMapper(mapping);
+
+// }
+
+// @Override
+// public void updateProtocolMapper(ProtocolMapperModel mapping) {
+// getDelegateForUpdate();
+// updated.updateProtocolMapper(mapping);
+
+// }
+
+// @Override
+// public ProtocolMapperModel getProtocolMapperById(String id) {
+// for (ProtocolMapperModel mapping : cached.getProtocolMappers()) {
+// if (mapping.getId().equals(id)) return mapping;
+// }
+// return null;
+// }
+
+// @Override
+// public ProtocolMapperModel getProtocolMapperByName(String protocol, String name) {
+// for (ProtocolMapperModel mapping : cached.getProtocolMappers()) {
+// if (mapping.getProtocol().equals(protocol) && mapping.getName().equals(name)) return mapping;
+// }
+// return null;
+// }
+
+// @Override
+// public String getClientId() {
+// if (isUpdated()) return updated.getClientId();
+// return cached.getClientId();
+// }
+
+// @Override
+// public void setClientId(String clientId) {
+// getDelegateForUpdate();
+// updated.setClientId(clientId);
+// }
+
+// @Override
+// public String getName() {
+// if (isUpdated()) return updated.getName();
+// return cached.getName();
+// }
+
+// @Override
+// public void setName(String name) {
+// getDelegateForUpdate();
+// updated.setName(name);
+// }
+
+// @Override
+// public String getDescription() {
+// if (isUpdated()) return updated.getDescription();
+// return cached.getDescription();
+// }
+
+// @Override
+// public void setDescription(String description) {
+// getDelegateForUpdate();
+// updated.setDescription(description);
+// }
+
+// @Override
+// public boolean isSurrogateAuthRequired() {
+// if (isUpdated()) return updated.isSurrogateAuthRequired();
+// return cached.isSurrogateAuthRequired();
+// }
+
+// @Override
+// public void setSurrogateAuthRequired(boolean surrogateAuthRequired) {
+// getDelegateForUpdate();
+// updated.setSurrogateAuthRequired(surrogateAuthRequired);
+// }
+
+// @Override
+// public String getManagementUrl() {
+// if (isUpdated()) return updated.getManagementUrl();
+// return cached.getManagementUrl();
+// }
+
+// @Override
+// public void setManagementUrl(String url) {
+// getDelegateForUpdate();
+// updated.setManagementUrl(url);
+// }
+
+// @Override
+// public String getRootUrl() {
+// if (isUpdated()) return updated.getRootUrl();
+// return cached.getRootUrl();
+// }
+
+// @Override
+// public void setRootUrl(String url) {
+// getDelegateForUpdate();
+// updated.setRootUrl(url);
+// }
+
+// @Override
+// public String getBaseUrl() {
+// if (isUpdated()) return updated.getBaseUrl();
+// return cached.getBaseUrl();
+// }
+
+// @Override
+// public void setBaseUrl(String url) {
+// getDelegateForUpdate();
+// updated.setBaseUrl(url);
+// }
+
+// @Override
+// public List<String> getDefaultRoles() {
+// if (isUpdated()) return updated.getDefaultRoles();
+// return cached.getDefaultRoles();
+// }
+
+// @Override
+// public void addDefaultRole(String name) {
+// getDelegateForUpdate();
+// updated.addDefaultRole(name);
+// }
+
+// @Override
+// public void updateDefaultRoles(String... defaultRoles) {
+// getDelegateForUpdate();
+// updated.updateDefaultRoles(defaultRoles);
+// }
+
+// @Override
+// public void removeDefaultRoles(String... defaultRoles) {
+// getDelegateForUpdate();
+// updated.removeDefaultRoles(defaultRoles);
+
+// }
+
+// @Override
+// public boolean isBearerOnly() {
+// if (isUpdated()) return updated.isBearerOnly();
+// return cached.isBearerOnly();
+// }
+
+// @Override
+// public void setBearerOnly(boolean only) {
+// getDelegateForUpdate();
+// updated.setBearerOnly(only);
+// }
+
+// @Override
+// public boolean isConsentRequired() {
+// if (isUpdated()) return updated.isConsentRequired();
+// return cached.isConsentRequired();
+// }
+
+// @Override
+// public void setConsentRequired(boolean consentRequired) {
+// getDelegateForUpdate();
+// updated.setConsentRequired(consentRequired);
+// }
+
+// @Override
+// public boolean isStandardFlowEnabled() {
+// if (isUpdated()) return updated.isStandardFlowEnabled();
+// return cached.isStandardFlowEnabled();
+// }
+
+// @Override
+// public void setStandardFlowEnabled(boolean standardFlowEnabled) {
+// getDelegateForUpdate();
+// updated.setStandardFlowEnabled(standardFlowEnabled);
+// }
+
+// @Override
+// public boolean isImplicitFlowEnabled() {
+// if (isUpdated()) return updated.isImplicitFlowEnabled();
+// return cached.isImplicitFlowEnabled();
+// }
+
+// @Override
+// public void setImplicitFlowEnabled(boolean implicitFlowEnabled) {
+// getDelegateForUpdate();
+// updated.setImplicitFlowEnabled(implicitFlowEnabled);
+// }
+
+// @Override
+// public boolean isDirectAccessGrantsEnabled() {
+// if (isUpdated()) return updated.isDirectAccessGrantsEnabled();
+// return cached.isDirectAccessGrantsEnabled();
+// }
+
+// @Override
+// public void setDirectAccessGrantsEnabled(boolean directAccessGrantsEnabled) {
+// getDelegateForUpdate();
+// updated.setDirectAccessGrantsEnabled(directAccessGrantsEnabled);
+// }
+
+// @Override
+// public boolean isServiceAccountsEnabled() {
+// if (isUpdated()) return updated.isServiceAccountsEnabled();
+// return cached.isServiceAccountsEnabled();
+// }
+
+// @Override
+// public void setServiceAccountsEnabled(boolean serviceAccountsEnabled) {
+// getDelegateForUpdate();
+// updated.setServiceAccountsEnabled(serviceAccountsEnabled);
+// }
+
+// @Override
+// public RoleModel getRole(String name) {
+// return cacheSession.getClientRole(getRealm(), this, name);
+// }
+
+// @Override
+// public RoleModel addRole(String name) {
+// return cacheSession.addClientRole(getRealm(), this, name);
+// }
+
+// @Override
+// public RoleModel addRole(String id, String name) {
+// return cacheSession.addClientRole(getRealm(), this, id, name);
+// }
+
+// @Override
+// public boolean removeRole(RoleModel role) {
+// return cacheSession.removeRole(cachedRealm, role);
+// }
+
+// @Override
+// public Set<RoleModel> getRoles() {
+// return cacheSession.getClientRoles(cachedRealm, this);
+// }
+
+// @Override
+// public int getNodeReRegistrationTimeout() {
+// if (isUpdated()) return updated.getNodeReRegistrationTimeout();
+// return cached.getNodeReRegistrationTimeout();
+// }
+
+// @Override
+// public void setNodeReRegistrationTimeout(int timeout) {
+// getDelegateForUpdate();
+// updated.setNodeReRegistrationTimeout(timeout);
+// }
+
+// @Override
+// public Map<String, Integer> getRegisteredNodes() {
+// if (isUpdated()) return updated.getRegisteredNodes();
+// return cached.getRegisteredNodes();
+// }
+
+// @Override
+// public void registerNode(String nodeHost, int registrationTime) {
+// getDelegateForUpdate();
+// updated.registerNode(nodeHost, registrationTime);
+// }
+
+// @Override
+// public void unregisterNode(String nodeHost) {
+// getDelegateForUpdate();
+// updated.unregisterNode(nodeHost);
+// }
+
+// @Override
+// public boolean hasScope(RoleModel role) {
+// if (isUpdated()) return updated.hasScope(role);
+// if (cached.isFullScopeAllowed() || cached.getScope().contains(role.getId())) return true;
+
+// Set<RoleModel> roles = getScopeMappings();
+
+// for (RoleModel mapping : roles) {
+// if (mapping.hasRole(role)) return true;
+// }
+
+// roles = getRoles();
+// if (roles.contains(role)) return true;
+
+// for (RoleModel mapping : roles) {
+// if (mapping.hasRole(role)) return true;
+// }
+// return false;
+// }
+
+// @Override
+// public boolean equals(Object o) {
+// if (this == o) return true;
+// if (o == null || !(o instanceof ClientModel)) return false;
+
+// ClientModel that = (ClientModel) o;
+// return that.getId().equals(getId());
+// }
+
+// @Override
+// public int hashCode() {
+// return getId().hashCode();
+// }
+
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/ClientScopeAdapter.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/ClientScopeAdapter.java
index a15cbb6..7051fd8 100755
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/ClientScopeAdapter.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/ClientScopeAdapter.java
@@ -1,253 +1,253 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan;
-
-import org.keycloak.models.ClientModel;
-import org.keycloak.models.ClientScopeModel;
-import org.keycloak.models.ProtocolMapperModel;
-import org.keycloak.models.RealmModel;
-import org.keycloak.models.RoleContainerModel;
-import org.keycloak.models.RoleModel;
-import org.keycloak.models.cache.infinispan.entities.CachedClientScope;
-
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class ClientScopeAdapter implements ClientScopeModel {
- protected RealmCacheSession cacheSession;
- protected RealmModel cachedRealm;
-
- protected ClientScopeModel updated;
- protected CachedClientScope cached;
-
- public ClientScopeAdapter(RealmModel cachedRealm, CachedClientScope cached, RealmCacheSession cacheSession) {
- this.cachedRealm = cachedRealm;
- this.cacheSession = cacheSession;
- this.cached = cached;
- }
-
- private void getDelegateForUpdate() {
- if (updated == null) {
- cacheSession.registerClientScopeInvalidation(cached.getId());
- updated = cacheSession.getRealmDelegate().getClientScopeById(cached.getId(), cachedRealm);
- if (updated == null) throw new IllegalStateException("Not found in database");
- }
- }
-
- protected boolean invalidated;
- public void invalidate() {
- invalidated = true;
- }
-
- protected boolean isUpdated() {
- if (updated != null) return true;
- if (!invalidated) return false;
- updated = cacheSession.getRealmDelegate().getClientScopeById(cached.getId(), cachedRealm);
- if (updated == null) throw new IllegalStateException("Not found in database");
- return true;
- }
-
-
- @Override
- public String getId() {
- if (isUpdated()) return updated.getId();
- return cached.getId();
- }
-
- public RealmModel getRealm() {
- return cachedRealm;
- }
-
- @Override
- public Set<ProtocolMapperModel> getProtocolMappers() {
- if (isUpdated()) return updated.getProtocolMappers();
- return cached.getProtocolMappers();
- }
-
- @Override
- public ProtocolMapperModel addProtocolMapper(ProtocolMapperModel model) {
- getDelegateForUpdate();
- return updated.addProtocolMapper(model);
- }
-
- @Override
- public void removeProtocolMapper(ProtocolMapperModel mapping) {
- getDelegateForUpdate();
- updated.removeProtocolMapper(mapping);
-
- }
-
- @Override
- public void updateProtocolMapper(ProtocolMapperModel mapping) {
- getDelegateForUpdate();
- updated.updateProtocolMapper(mapping);
-
- }
-
- @Override
- public ProtocolMapperModel getProtocolMapperById(String id) {
- for (ProtocolMapperModel mapping : cached.getProtocolMappers()) {
- if (mapping.getId().equals(id)) return mapping;
- }
- return null;
- }
-
- @Override
- public ProtocolMapperModel getProtocolMapperByName(String protocol, String name) {
- for (ProtocolMapperModel mapping : cached.getProtocolMappers()) {
- if (mapping.getProtocol().equals(protocol) && mapping.getName().equals(name)) return mapping;
- }
- return null;
- }
-
- @Override
- public String getName() {
- if (isUpdated()) return updated.getName();
- return cached.getName();
- }
-
- @Override
- public void setName(String name) {
- getDelegateForUpdate();
- updated.setName(name);
- }
-
- @Override
- public String getDescription() {
- if (isUpdated()) return updated.getDescription();
- return cached.getDescription();
- }
-
- @Override
- public void setDescription(String description) {
- getDelegateForUpdate();
- updated.setDescription(description);
- }
-
- @Override
- public String getProtocol() {
- if (isUpdated()) return updated.getProtocol();
- return cached.getProtocol();
- }
-
- @Override
- public void setProtocol(String protocol) {
- getDelegateForUpdate();
- updated.setProtocol(protocol);
- }
-
- public Set<RoleModel> getScopeMappings() {
- if (isUpdated()) return updated.getScopeMappings();
- Set<RoleModel> roles = new HashSet<RoleModel>();
- for (String id : cached.getScope()) {
- roles.add(cacheSession.getRoleById(id, getRealm()));
-
- }
- return roles;
- }
-
- public void addScopeMapping(RoleModel role) {
- getDelegateForUpdate();
- updated.addScopeMapping(role);
- }
-
- public void deleteScopeMapping(RoleModel role) {
- getDelegateForUpdate();
- updated.deleteScopeMapping(role);
- }
-
- public Set<RoleModel> getRealmScopeMappings() {
- Set<RoleModel> roleMappings = getScopeMappings();
-
- Set<RoleModel> appRoles = new HashSet<RoleModel>();
- for (RoleModel role : roleMappings) {
- RoleContainerModel container = role.getContainer();
- if (container instanceof RealmModel) {
- if (((RealmModel) container).getId().equals(cachedRealm.getId())) {
- appRoles.add(role);
- }
- }
- }
-
- return appRoles;
- }
-
- @Override
- public boolean hasScope(RoleModel role) {
- if (isUpdated()) return updated.hasScope(role);
- if (cached.getScope().contains(role.getId())) return true;
-
- Set<RoleModel> roles = getScopeMappings();
-
- for (RoleModel mapping : roles) {
- if (mapping.hasRole(role)) return true;
- }
- return false;
- }
-
-
- @Override
- public void setAttribute(String name, String value) {
- getDelegateForUpdate();
- updated.setAttribute(name, value);
-
- }
-
- @Override
- public void removeAttribute(String name) {
- getDelegateForUpdate();
- updated.removeAttribute(name);
-
- }
-
- @Override
- public String getAttribute(String name) {
- if (isUpdated()) return updated.getAttribute(name);
- return cached.getAttributes().get(name);
- }
-
- @Override
- public Map<String, String> getAttributes() {
- if (isUpdated()) return updated.getAttributes();
- Map<String, String> copy = new HashMap<String, String>();
- copy.putAll(cached.getAttributes());
- return copy;
- }
-
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || !(o instanceof ClientModel)) return false;
-
- ClientScopeModel that = (ClientScopeModel) o;
- return that.getId().equals(getId());
- }
-
- @Override
- public int hashCode() {
- return getId().hashCode();
- }
-
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan;
+
+// import org.keycloak.models.ClientModel;
+// import org.keycloak.models.ClientScopeModel;
+// import org.keycloak.models.ProtocolMapperModel;
+// import org.keycloak.models.RealmModel;
+// import org.keycloak.models.RoleContainerModel;
+// import org.keycloak.models.RoleModel;
+// import org.keycloak.models.cache.infinispan.entities.CachedClientScope;
+
+// import java.util.HashMap;
+// import java.util.HashSet;
+// import java.util.Map;
+// import java.util.Set;
+
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public class ClientScopeAdapter implements ClientScopeModel {
+// protected RealmCacheSession cacheSession;
+// protected RealmModel cachedRealm;
+
+// protected ClientScopeModel updated;
+// protected CachedClientScope cached;
+
+// public ClientScopeAdapter(RealmModel cachedRealm, CachedClientScope cached, RealmCacheSession cacheSession) {
+// this.cachedRealm = cachedRealm;
+// this.cacheSession = cacheSession;
+// this.cached = cached;
+// }
+
+// private void getDelegateForUpdate() {
+// if (updated == null) {
+// cacheSession.registerClientScopeInvalidation(cached.getId());
+// updated = cacheSession.getRealmDelegate().getClientScopeById(cached.getId(), cachedRealm);
+// if (updated == null) throw new IllegalStateException("Not found in database");
+// }
+// }
+
+// protected boolean invalidated;
+// public void invalidate() {
+// invalidated = true;
+// }
+
+// protected boolean isUpdated() {
+// if (updated != null) return true;
+// if (!invalidated) return false;
+// updated = cacheSession.getRealmDelegate().getClientScopeById(cached.getId(), cachedRealm);
+// if (updated == null) throw new IllegalStateException("Not found in database");
+// return true;
+// }
+
+
+// @Override
+// public String getId() {
+// if (isUpdated()) return updated.getId();
+// return cached.getId();
+// }
+
+// public RealmModel getRealm() {
+// return cachedRealm;
+// }
+
+// @Override
+// public Set<ProtocolMapperModel> getProtocolMappers() {
+// if (isUpdated()) return updated.getProtocolMappers();
+// return cached.getProtocolMappers();
+// }
+
+// @Override
+// public ProtocolMapperModel addProtocolMapper(ProtocolMapperModel model) {
+// getDelegateForUpdate();
+// return updated.addProtocolMapper(model);
+// }
+
+// @Override
+// public void removeProtocolMapper(ProtocolMapperModel mapping) {
+// getDelegateForUpdate();
+// updated.removeProtocolMapper(mapping);
+
+// }
+
+// @Override
+// public void updateProtocolMapper(ProtocolMapperModel mapping) {
+// getDelegateForUpdate();
+// updated.updateProtocolMapper(mapping);
+
+// }
+
+// @Override
+// public ProtocolMapperModel getProtocolMapperById(String id) {
+// for (ProtocolMapperModel mapping : cached.getProtocolMappers()) {
+// if (mapping.getId().equals(id)) return mapping;
+// }
+// return null;
+// }
+
+// @Override
+// public ProtocolMapperModel getProtocolMapperByName(String protocol, String name) {
+// for (ProtocolMapperModel mapping : cached.getProtocolMappers()) {
+// if (mapping.getProtocol().equals(protocol) && mapping.getName().equals(name)) return mapping;
+// }
+// return null;
+// }
+
+// @Override
+// public String getName() {
+// if (isUpdated()) return updated.getName();
+// return cached.getName();
+// }
+
+// @Override
+// public void setName(String name) {
+// getDelegateForUpdate();
+// updated.setName(name);
+// }
+
+// @Override
+// public String getDescription() {
+// if (isUpdated()) return updated.getDescription();
+// return cached.getDescription();
+// }
+
+// @Override
+// public void setDescription(String description) {
+// getDelegateForUpdate();
+// updated.setDescription(description);
+// }
+
+// @Override
+// public String getProtocol() {
+// if (isUpdated()) return updated.getProtocol();
+// return cached.getProtocol();
+// }
+
+// @Override
+// public void setProtocol(String protocol) {
+// getDelegateForUpdate();
+// updated.setProtocol(protocol);
+// }
+
+// public Set<RoleModel> getScopeMappings() {
+// if (isUpdated()) return updated.getScopeMappings();
+// Set<RoleModel> roles = new HashSet<RoleModel>();
+// for (String id : cached.getScope()) {
+// roles.add(cacheSession.getRoleById(id, getRealm()));
+
+// }
+// return roles;
+// }
+
+// public void addScopeMapping(RoleModel role) {
+// getDelegateForUpdate();
+// updated.addScopeMapping(role);
+// }
+
+// public void deleteScopeMapping(RoleModel role) {
+// getDelegateForUpdate();
+// updated.deleteScopeMapping(role);
+// }
+
+// public Set<RoleModel> getRealmScopeMappings() {
+// Set<RoleModel> roleMappings = getScopeMappings();
+
+// Set<RoleModel> appRoles = new HashSet<RoleModel>();
+// for (RoleModel role : roleMappings) {
+// RoleContainerModel container = role.getContainer();
+// if (container instanceof RealmModel) {
+// if (((RealmModel) container).getId().equals(cachedRealm.getId())) {
+// appRoles.add(role);
+// }
+// }
+// }
+
+// return appRoles;
+// }
+
+// @Override
+// public boolean hasScope(RoleModel role) {
+// if (isUpdated()) return updated.hasScope(role);
+// if (cached.getScope().contains(role.getId())) return true;
+
+// Set<RoleModel> roles = getScopeMappings();
+
+// for (RoleModel mapping : roles) {
+// if (mapping.hasRole(role)) return true;
+// }
+// return false;
+// }
+
+
+// @Override
+// public void setAttribute(String name, String value) {
+// getDelegateForUpdate();
+// updated.setAttribute(name, value);
+
+// }
+
+// @Override
+// public void removeAttribute(String name) {
+// getDelegateForUpdate();
+// updated.removeAttribute(name);
+
+// }
+
+// @Override
+// public String getAttribute(String name) {
+// if (isUpdated()) return updated.getAttribute(name);
+// return cached.getAttributes().get(name);
+// }
+
+// @Override
+// public Map<String, String> getAttributes() {
+// if (isUpdated()) return updated.getAttributes();
+// Map<String, String> copy = new HashMap<String, String>();
+// copy.putAll(cached.getAttributes());
+// return copy;
+// }
+
+
+// @Override
+// public boolean equals(Object o) {
+// if (this == o) return true;
+// if (o == null || !(o instanceof ClientModel)) return false;
+
+// ClientScopeModel that = (ClientScopeModel) o;
+// return that.getId().equals(getId());
+// }
+
+// @Override
+// public int hashCode() {
+// return getId().hashCode();
+// }
+
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/AbstractRevisioned.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/AbstractRevisioned.java
index 8c88df7..bedd1c7 100755
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/AbstractRevisioned.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/AbstractRevisioned.java
@@ -1,7 +1,7 @@
package org.keycloak.models.cache.infinispan.entities;
import org.keycloak.common.util.Time;
-import org.keycloak.models.cache.CachedObject;
+// import org.keycloak.models.cache.CachedObject;
import java.io.Serializable;
@@ -9,10 +9,12 @@ import java.io.Serializable;
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
-public class AbstractRevisioned implements Revisioned, Serializable, CachedObject {
+public class AbstractRevisioned implements Revisioned, Serializable
+// , CachedObject {
+{
private String id;
private Long revision;
- private final long cacheTimestamp = Time.currentTimeMillis();
+ // private final long cacheTimestamp = Time.currentTimeMillis();
public AbstractRevisioned(Long revision, String id) {
this.revision = revision;
@@ -39,8 +41,8 @@ public class AbstractRevisioned implements Revisioned, Serializable, CachedObjec
*
* @return
*/
- @Override
- public long getCacheTimestamp() {
- return cacheTimestamp;
- }
+ // @Override
+ // public long getCacheTimestamp() {
+ // return cacheTimestamp;
+ // }
}
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/CachedClient.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/CachedClient.java
index f6f288b..8bde120 100755
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/CachedClient.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/entities/CachedClient.java
@@ -1,259 +1,259 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.entities;
-
-import org.keycloak.models.ClientModel;
-import org.keycloak.models.ClientScopeModel;
-import org.keycloak.models.ProtocolMapperModel;
-import org.keycloak.models.RealmModel;
-import org.keycloak.models.RoleModel;
-
-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.TreeMap;
-
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class CachedClient extends AbstractRevisioned implements InRealm {
- protected String clientId;
- protected String name;
- protected String description;
- protected String realm;
- protected Set<String> redirectUris = new HashSet<String>();
- protected boolean enabled;
- protected String clientAuthenticatorType;
- protected String secret;
- protected String registrationToken;
- protected String protocol;
- protected Map<String, String> attributes = new HashMap<String, String>();
- protected Map<String, String> authFlowBindings = new HashMap<String, String>();
- protected boolean publicClient;
- protected boolean fullScopeAllowed;
- protected boolean frontchannelLogout;
- protected int notBefore;
- protected Set<String> scope = new HashSet<String>();
- protected Set<String> webOrigins = new HashSet<String>();
- protected Set<ProtocolMapperModel> protocolMappers = new HashSet<ProtocolMapperModel>();
- protected boolean surrogateAuthRequired;
- protected String managementUrl;
- protected String rootUrl;
- protected String baseUrl;
- protected List<String> defaultRoles = new LinkedList<String>();
- protected boolean bearerOnly;
- protected boolean consentRequired;
- protected boolean standardFlowEnabled;
- protected boolean implicitFlowEnabled;
- protected boolean directAccessGrantsEnabled;
- protected boolean serviceAccountsEnabled;
- protected int nodeReRegistrationTimeout;
- protected Map<String, Integer> registeredNodes;
- protected List<String> defaultClientScopesIds;
- protected List<String> optionalClientScopesIds;
-
- public CachedClient(Long revision, RealmModel realm, ClientModel model) {
- super(revision, model.getId());
- clientAuthenticatorType = model.getClientAuthenticatorType();
- secret = model.getSecret();
- registrationToken = model.getRegistrationToken();
- clientId = model.getClientId();
- name = model.getName();
- description = model.getDescription();
- this.realm = realm.getId();
- enabled = model.isEnabled();
- protocol = model.getProtocol();
- attributes.putAll(model.getAttributes());
- authFlowBindings.putAll(model.getAuthenticationFlowBindingOverrides());
- notBefore = model.getNotBefore();
- frontchannelLogout = model.isFrontchannelLogout();
- publicClient = model.isPublicClient();
- fullScopeAllowed = model.isFullScopeAllowed();
- redirectUris.addAll(model.getRedirectUris());
- webOrigins.addAll(model.getWebOrigins());
- for (RoleModel role : model.getScopeMappings()) {
- scope.add(role.getId());
- }
- for (ProtocolMapperModel mapper : model.getProtocolMappers()) {
- this.protocolMappers.add(mapper);
- }
- surrogateAuthRequired = model.isSurrogateAuthRequired();
- managementUrl = model.getManagementUrl();
- rootUrl = model.getRootUrl();
- baseUrl = model.getBaseUrl();
- defaultRoles.addAll(model.getDefaultRoles());
- bearerOnly = model.isBearerOnly();
- consentRequired = model.isConsentRequired();
- standardFlowEnabled = model.isStandardFlowEnabled();
- implicitFlowEnabled = model.isImplicitFlowEnabled();
- directAccessGrantsEnabled = model.isDirectAccessGrantsEnabled();
- serviceAccountsEnabled = model.isServiceAccountsEnabled();
-
- nodeReRegistrationTimeout = model.getNodeReRegistrationTimeout();
- registeredNodes = new TreeMap<>(model.getRegisteredNodes());
-
- defaultClientScopesIds = new LinkedList<>();
- for (ClientScopeModel clientScope : model.getClientScopes(true, false).values()) {
- defaultClientScopesIds.add(clientScope.getId());
- }
- optionalClientScopesIds = new LinkedList<>();
- for (ClientScopeModel clientScope : model.getClientScopes(false, false).values()) {
- optionalClientScopesIds.add(clientScope.getId());
- }
- }
-
- public String getClientId() {
- return clientId;
- }
-
- public String getName() {
- return name;
- }
-
- public String getDescription() { return description; }
-
- public void setDescription(String description) { this.description = description; }
-
- public String getRealm() {
- return realm;
- }
-
- public Set<String> getRedirectUris() {
- return redirectUris;
- }
-
- public boolean isEnabled() {
- return enabled;
- }
-
- public String getClientAuthenticatorType() {
- return clientAuthenticatorType;
- }
-
- public String getSecret() {
- return secret;
- }
-
- public String getRegistrationToken() {
- return registrationToken;
- }
-
- public boolean isPublicClient() {
- return publicClient;
- }
-
- public int getNotBefore() {
- return notBefore;
- }
-
- public Set<String> getScope() {
- return scope;
- }
-
- public Set<String> getWebOrigins() {
- return webOrigins;
- }
-
- public boolean isFullScopeAllowed() {
- return fullScopeAllowed;
- }
-
- public String getProtocol() {
- return protocol;
- }
-
- public Map<String, String> getAttributes() {
- return attributes;
- }
-
- public boolean isFrontchannelLogout() {
- return frontchannelLogout;
- }
-
- public Set<ProtocolMapperModel> getProtocolMappers() {
- return protocolMappers;
- }
-
- public boolean isSurrogateAuthRequired() {
- return surrogateAuthRequired;
- }
-
- public String getManagementUrl() {
- return managementUrl;
- }
-
- public String getRootUrl() {
- return rootUrl;
- }
-
- public String getBaseUrl() {
- return baseUrl;
- }
-
- public List<String> getDefaultRoles() {
- return defaultRoles;
- }
-
- public boolean isBearerOnly() {
- return bearerOnly;
- }
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.entities;
+
+// import org.keycloak.models.ClientModel;
+// import org.keycloak.models.ClientScopeModel;
+// import org.keycloak.models.ProtocolMapperModel;
+// import org.keycloak.models.RealmModel;
+// import org.keycloak.models.RoleModel;
+
+// 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.TreeMap;
+
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public class CachedClient extends AbstractRevisioned implements InRealm {
+// protected String clientId;
+// protected String name;
+// protected String description;
+// protected String realm;
+// protected Set<String> redirectUris = new HashSet<String>();
+// protected boolean enabled;
+// protected String clientAuthenticatorType;
+// protected String secret;
+// protected String registrationToken;
+// protected String protocol;
+// protected Map<String, String> attributes = new HashMap<String, String>();
+// protected Map<String, String> authFlowBindings = new HashMap<String, String>();
+// protected boolean publicClient;
+// protected boolean fullScopeAllowed;
+// protected boolean frontchannelLogout;
+// protected int notBefore;
+// protected Set<String> scope = new HashSet<String>();
+// protected Set<String> webOrigins = new HashSet<String>();
+// protected Set<ProtocolMapperModel> protocolMappers = new HashSet<ProtocolMapperModel>();
+// protected boolean surrogateAuthRequired;
+// protected String managementUrl;
+// protected String rootUrl;
+// protected String baseUrl;
+// protected List<String> defaultRoles = new LinkedList<String>();
+// protected boolean bearerOnly;
+// protected boolean consentRequired;
+// protected boolean standardFlowEnabled;
+// protected boolean implicitFlowEnabled;
+// protected boolean directAccessGrantsEnabled;
+// protected boolean serviceAccountsEnabled;
+// protected int nodeReRegistrationTimeout;
+// protected Map<String, Integer> registeredNodes;
+// protected List<String> defaultClientScopesIds;
+// protected List<String> optionalClientScopesIds;
+
+// public CachedClient(Long revision, RealmModel realm, ClientModel model) {
+// super(revision, model.getId());
+// clientAuthenticatorType = model.getClientAuthenticatorType();
+// secret = model.getSecret();
+// registrationToken = model.getRegistrationToken();
+// clientId = model.getClientId();
+// name = model.getName();
+// description = model.getDescription();
+// this.realm = realm.getId();
+// enabled = model.isEnabled();
+// protocol = model.getProtocol();
+// attributes.putAll(model.getAttributes());
+// authFlowBindings.putAll(model.getAuthenticationFlowBindingOverrides());
+// notBefore = model.getNotBefore();
+// frontchannelLogout = model.isFrontchannelLogout();
+// publicClient = model.isPublicClient();
+// fullScopeAllowed = model.isFullScopeAllowed();
+// redirectUris.addAll(model.getRedirectUris());
+// webOrigins.addAll(model.getWebOrigins());
+// for (RoleModel role : model.getScopeMappings()) {
+// scope.add(role.getId());
+// }
+// for (ProtocolMapperModel mapper : model.getProtocolMappers()) {
+// this.protocolMappers.add(mapper);
+// }
+// surrogateAuthRequired = model.isSurrogateAuthRequired();
+// managementUrl = model.getManagementUrl();
+// rootUrl = model.getRootUrl();
+// baseUrl = model.getBaseUrl();
+// defaultRoles.addAll(model.getDefaultRoles());
+// bearerOnly = model.isBearerOnly();
+// consentRequired = model.isConsentRequired();
+// standardFlowEnabled = model.isStandardFlowEnabled();
+// implicitFlowEnabled = model.isImplicitFlowEnabled();
+// directAccessGrantsEnabled = model.isDirectAccessGrantsEnabled();
+// serviceAccountsEnabled = model.isServiceAccountsEnabled();
+
+// nodeReRegistrationTimeout = model.getNodeReRegistrationTimeout();
+// registeredNodes = new TreeMap<>(model.getRegisteredNodes());
+
+// defaultClientScopesIds = new LinkedList<>();
+// for (ClientScopeModel clientScope : model.getClientScopes(true, false).values()) {
+// defaultClientScopesIds.add(clientScope.getId());
+// }
+// optionalClientScopesIds = new LinkedList<>();
+// for (ClientScopeModel clientScope : model.getClientScopes(false, false).values()) {
+// optionalClientScopesIds.add(clientScope.getId());
+// }
+// }
+
+// public String getClientId() {
+// return clientId;
+// }
+
+// public String getName() {
+// return name;
+// }
+
+// public String getDescription() { return description; }
+
+// public void setDescription(String description) { this.description = description; }
+
+// public String getRealm() {
+// return realm;
+// }
+
+// public Set<String> getRedirectUris() {
+// return redirectUris;
+// }
+
+// public boolean isEnabled() {
+// return enabled;
+// }
+
+// public String getClientAuthenticatorType() {
+// return clientAuthenticatorType;
+// }
+
+// public String getSecret() {
+// return secret;
+// }
+
+// public String getRegistrationToken() {
+// return registrationToken;
+// }
+
+// public boolean isPublicClient() {
+// return publicClient;
+// }
+
+// public int getNotBefore() {
+// return notBefore;
+// }
+
+// public Set<String> getScope() {
+// return scope;
+// }
+
+// public Set<String> getWebOrigins() {
+// return webOrigins;
+// }
+
+// public boolean isFullScopeAllowed() {
+// return fullScopeAllowed;
+// }
+
+// public String getProtocol() {
+// return protocol;
+// }
+
+// public Map<String, String> getAttributes() {
+// return attributes;
+// }
+
+// public boolean isFrontchannelLogout() {
+// return frontchannelLogout;
+// }
+
+// public Set<ProtocolMapperModel> getProtocolMappers() {
+// return protocolMappers;
+// }
+
+// public boolean isSurrogateAuthRequired() {
+// return surrogateAuthRequired;
+// }
+
+// public String getManagementUrl() {
+// return managementUrl;
+// }
+
+// public String getRootUrl() {
+// return rootUrl;
+// }
+
+// public String getBaseUrl() {
+// return baseUrl;
+// }
+
+// public List<String> getDefaultRoles() {
+// return defaultRoles;
+// }
+
+// public boolean isBearerOnly() {
+// return bearerOnly;
+// }
- public boolean isConsentRequired() {
- return consentRequired;
- }
+// public boolean isConsentRequired() {
+// return consentRequired;
+// }
- public boolean isStandardFlowEnabled() {
- return standardFlowEnabled;
- }
+// public boolean isStandardFlowEnabled() {
+// return standardFlowEnabled;
+// }
- public boolean isImplicitFlowEnabled() {
- return implicitFlowEnabled;
- }
+// public boolean isImplicitFlowEnabled() {
+// return implicitFlowEnabled;
+// }
- public boolean isDirectAccessGrantsEnabled() {
- return directAccessGrantsEnabled;
- }
+// public boolean isDirectAccessGrantsEnabled() {
+// return directAccessGrantsEnabled;
+// }
- public boolean isServiceAccountsEnabled() {
- return serviceAccountsEnabled;
- }
+// public boolean isServiceAccountsEnabled() {
+// return serviceAccountsEnabled;
+// }
- public int getNodeReRegistrationTimeout() {
- return nodeReRegistrationTimeout;
- }
+// public int getNodeReRegistrationTimeout() {
+// return nodeReRegistrationTimeout;
+// }
- public Map<String, Integer> getRegisteredNodes() {
- return registeredNodes;
- }
+// public Map<String, Integer> getRegisteredNodes() {
+// return registeredNodes;
+// }
- public List<String> getDefaultClientScopesIds() {
- return defaultClientScopesIds;
- }
+// public List<String> getDefaultClientScopesIds() {
+// return defaultClientScopesIds;
+// }
- public List<String> getOptionalClientScopesIds() {
- return optionalClientScopesIds;
- }
+// public List<String> getOptionalClientScopesIds() {
+// return optionalClientScopesIds;
+// }
- public Map<String, String> getAuthFlowBindings() {
- return authFlowBindings;
- }
-}
+// public Map<String, String> getAuthFlowBindings() {
+// return authFlowBindings;
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/ClientAddedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/ClientAddedEvent.java
index ae264b0..311cbd8 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/ClientAddedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/ClientAddedEvent.java
@@ -1,95 +1,95 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.events;
-
-import java.util.Set;
-
-import org.keycloak.models.cache.infinispan.RealmCacheManager;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(ClientAddedEvent.ExternalizerImpl.class)
-public class ClientAddedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
-
- private String clientUuid;
- private String clientId;
- private String realmId;
-
- public static ClientAddedEvent create(String clientUuid, String clientId, String realmId) {
- ClientAddedEvent event = new ClientAddedEvent();
- event.clientUuid = clientUuid;
- event.clientId = clientId;
- event.realmId = realmId;
- return event;
- }
-
- @Override
- public String getId() {
- return clientUuid;
- }
-
- @Override
- public String toString() {
- return String.format("ClientAddedEvent [ realmId=%s, clientUuid=%s, clientId=%s ]", realmId, clientUuid, clientId);
- }
-
- @Override
- public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
- realmCache.clientAdded(realmId, clientUuid, clientId, invalidations);
- }
-
- public static class ExternalizerImpl implements Externalizer<ClientAddedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, ClientAddedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.clientUuid, output);
- MarshallUtil.marshallString(obj.clientId, output);
- MarshallUtil.marshallString(obj.realmId, output);
- }
-
- @Override
- public ClientAddedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public ClientAddedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- ClientAddedEvent res = new ClientAddedEvent();
- res.clientUuid = MarshallUtil.unmarshallString(input);
- res.clientId = MarshallUtil.unmarshallString(input);
- res.realmId = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.events;
+
+// import java.util.Set;
+
+// import org.keycloak.models.cache.infinispan.RealmCacheManager;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(ClientAddedEvent.ExternalizerImpl.class)
+// public class ClientAddedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
+
+// private String clientUuid;
+// private String clientId;
+// private String realmId;
+
+// public static ClientAddedEvent create(String clientUuid, String clientId, String realmId) {
+// ClientAddedEvent event = new ClientAddedEvent();
+// event.clientUuid = clientUuid;
+// event.clientId = clientId;
+// event.realmId = realmId;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return clientUuid;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("ClientAddedEvent [ realmId=%s, clientUuid=%s, clientId=%s ]", realmId, clientUuid, clientId);
+// }
+
+// @Override
+// public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
+// realmCache.clientAdded(realmId, clientUuid, clientId, invalidations);
+// }
+
+// public static class ExternalizerImpl implements Externalizer<ClientAddedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, ClientAddedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.clientUuid, output);
+// MarshallUtil.marshallString(obj.clientId, output);
+// MarshallUtil.marshallString(obj.realmId, output);
+// }
+
+// @Override
+// public ClientAddedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public ClientAddedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// ClientAddedEvent res = new ClientAddedEvent();
+// res.clientUuid = MarshallUtil.unmarshallString(input);
+// res.clientId = MarshallUtil.unmarshallString(input);
+// res.realmId = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/ClientRemovedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/ClientRemovedEvent.java
index 2d48693..b0207fd 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/ClientRemovedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/ClientRemovedEvent.java
@@ -1,119 +1,119 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.events;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import org.keycloak.models.ClientModel;
-import org.keycloak.models.RoleModel;
-import org.keycloak.models.cache.infinispan.RealmCacheManager;
-import org.keycloak.models.sessions.infinispan.util.KeycloakMarshallUtil;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import java.util.concurrent.ConcurrentHashMap;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(ClientRemovedEvent.ExternalizerImpl.class)
-public class ClientRemovedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
-
- private String clientUuid;
- private String clientId;
- private String realmId;
- // roleId -> roleName
- private Map<String, String> clientRoles;
-
- public static ClientRemovedEvent create(ClientModel client) {
- ClientRemovedEvent event = new ClientRemovedEvent();
-
- event.realmId = client.getRealm().getId();
- event.clientUuid = client.getId();
- event.clientId = client.getClientId();
- event.clientRoles = new HashMap<>();
- for (RoleModel clientRole : client.getRoles()) {
- event.clientRoles.put(clientRole.getId(), clientRole.getName());
- }
-
- return event;
- }
-
- @Override
- public String getId() {
- return clientUuid;
- }
-
- @Override
- public String toString() {
- return String.format("ClientRemovedEvent [ realmId=%s, clientUuid=%s, clientId=%s, clientRoleIds=%s ]", realmId, clientUuid, clientId, clientRoles);
- }
-
- @Override
- public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
- realmCache.clientRemoval(realmId, clientUuid, clientId, invalidations);
-
- // Separate iteration for all client roles to invalidate records dependent on them
- for (Map.Entry<String, String> clientRole : clientRoles.entrySet()) {
- String roleId = clientRole.getKey();
- String roleName = clientRole.getValue();
- realmCache.roleRemoval(roleId, roleName, clientUuid, invalidations);
- }
- }
-
- public static class ExternalizerImpl implements Externalizer<ClientRemovedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, ClientRemovedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.clientUuid, output);
- MarshallUtil.marshallString(obj.clientId, output);
- MarshallUtil.marshallString(obj.realmId, output);
- KeycloakMarshallUtil.writeMap(obj.clientRoles, KeycloakMarshallUtil.STRING_EXT, KeycloakMarshallUtil.STRING_EXT, output);
- }
-
- @Override
- public ClientRemovedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public ClientRemovedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- ClientRemovedEvent res = new ClientRemovedEvent();
- res.clientUuid = MarshallUtil.unmarshallString(input);
- res.clientId = MarshallUtil.unmarshallString(input);
- res.realmId = MarshallUtil.unmarshallString(input);
- res.clientRoles = KeycloakMarshallUtil.readMap(input, KeycloakMarshallUtil.STRING_EXT, KeycloakMarshallUtil.STRING_EXT,
- size -> new ConcurrentHashMap<>(size));
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.events;
+
+// import java.util.HashMap;
+// import java.util.Map;
+// import java.util.Set;
+
+// import org.keycloak.models.ClientModel;
+// import org.keycloak.models.RoleModel;
+// import org.keycloak.models.cache.infinispan.RealmCacheManager;
+// import org.keycloak.models.sessions.infinispan.util.KeycloakMarshallUtil;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import java.util.concurrent.ConcurrentHashMap;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(ClientRemovedEvent.ExternalizerImpl.class)
+// public class ClientRemovedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
+
+// private String clientUuid;
+// private String clientId;
+// private String realmId;
+// // roleId -> roleName
+// private Map<String, String> clientRoles;
+
+// public static ClientRemovedEvent create(ClientModel client) {
+// ClientRemovedEvent event = new ClientRemovedEvent();
+
+// event.realmId = client.getRealm().getId();
+// event.clientUuid = client.getId();
+// event.clientId = client.getClientId();
+// event.clientRoles = new HashMap<>();
+// for (RoleModel clientRole : client.getRoles()) {
+// event.clientRoles.put(clientRole.getId(), clientRole.getName());
+// }
+
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return clientUuid;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("ClientRemovedEvent [ realmId=%s, clientUuid=%s, clientId=%s, clientRoleIds=%s ]", realmId, clientUuid, clientId, clientRoles);
+// }
+
+// @Override
+// public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
+// realmCache.clientRemoval(realmId, clientUuid, clientId, invalidations);
+
+// // Separate iteration for all client roles to invalidate records dependent on them
+// for (Map.Entry<String, String> clientRole : clientRoles.entrySet()) {
+// String roleId = clientRole.getKey();
+// String roleName = clientRole.getValue();
+// realmCache.roleRemoval(roleId, roleName, clientUuid, invalidations);
+// }
+// }
+
+// public static class ExternalizerImpl implements Externalizer<ClientRemovedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, ClientRemovedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.clientUuid, output);
+// MarshallUtil.marshallString(obj.clientId, output);
+// MarshallUtil.marshallString(obj.realmId, output);
+// KeycloakMarshallUtil.writeMap(obj.clientRoles, KeycloakMarshallUtil.STRING_EXT, KeycloakMarshallUtil.STRING_EXT, output);
+// }
+
+// @Override
+// public ClientRemovedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public ClientRemovedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// ClientRemovedEvent res = new ClientRemovedEvent();
+// res.clientUuid = MarshallUtil.unmarshallString(input);
+// res.clientId = MarshallUtil.unmarshallString(input);
+// res.realmId = MarshallUtil.unmarshallString(input);
+// res.clientRoles = KeycloakMarshallUtil.readMap(input, KeycloakMarshallUtil.STRING_EXT, KeycloakMarshallUtil.STRING_EXT,
+// size -> new ConcurrentHashMap<>(size));
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/ClientTemplateEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/ClientTemplateEvent.java
index 7ec3a03..6204c4b 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/ClientTemplateEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/ClientTemplateEvent.java
@@ -1,91 +1,91 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.events;
-
-import java.util.Set;
-
-import org.keycloak.models.cache.infinispan.RealmCacheManager;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * TODO Leave the name ClientTemplateEvent just due the backwards compatibility of infinispan migration. See if can be renamed based on
- * rolling upgrades plan...
- *
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(ClientTemplateEvent.ExternalizerImpl.class)
-public class ClientTemplateEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
-
- private String clientTemplateId;
-
- public static ClientTemplateEvent create(String clientTemplateId) {
- ClientTemplateEvent event = new ClientTemplateEvent();
- event.clientTemplateId = clientTemplateId;
- return event;
- }
-
- @Override
- public String getId() {
- return clientTemplateId;
- }
-
-
- @Override
- public String toString() {
- return "ClientTemplateEvent [ " + clientTemplateId + " ]";
- }
-
- @Override
- public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
- // Nothing. ID was already invalidated
- }
-
- public static class ExternalizerImpl implements Externalizer<ClientTemplateEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, ClientTemplateEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.clientTemplateId, output);
- }
-
- @Override
- public ClientTemplateEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public ClientTemplateEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- ClientTemplateEvent res = new ClientTemplateEvent();
- res.clientTemplateId = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.events;
+
+// import java.util.Set;
+
+// import org.keycloak.models.cache.infinispan.RealmCacheManager;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * TODO Leave the name ClientTemplateEvent just due the backwards compatibility of infinispan migration. See if can be renamed based on
+// * rolling upgrades plan...
+// *
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(ClientTemplateEvent.ExternalizerImpl.class)
+// public class ClientTemplateEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
+
+// private String clientTemplateId;
+
+// public static ClientTemplateEvent create(String clientTemplateId) {
+// ClientTemplateEvent event = new ClientTemplateEvent();
+// event.clientTemplateId = clientTemplateId;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return clientTemplateId;
+// }
+
+
+// @Override
+// public String toString() {
+// return "ClientTemplateEvent [ " + clientTemplateId + " ]";
+// }
+
+// @Override
+// public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
+// // Nothing. ID was already invalidated
+// }
+
+// public static class ExternalizerImpl implements Externalizer<ClientTemplateEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, ClientTemplateEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.clientTemplateId, output);
+// }
+
+// @Override
+// public ClientTemplateEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public ClientTemplateEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// ClientTemplateEvent res = new ClientTemplateEvent();
+// res.clientTemplateId = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/ClientUpdatedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/ClientUpdatedEvent.java
index c66ba49..4191bf2 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/ClientUpdatedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/ClientUpdatedEvent.java
@@ -1,95 +1,95 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.events;
-
-import java.util.Set;
-
-import org.keycloak.models.cache.infinispan.RealmCacheManager;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(ClientUpdatedEvent.ExternalizerImpl.class)
-public class ClientUpdatedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
-
- private String clientUuid;
- private String clientId;
- private String realmId;
-
- public static ClientUpdatedEvent create(String clientUuid, String clientId, String realmId) {
- ClientUpdatedEvent event = new ClientUpdatedEvent();
- event.clientUuid = clientUuid;
- event.clientId = clientId;
- event.realmId = realmId;
- return event;
- }
-
- @Override
- public String getId() {
- return clientUuid;
- }
-
- @Override
- public String toString() {
- return String.format("ClientUpdatedEvent [ realmId=%s, clientUuid=%s, clientId=%s ]", realmId, clientUuid, clientId);
- }
-
- @Override
- public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
- realmCache.clientUpdated(realmId, clientUuid, clientId, invalidations);
- }
-
- public static class ExternalizerImpl implements Externalizer<ClientUpdatedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, ClientUpdatedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.clientUuid, output);
- MarshallUtil.marshallString(obj.clientId, output);
- MarshallUtil.marshallString(obj.realmId, output);
- }
-
- @Override
- public ClientUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public ClientUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- ClientUpdatedEvent res = new ClientUpdatedEvent();
- res.clientUuid = MarshallUtil.unmarshallString(input);
- res.clientId = MarshallUtil.unmarshallString(input);
- res.realmId = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.events;
+
+// import java.util.Set;
+
+// import org.keycloak.models.cache.infinispan.RealmCacheManager;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(ClientUpdatedEvent.ExternalizerImpl.class)
+// public class ClientUpdatedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
+
+// private String clientUuid;
+// private String clientId;
+// private String realmId;
+
+// public static ClientUpdatedEvent create(String clientUuid, String clientId, String realmId) {
+// ClientUpdatedEvent event = new ClientUpdatedEvent();
+// event.clientUuid = clientUuid;
+// event.clientId = clientId;
+// event.realmId = realmId;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return clientUuid;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("ClientUpdatedEvent [ realmId=%s, clientUuid=%s, clientId=%s ]", realmId, clientUuid, clientId);
+// }
+
+// @Override
+// public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
+// realmCache.clientUpdated(realmId, clientUuid, clientId, invalidations);
+// }
+
+// public static class ExternalizerImpl implements Externalizer<ClientUpdatedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, ClientUpdatedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.clientUuid, output);
+// MarshallUtil.marshallString(obj.clientId, output);
+// MarshallUtil.marshallString(obj.realmId, output);
+// }
+
+// @Override
+// public ClientUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public ClientUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// ClientUpdatedEvent res = new ClientUpdatedEvent();
+// res.clientUuid = MarshallUtil.unmarshallString(input);
+// res.clientId = MarshallUtil.unmarshallString(input);
+// res.realmId = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/GroupAddedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/GroupAddedEvent.java
index 5573e61..267d335 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/GroupAddedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/GroupAddedEvent.java
@@ -1,92 +1,92 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.events;
-
-import java.util.Set;
-
-import org.keycloak.models.cache.infinispan.RealmCacheManager;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- *
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(GroupAddedEvent.ExternalizerImpl.class)
-public class GroupAddedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
-
- private String groupId;
- private String realmId;
-
- public static GroupAddedEvent create(String groupId, String realmId) {
- GroupAddedEvent event = new GroupAddedEvent();
- event.realmId = realmId;
- event.groupId = groupId;
- return event;
- }
-
- @Override
- public String getId() {
- return groupId;
- }
-
- @Override
- public String toString() {
- return String.format("GroupAddedEvent [ realmId=%s, groupId=%s ]", realmId, groupId);
- }
-
- @Override
- public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
- realmCache.groupQueriesInvalidations(realmId, invalidations);
- }
-
- public static class ExternalizerImpl implements Externalizer<GroupAddedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, GroupAddedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.groupId, output);
- MarshallUtil.marshallString(obj.realmId, output);
- }
-
- @Override
- public GroupAddedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public GroupAddedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- GroupAddedEvent res = new GroupAddedEvent();
- res.groupId = MarshallUtil.unmarshallString(input);
- res.realmId = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.events;
+
+// import java.util.Set;
+
+// import org.keycloak.models.cache.infinispan.RealmCacheManager;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// *
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(GroupAddedEvent.ExternalizerImpl.class)
+// public class GroupAddedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
+
+// private String groupId;
+// private String realmId;
+
+// public static GroupAddedEvent create(String groupId, String realmId) {
+// GroupAddedEvent event = new GroupAddedEvent();
+// event.realmId = realmId;
+// event.groupId = groupId;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return groupId;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("GroupAddedEvent [ realmId=%s, groupId=%s ]", realmId, groupId);
+// }
+
+// @Override
+// public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
+// realmCache.groupQueriesInvalidations(realmId, invalidations);
+// }
+
+// public static class ExternalizerImpl implements Externalizer<GroupAddedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, GroupAddedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.groupId, output);
+// MarshallUtil.marshallString(obj.realmId, output);
+// }
+
+// @Override
+// public GroupAddedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public GroupAddedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// GroupAddedEvent res = new GroupAddedEvent();
+// res.groupId = MarshallUtil.unmarshallString(input);
+// res.realmId = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/GroupMovedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/GroupMovedEvent.java
index 1f97723..c449683 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/GroupMovedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/GroupMovedEvent.java
@@ -1,106 +1,106 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.events;
-
-import java.util.Set;
-
-import org.keycloak.models.GroupModel;
-import org.keycloak.models.cache.infinispan.RealmCacheManager;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(GroupMovedEvent.ExternalizerImpl.class)
-public class GroupMovedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
-
- private String groupId;
- private String newParentId; // null if moving to top-level
- private String oldParentId; // null if moving from top-level
- private String realmId;
-
- public static GroupMovedEvent create(GroupModel group, GroupModel toParent, String realmId) {
- GroupMovedEvent event = new GroupMovedEvent();
- event.realmId = realmId;
- event.groupId = group.getId();
- event.oldParentId = group.getParentId();
- event.newParentId = toParent==null ? null : toParent.getId();
- return event;
- }
-
- @Override
- public String getId() {
- return groupId;
- }
-
- @Override
- public String toString() {
- return String.format("GroupMovedEvent [ realmId=%s, groupId=%s, newParentId=%s, oldParentId=%s ]", realmId, groupId, newParentId, oldParentId);
- }
-
- @Override
- public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
- realmCache.groupQueriesInvalidations(realmId, invalidations);
- if (newParentId != null) {
- invalidations.add(newParentId);
- }
- if (oldParentId != null) {
- invalidations.add(oldParentId);
- }
- }
-
- public static class ExternalizerImpl implements Externalizer<GroupMovedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, GroupMovedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.groupId, output);
- MarshallUtil.marshallString(obj.newParentId, output);
- MarshallUtil.marshallString(obj.oldParentId, output);
- MarshallUtil.marshallString(obj.realmId, output);
- }
-
- @Override
- public GroupMovedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public GroupMovedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- GroupMovedEvent res = new GroupMovedEvent();
- res.groupId = MarshallUtil.unmarshallString(input);
- res.newParentId = MarshallUtil.unmarshallString(input);
- res.oldParentId = MarshallUtil.unmarshallString(input);
- res.realmId = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.events;
+
+// import java.util.Set;
+
+// import org.keycloak.models.GroupModel;
+// import org.keycloak.models.cache.infinispan.RealmCacheManager;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(GroupMovedEvent.ExternalizerImpl.class)
+// public class GroupMovedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
+
+// private String groupId;
+// private String newParentId; // null if moving to top-level
+// private String oldParentId; // null if moving from top-level
+// private String realmId;
+
+// public static GroupMovedEvent create(GroupModel group, GroupModel toParent, String realmId) {
+// GroupMovedEvent event = new GroupMovedEvent();
+// event.realmId = realmId;
+// event.groupId = group.getId();
+// event.oldParentId = group.getParentId();
+// event.newParentId = toParent==null ? null : toParent.getId();
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return groupId;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("GroupMovedEvent [ realmId=%s, groupId=%s, newParentId=%s, oldParentId=%s ]", realmId, groupId, newParentId, oldParentId);
+// }
+
+// @Override
+// public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
+// realmCache.groupQueriesInvalidations(realmId, invalidations);
+// if (newParentId != null) {
+// invalidations.add(newParentId);
+// }
+// if (oldParentId != null) {
+// invalidations.add(oldParentId);
+// }
+// }
+
+// public static class ExternalizerImpl implements Externalizer<GroupMovedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, GroupMovedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.groupId, output);
+// MarshallUtil.marshallString(obj.newParentId, output);
+// MarshallUtil.marshallString(obj.oldParentId, output);
+// MarshallUtil.marshallString(obj.realmId, output);
+// }
+
+// @Override
+// public GroupMovedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public GroupMovedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// GroupMovedEvent res = new GroupMovedEvent();
+// res.groupId = MarshallUtil.unmarshallString(input);
+// res.newParentId = MarshallUtil.unmarshallString(input);
+// res.oldParentId = MarshallUtil.unmarshallString(input);
+// res.realmId = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/GroupRemovedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/GroupRemovedEvent.java
index bd301f7..f276d36 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/GroupRemovedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/GroupRemovedEvent.java
@@ -1,99 +1,99 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.events;
-
-import java.util.Set;
-
-import org.keycloak.models.GroupModel;
-import org.keycloak.models.cache.infinispan.RealmCacheManager;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(GroupRemovedEvent.ExternalizerImpl.class)
-public class GroupRemovedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
-
- private String groupId;
- private String parentId;
- private String realmId;
-
- public static GroupRemovedEvent create(GroupModel group, String realmId) {
- GroupRemovedEvent event = new GroupRemovedEvent();
- event.realmId = realmId;
- event.groupId = group.getId();
- event.parentId = group.getParentId();
- return event;
- }
-
- @Override
- public String getId() {
- return groupId;
- }
-
- @Override
- public String toString() {
- return String.format("GroupRemovedEvent [ realmId=%s, groupId=%s, parentId=%s ]", realmId, groupId, parentId);
- }
-
- @Override
- public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
- realmCache.groupQueriesInvalidations(realmId, invalidations);
- if (parentId != null) {
- invalidations.add(parentId);
- }
- }
-
- public static class ExternalizerImpl implements Externalizer<GroupRemovedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, GroupRemovedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.realmId, output);
- MarshallUtil.marshallString(obj.groupId, output);
- MarshallUtil.marshallString(obj.parentId, output);
- }
-
- @Override
- public GroupRemovedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public GroupRemovedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- GroupRemovedEvent res = new GroupRemovedEvent();
- res.realmId = MarshallUtil.unmarshallString(input);
- res.groupId = MarshallUtil.unmarshallString(input);
- res.parentId = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.events;
+
+// import java.util.Set;
+
+// import org.keycloak.models.GroupModel;
+// import org.keycloak.models.cache.infinispan.RealmCacheManager;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(GroupRemovedEvent.ExternalizerImpl.class)
+// public class GroupRemovedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
+
+// private String groupId;
+// private String parentId;
+// private String realmId;
+
+// public static GroupRemovedEvent create(GroupModel group, String realmId) {
+// GroupRemovedEvent event = new GroupRemovedEvent();
+// event.realmId = realmId;
+// event.groupId = group.getId();
+// event.parentId = group.getParentId();
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return groupId;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("GroupRemovedEvent [ realmId=%s, groupId=%s, parentId=%s ]", realmId, groupId, parentId);
+// }
+
+// @Override
+// public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
+// realmCache.groupQueriesInvalidations(realmId, invalidations);
+// if (parentId != null) {
+// invalidations.add(parentId);
+// }
+// }
+
+// public static class ExternalizerImpl implements Externalizer<GroupRemovedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, GroupRemovedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.realmId, output);
+// MarshallUtil.marshallString(obj.groupId, output);
+// MarshallUtil.marshallString(obj.parentId, output);
+// }
+
+// @Override
+// public GroupRemovedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public GroupRemovedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// GroupRemovedEvent res = new GroupRemovedEvent();
+// res.realmId = MarshallUtil.unmarshallString(input);
+// res.groupId = MarshallUtil.unmarshallString(input);
+// res.parentId = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/GroupUpdatedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/GroupUpdatedEvent.java
index a7ec69e..61033a9 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/GroupUpdatedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/GroupUpdatedEvent.java
@@ -1,88 +1,88 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.events;
-
-import java.util.Set;
-
-import org.keycloak.models.cache.infinispan.RealmCacheManager;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(GroupUpdatedEvent.ExternalizerImpl.class)
-public class GroupUpdatedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
-
- private String groupId;
-
- public static GroupUpdatedEvent create(String groupId) {
- GroupUpdatedEvent event = new GroupUpdatedEvent();
- event.groupId = groupId;
- return event;
- }
-
- @Override
- public String getId() {
- return groupId;
- }
-
-
- @Override
- public String toString() {
- return "GroupUpdatedEvent [ " + groupId + " ]";
- }
-
- @Override
- public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
- // Nothing. ID already invalidated
- }
-
- public static class ExternalizerImpl implements Externalizer<GroupUpdatedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, GroupUpdatedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.groupId, output);
- }
-
- @Override
- public GroupUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public GroupUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- GroupUpdatedEvent res = new GroupUpdatedEvent();
- res.groupId = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.events;
+
+// import java.util.Set;
+
+// import org.keycloak.models.cache.infinispan.RealmCacheManager;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(GroupUpdatedEvent.ExternalizerImpl.class)
+// public class GroupUpdatedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
+
+// private String groupId;
+
+// public static GroupUpdatedEvent create(String groupId) {
+// GroupUpdatedEvent event = new GroupUpdatedEvent();
+// event.groupId = groupId;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return groupId;
+// }
+
+
+// @Override
+// public String toString() {
+// return "GroupUpdatedEvent [ " + groupId + " ]";
+// }
+
+// @Override
+// public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
+// // Nothing. ID already invalidated
+// }
+
+// public static class ExternalizerImpl implements Externalizer<GroupUpdatedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, GroupUpdatedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.groupId, output);
+// }
+
+// @Override
+// public GroupUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public GroupUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// GroupUpdatedEvent res = new GroupUpdatedEvent();
+// res.groupId = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RealmCacheInvalidationEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RealmCacheInvalidationEvent.java
index 2876e08..6f63fe2 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RealmCacheInvalidationEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RealmCacheInvalidationEvent.java
@@ -15,17 +15,17 @@
* limitations under the License.
*/
-package org.keycloak.models.cache.infinispan.events;
+// package org.keycloak.models.cache.infinispan.events;
-import java.util.Set;
+// import java.util.Set;
-import org.keycloak.models.cache.infinispan.RealmCacheManager;
+// import org.keycloak.models.cache.infinispan.RealmCacheManager;
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-public interface RealmCacheInvalidationEvent {
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// public interface RealmCacheInvalidationEvent {
- void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations);
+// void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations);
-}
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RealmRemovedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RealmRemovedEvent.java
index df5c6b7..52a68fa 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RealmRemovedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RealmRemovedEvent.java
@@ -1,91 +1,91 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.events;
-
-import java.util.Set;
-
-import org.keycloak.models.cache.infinispan.RealmCacheManager;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(RealmRemovedEvent.ExternalizerImpl.class)
-public class RealmRemovedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
-
- private String realmId;
- private String realmName;
-
- public static RealmRemovedEvent create(String realmId, String realmName) {
- RealmRemovedEvent event = new RealmRemovedEvent();
- event.realmId = realmId;
- event.realmName = realmName;
- return event;
- }
-
- @Override
- public String getId() {
- return realmId;
- }
-
- @Override
- public String toString() {
- return String.format("RealmRemovedEvent [ realmId=%s, realmName=%s ]", realmId, realmName);
- }
-
- @Override
- public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
- realmCache.realmRemoval(realmId, realmName, invalidations);
- }
-
- public static class ExternalizerImpl implements Externalizer<RealmRemovedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, RealmRemovedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.realmId, output);
- MarshallUtil.marshallString(obj.realmName, output);
- }
-
- @Override
- public RealmRemovedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public RealmRemovedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- RealmRemovedEvent res = new RealmRemovedEvent();
- res.realmId = MarshallUtil.unmarshallString(input);
- res.realmName = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.events;
+
+// import java.util.Set;
+
+// import org.keycloak.models.cache.infinispan.RealmCacheManager;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(RealmRemovedEvent.ExternalizerImpl.class)
+// public class RealmRemovedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
+
+// private String realmId;
+// private String realmName;
+
+// public static RealmRemovedEvent create(String realmId, String realmName) {
+// RealmRemovedEvent event = new RealmRemovedEvent();
+// event.realmId = realmId;
+// event.realmName = realmName;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return realmId;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("RealmRemovedEvent [ realmId=%s, realmName=%s ]", realmId, realmName);
+// }
+
+// @Override
+// public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
+// realmCache.realmRemoval(realmId, realmName, invalidations);
+// }
+
+// public static class ExternalizerImpl implements Externalizer<RealmRemovedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, RealmRemovedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.realmId, output);
+// MarshallUtil.marshallString(obj.realmName, output);
+// }
+
+// @Override
+// public RealmRemovedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public RealmRemovedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// RealmRemovedEvent res = new RealmRemovedEvent();
+// res.realmId = MarshallUtil.unmarshallString(input);
+// res.realmName = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RealmUpdatedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RealmUpdatedEvent.java
index ce3c9c2..941a301 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RealmUpdatedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RealmUpdatedEvent.java
@@ -1,91 +1,91 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.events;
-
-import java.util.Set;
-
-import org.keycloak.models.cache.infinispan.RealmCacheManager;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(RealmUpdatedEvent.ExternalizerImpl.class)
-public class RealmUpdatedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
-
- private String realmId;
- private String realmName;
-
- public static RealmUpdatedEvent create(String realmId, String realmName) {
- RealmUpdatedEvent event = new RealmUpdatedEvent();
- event.realmId = realmId;
- event.realmName = realmName;
- return event;
- }
-
- @Override
- public String getId() {
- return realmId;
- }
-
- @Override
- public String toString() {
- return String.format("RealmUpdatedEvent [ realmId=%s, realmName=%s ]", realmId, realmName);
- }
-
- @Override
- public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
- realmCache.realmUpdated(realmId, realmName, invalidations);
- }
-
- public static class ExternalizerImpl implements Externalizer<RealmUpdatedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, RealmUpdatedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.realmId, output);
- MarshallUtil.marshallString(obj.realmName, output);
- }
-
- @Override
- public RealmUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public RealmUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- RealmUpdatedEvent res = new RealmUpdatedEvent();
- res.realmId = MarshallUtil.unmarshallString(input);
- res.realmName = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.events;
+
+// import java.util.Set;
+
+// import org.keycloak.models.cache.infinispan.RealmCacheManager;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(RealmUpdatedEvent.ExternalizerImpl.class)
+// public class RealmUpdatedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
+
+// private String realmId;
+// private String realmName;
+
+// public static RealmUpdatedEvent create(String realmId, String realmName) {
+// RealmUpdatedEvent event = new RealmUpdatedEvent();
+// event.realmId = realmId;
+// event.realmName = realmName;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return realmId;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("RealmUpdatedEvent [ realmId=%s, realmName=%s ]", realmId, realmName);
+// }
+
+// @Override
+// public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
+// realmCache.realmUpdated(realmId, realmName, invalidations);
+// }
+
+// public static class ExternalizerImpl implements Externalizer<RealmUpdatedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, RealmUpdatedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.realmId, output);
+// MarshallUtil.marshallString(obj.realmName, output);
+// }
+
+// @Override
+// public RealmUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public RealmUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// RealmUpdatedEvent res = new RealmUpdatedEvent();
+// res.realmId = MarshallUtil.unmarshallString(input);
+// res.realmName = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RoleAddedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RoleAddedEvent.java
index fac386f..b4a3095 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RoleAddedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RoleAddedEvent.java
@@ -1,91 +1,91 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.events;
-
-import java.util.Set;
-
-import org.keycloak.models.cache.infinispan.RealmCacheManager;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(RoleAddedEvent.ExternalizerImpl.class)
-public class RoleAddedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
-
- private String roleId;
- private String containerId;
-
- public static RoleAddedEvent create(String roleId, String containerId) {
- RoleAddedEvent event = new RoleAddedEvent();
- event.roleId = roleId;
- event.containerId = containerId;
- return event;
- }
-
- @Override
- public String getId() {
- return roleId;
- }
-
- @Override
- public String toString() {
- return String.format("RoleAddedEvent [ roleId=%s, containerId=%s ]", roleId, containerId);
- }
-
- @Override
- public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
- realmCache.roleAdded(containerId, invalidations);
- }
-
- public static class ExternalizerImpl implements Externalizer<RoleAddedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, RoleAddedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.roleId, output);
- MarshallUtil.marshallString(obj.containerId, output);
- }
-
- @Override
- public RoleAddedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public RoleAddedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- RoleAddedEvent res = new RoleAddedEvent();
- res.roleId = MarshallUtil.unmarshallString(input);
- res.containerId = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.events;
+
+// import java.util.Set;
+
+// import org.keycloak.models.cache.infinispan.RealmCacheManager;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(RoleAddedEvent.ExternalizerImpl.class)
+// public class RoleAddedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
+
+// private String roleId;
+// private String containerId;
+
+// public static RoleAddedEvent create(String roleId, String containerId) {
+// RoleAddedEvent event = new RoleAddedEvent();
+// event.roleId = roleId;
+// event.containerId = containerId;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return roleId;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("RoleAddedEvent [ roleId=%s, containerId=%s ]", roleId, containerId);
+// }
+
+// @Override
+// public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
+// realmCache.roleAdded(containerId, invalidations);
+// }
+
+// public static class ExternalizerImpl implements Externalizer<RoleAddedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, RoleAddedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.roleId, output);
+// MarshallUtil.marshallString(obj.containerId, output);
+// }
+
+// @Override
+// public RoleAddedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public RoleAddedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// RoleAddedEvent res = new RoleAddedEvent();
+// res.roleId = MarshallUtil.unmarshallString(input);
+// res.containerId = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RoleRemovedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RoleRemovedEvent.java
index 59297e3..07391dc 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RoleRemovedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RoleRemovedEvent.java
@@ -1,95 +1,95 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.events;
-
-import java.util.Set;
-
-import org.keycloak.models.cache.infinispan.RealmCacheManager;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(RoleRemovedEvent.ExternalizerImpl.class)
-public class RoleRemovedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
-
- private String roleId;
- private String roleName;
- private String containerId;
-
- public static RoleRemovedEvent create(String roleId, String roleName, String containerId) {
- RoleRemovedEvent event = new RoleRemovedEvent();
- event.roleId = roleId;
- event.roleName = roleName;
- event.containerId = containerId;
- return event;
- }
-
- @Override
- public String getId() {
- return roleId;
- }
-
- @Override
- public String toString() {
- return String.format("RoleRemovedEvent [ roleId=%s, containerId=%s ]", roleId, containerId);
- }
-
- @Override
- public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
- realmCache.roleRemoval(roleId, roleName, containerId, invalidations);
- }
-
- public static class ExternalizerImpl implements Externalizer<RoleRemovedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, RoleRemovedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.roleId, output);
- MarshallUtil.marshallString(obj.roleName, output);
- MarshallUtil.marshallString(obj.containerId, output);
- }
-
- @Override
- public RoleRemovedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public RoleRemovedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- RoleRemovedEvent res = new RoleRemovedEvent();
- res.roleId = MarshallUtil.unmarshallString(input);
- res.roleName = MarshallUtil.unmarshallString(input);
- res.containerId = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.events;
+
+// import java.util.Set;
+
+// import org.keycloak.models.cache.infinispan.RealmCacheManager;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(RoleRemovedEvent.ExternalizerImpl.class)
+// public class RoleRemovedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
+
+// private String roleId;
+// private String roleName;
+// private String containerId;
+
+// public static RoleRemovedEvent create(String roleId, String roleName, String containerId) {
+// RoleRemovedEvent event = new RoleRemovedEvent();
+// event.roleId = roleId;
+// event.roleName = roleName;
+// event.containerId = containerId;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return roleId;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("RoleRemovedEvent [ roleId=%s, containerId=%s ]", roleId, containerId);
+// }
+
+// @Override
+// public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
+// realmCache.roleRemoval(roleId, roleName, containerId, invalidations);
+// }
+
+// public static class ExternalizerImpl implements Externalizer<RoleRemovedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, RoleRemovedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.roleId, output);
+// MarshallUtil.marshallString(obj.roleName, output);
+// MarshallUtil.marshallString(obj.containerId, output);
+// }
+
+// @Override
+// public RoleRemovedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public RoleRemovedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// RoleRemovedEvent res = new RoleRemovedEvent();
+// res.roleId = MarshallUtil.unmarshallString(input);
+// res.roleName = MarshallUtil.unmarshallString(input);
+// res.containerId = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RoleUpdatedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RoleUpdatedEvent.java
index c550b70..2fa0001 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RoleUpdatedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/RoleUpdatedEvent.java
@@ -1,95 +1,95 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.events;
-
-import java.util.Set;
-
-import org.keycloak.models.cache.infinispan.RealmCacheManager;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(RoleUpdatedEvent.ExternalizerImpl.class)
-public class RoleUpdatedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
-
- private String roleId;
- private String roleName;
- private String containerId;
-
- public static RoleUpdatedEvent create(String roleId, String roleName, String containerId) {
- RoleUpdatedEvent event = new RoleUpdatedEvent();
- event.roleId = roleId;
- event.roleName = roleName;
- event.containerId = containerId;
- return event;
- }
-
- @Override
- public String getId() {
- return roleId;
- }
-
- @Override
- public String toString() {
- return String.format("RoleUpdatedEvent [ roleId=%s, roleName=%s, containerId=%s ]", roleId, roleName, containerId);
- }
-
- @Override
- public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
- realmCache.roleUpdated(containerId, roleName, invalidations);
- }
-
- public static class ExternalizerImpl implements Externalizer<RoleUpdatedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, RoleUpdatedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.roleId, output);
- MarshallUtil.marshallString(obj.roleName, output);
- MarshallUtil.marshallString(obj.containerId, output);
- }
-
- @Override
- public RoleUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public RoleUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- RoleUpdatedEvent res = new RoleUpdatedEvent();
- res.roleId = MarshallUtil.unmarshallString(input);
- res.roleName = MarshallUtil.unmarshallString(input);
- res.containerId = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.events;
+
+// import java.util.Set;
+
+// import org.keycloak.models.cache.infinispan.RealmCacheManager;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(RoleUpdatedEvent.ExternalizerImpl.class)
+// public class RoleUpdatedEvent extends InvalidationEvent implements RealmCacheInvalidationEvent {
+
+// private String roleId;
+// private String roleName;
+// private String containerId;
+
+// public static RoleUpdatedEvent create(String roleId, String roleName, String containerId) {
+// RoleUpdatedEvent event = new RoleUpdatedEvent();
+// event.roleId = roleId;
+// event.roleName = roleName;
+// event.containerId = containerId;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return roleId;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("RoleUpdatedEvent [ roleId=%s, roleName=%s, containerId=%s ]", roleId, roleName, containerId);
+// }
+
+// @Override
+// public void addInvalidations(RealmCacheManager realmCache, Set<String> invalidations) {
+// realmCache.roleUpdated(containerId, roleName, invalidations);
+// }
+
+// public static class ExternalizerImpl implements Externalizer<RoleUpdatedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, RoleUpdatedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.roleId, output);
+// MarshallUtil.marshallString(obj.roleName, output);
+// MarshallUtil.marshallString(obj.containerId, output);
+// }
+
+// @Override
+// public RoleUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public RoleUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// RoleUpdatedEvent res = new RoleUpdatedEvent();
+// res.roleId = MarshallUtil.unmarshallString(input);
+// res.roleName = MarshallUtil.unmarshallString(input);
+// res.containerId = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserCacheInvalidationEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserCacheInvalidationEvent.java
index 964e97a..65d967f 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserCacheInvalidationEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserCacheInvalidationEvent.java
@@ -15,17 +15,17 @@
* limitations under the License.
*/
-package org.keycloak.models.cache.infinispan.events;
+// package org.keycloak.models.cache.infinispan.events;
-import java.util.Set;
+// import java.util.Set;
-import org.keycloak.models.cache.infinispan.UserCacheManager;
+// import org.keycloak.models.cache.infinispan.UserCacheManager;
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-public interface UserCacheInvalidationEvent {
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// public interface UserCacheInvalidationEvent {
- void addInvalidations(UserCacheManager userCache, Set<String> invalidations);
+// void addInvalidations(UserCacheManager userCache, Set<String> invalidations);
-}
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserCacheRealmInvalidationEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserCacheRealmInvalidationEvent.java
index 2f144d2..a826972 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserCacheRealmInvalidationEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserCacheRealmInvalidationEvent.java
@@ -1,87 +1,87 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.events;
-
-import java.util.Set;
-
-import org.keycloak.models.cache.infinispan.UserCacheManager;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(UserCacheRealmInvalidationEvent.ExternalizerImpl.class)
-public class UserCacheRealmInvalidationEvent extends InvalidationEvent implements UserCacheInvalidationEvent {
-
- private String realmId;
-
- public static UserCacheRealmInvalidationEvent create(String realmId) {
- UserCacheRealmInvalidationEvent event = new UserCacheRealmInvalidationEvent();
- event.realmId = realmId;
- return event;
- }
-
- @Override
- public String getId() {
- return realmId; // Just a placeholder
- }
-
- @Override
- public String toString() {
- return String.format("UserCacheRealmInvalidationEvent [ realmId=%s ]", realmId);
- }
-
- @Override
- public void addInvalidations(UserCacheManager userCache, Set<String> invalidations) {
- userCache.invalidateRealmUsers(realmId, invalidations);
- }
-
- public static class ExternalizerImpl implements Externalizer<UserCacheRealmInvalidationEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, UserCacheRealmInvalidationEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.realmId, output);
- }
-
- @Override
- public UserCacheRealmInvalidationEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public UserCacheRealmInvalidationEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- UserCacheRealmInvalidationEvent res = new UserCacheRealmInvalidationEvent();
- res.realmId = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.events;
+
+// import java.util.Set;
+
+// import org.keycloak.models.cache.infinispan.UserCacheManager;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(UserCacheRealmInvalidationEvent.ExternalizerImpl.class)
+// public class UserCacheRealmInvalidationEvent extends InvalidationEvent implements UserCacheInvalidationEvent {
+
+// private String realmId;
+
+// public static UserCacheRealmInvalidationEvent create(String realmId) {
+// UserCacheRealmInvalidationEvent event = new UserCacheRealmInvalidationEvent();
+// event.realmId = realmId;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return realmId; // Just a placeholder
+// }
+
+// @Override
+// public String toString() {
+// return String.format("UserCacheRealmInvalidationEvent [ realmId=%s ]", realmId);
+// }
+
+// @Override
+// public void addInvalidations(UserCacheManager userCache, Set<String> invalidations) {
+// userCache.invalidateRealmUsers(realmId, invalidations);
+// }
+
+// public static class ExternalizerImpl implements Externalizer<UserCacheRealmInvalidationEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, UserCacheRealmInvalidationEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.realmId, output);
+// }
+
+// @Override
+// public UserCacheRealmInvalidationEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public UserCacheRealmInvalidationEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// UserCacheRealmInvalidationEvent res = new UserCacheRealmInvalidationEvent();
+// res.realmId = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserConsentsUpdatedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserConsentsUpdatedEvent.java
index 1d4b93d..1ca6824 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserConsentsUpdatedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserConsentsUpdatedEvent.java
@@ -1,87 +1,87 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.events;
-
-import java.util.Set;
-
-import org.keycloak.models.cache.infinispan.UserCacheManager;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(UserConsentsUpdatedEvent.ExternalizerImpl.class)
-public class UserConsentsUpdatedEvent extends InvalidationEvent implements UserCacheInvalidationEvent {
-
- private String userId;
-
- public static UserConsentsUpdatedEvent create(String userId) {
- UserConsentsUpdatedEvent event = new UserConsentsUpdatedEvent();
- event.userId = userId;
- return event;
- }
-
- @Override
- public String getId() {
- return userId;
- }
-
- @Override
- public String toString() {
- return String.format("UserConsentsUpdatedEvent [ userId=%s ]", userId);
- }
-
- @Override
- public void addInvalidations(UserCacheManager userCache, Set<String> invalidations) {
- userCache.consentInvalidation(userId, invalidations);
- }
-
- public static class ExternalizerImpl implements Externalizer<UserConsentsUpdatedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, UserConsentsUpdatedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.userId, output);
- }
-
- @Override
- public UserConsentsUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public UserConsentsUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- UserConsentsUpdatedEvent res = new UserConsentsUpdatedEvent();
- res.userId = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.events;
+
+// import java.util.Set;
+
+// import org.keycloak.models.cache.infinispan.UserCacheManager;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(UserConsentsUpdatedEvent.ExternalizerImpl.class)
+// public class UserConsentsUpdatedEvent extends InvalidationEvent implements UserCacheInvalidationEvent {
+
+// private String userId;
+
+// public static UserConsentsUpdatedEvent create(String userId) {
+// UserConsentsUpdatedEvent event = new UserConsentsUpdatedEvent();
+// event.userId = userId;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return userId;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("UserConsentsUpdatedEvent [ userId=%s ]", userId);
+// }
+
+// @Override
+// public void addInvalidations(UserCacheManager userCache, Set<String> invalidations) {
+// userCache.consentInvalidation(userId, invalidations);
+// }
+
+// public static class ExternalizerImpl implements Externalizer<UserConsentsUpdatedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, UserConsentsUpdatedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.userId, output);
+// }
+
+// @Override
+// public UserConsentsUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public UserConsentsUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// UserConsentsUpdatedEvent res = new UserConsentsUpdatedEvent();
+// res.userId = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserFederationLinkRemovedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserFederationLinkRemovedEvent.java
index b752328..7271109 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserFederationLinkRemovedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserFederationLinkRemovedEvent.java
@@ -1,114 +1,114 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.events;
-
-import java.util.Set;
-
-import org.keycloak.models.FederatedIdentityModel;
-import org.keycloak.models.cache.infinispan.UserCacheManager;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(UserFederationLinkRemovedEvent.ExternalizerImpl.class)
-public class UserFederationLinkRemovedEvent extends InvalidationEvent implements UserCacheInvalidationEvent {
-
- private String userId;
- private String realmId;
- private String identityProviderId;
- private String socialUserId;
-
- public static UserFederationLinkRemovedEvent create(String userId, String realmId, FederatedIdentityModel socialLink) {
- UserFederationLinkRemovedEvent event = new UserFederationLinkRemovedEvent();
- event.userId = userId;
- event.realmId = realmId;
- if (socialLink != null) {
- event.identityProviderId = socialLink.getIdentityProvider();
- event.socialUserId = socialLink.getUserId();
- }
- return event;
- }
-
- @Override
- public String getId() {
- return userId;
- }
-
- public String getRealmId() {
- return realmId;
- }
-
- public String getIdentityProviderId() {
- return identityProviderId;
- }
-
- public String getSocialUserId() {
- return socialUserId;
- }
-
- @Override
- public String toString() {
- return String.format("UserFederationLinkRemovedEvent [ userId=%s, identityProviderId=%s, socialUserId=%s ]", userId, identityProviderId, socialUserId);
- }
-
- @Override
- public void addInvalidations(UserCacheManager userCache, Set<String> invalidations) {
- userCache.federatedIdentityLinkRemovedInvalidation(userId, realmId, identityProviderId, socialUserId, invalidations);
- }
-
- public static class ExternalizerImpl implements Externalizer<UserFederationLinkRemovedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, UserFederationLinkRemovedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.userId, output);
- MarshallUtil.marshallString(obj.realmId, output);
- MarshallUtil.marshallString(obj.identityProviderId, output);
- MarshallUtil.marshallString(obj.socialUserId, output);
- }
-
- @Override
- public UserFederationLinkRemovedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public UserFederationLinkRemovedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- UserFederationLinkRemovedEvent res = new UserFederationLinkRemovedEvent();
- res.userId = MarshallUtil.unmarshallString(input);
- res.realmId = MarshallUtil.unmarshallString(input);
- res.identityProviderId = MarshallUtil.unmarshallString(input);
- res.socialUserId = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.events;
+
+// import java.util.Set;
+
+// import org.keycloak.models.FederatedIdentityModel;
+// import org.keycloak.models.cache.infinispan.UserCacheManager;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(UserFederationLinkRemovedEvent.ExternalizerImpl.class)
+// public class UserFederationLinkRemovedEvent extends InvalidationEvent implements UserCacheInvalidationEvent {
+
+// private String userId;
+// private String realmId;
+// private String identityProviderId;
+// private String socialUserId;
+
+// public static UserFederationLinkRemovedEvent create(String userId, String realmId, FederatedIdentityModel socialLink) {
+// UserFederationLinkRemovedEvent event = new UserFederationLinkRemovedEvent();
+// event.userId = userId;
+// event.realmId = realmId;
+// if (socialLink != null) {
+// event.identityProviderId = socialLink.getIdentityProvider();
+// event.socialUserId = socialLink.getUserId();
+// }
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return userId;
+// }
+
+// public String getRealmId() {
+// return realmId;
+// }
+
+// public String getIdentityProviderId() {
+// return identityProviderId;
+// }
+
+// public String getSocialUserId() {
+// return socialUserId;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("UserFederationLinkRemovedEvent [ userId=%s, identityProviderId=%s, socialUserId=%s ]", userId, identityProviderId, socialUserId);
+// }
+
+// @Override
+// public void addInvalidations(UserCacheManager userCache, Set<String> invalidations) {
+// userCache.federatedIdentityLinkRemovedInvalidation(userId, realmId, identityProviderId, socialUserId, invalidations);
+// }
+
+// public static class ExternalizerImpl implements Externalizer<UserFederationLinkRemovedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, UserFederationLinkRemovedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.userId, output);
+// MarshallUtil.marshallString(obj.realmId, output);
+// MarshallUtil.marshallString(obj.identityProviderId, output);
+// MarshallUtil.marshallString(obj.socialUserId, output);
+// }
+
+// @Override
+// public UserFederationLinkRemovedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public UserFederationLinkRemovedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// UserFederationLinkRemovedEvent res = new UserFederationLinkRemovedEvent();
+// res.userId = MarshallUtil.unmarshallString(input);
+// res.realmId = MarshallUtil.unmarshallString(input);
+// res.identityProviderId = MarshallUtil.unmarshallString(input);
+// res.socialUserId = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserFederationLinkUpdatedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserFederationLinkUpdatedEvent.java
index 692915b..24d96d6 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserFederationLinkUpdatedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserFederationLinkUpdatedEvent.java
@@ -1,86 +1,86 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.keycloak.models.cache.infinispan.events;
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+// package org.keycloak.models.cache.infinispan.events;
-import java.util.Set;
+// import java.util.Set;
-import org.keycloak.models.cache.infinispan.UserCacheManager;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
+// import org.keycloak.models.cache.infinispan.UserCacheManager;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(UserFederationLinkUpdatedEvent.ExternalizerImpl.class)
-public class UserFederationLinkUpdatedEvent extends InvalidationEvent implements UserCacheInvalidationEvent {
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(UserFederationLinkUpdatedEvent.ExternalizerImpl.class)
+// public class UserFederationLinkUpdatedEvent extends InvalidationEvent implements UserCacheInvalidationEvent {
- private String userId;
+// private String userId;
- public static UserFederationLinkUpdatedEvent create(String userId) {
- UserFederationLinkUpdatedEvent event = new UserFederationLinkUpdatedEvent();
- event.userId = userId;
- return event;
- }
+// public static UserFederationLinkUpdatedEvent create(String userId) {
+// UserFederationLinkUpdatedEvent event = new UserFederationLinkUpdatedEvent();
+// event.userId = userId;
+// return event;
+// }
- @Override
- public String getId() {
- return userId;
- }
+// @Override
+// public String getId() {
+// return userId;
+// }
- @Override
- public String toString() {
- return String.format("UserFederationLinkUpdatedEvent [ userId=%s ]", userId);
- }
+// @Override
+// public String toString() {
+// return String.format("UserFederationLinkUpdatedEvent [ userId=%s ]", userId);
+// }
- @Override
- public void addInvalidations(UserCacheManager userCache, Set<String> invalidations) {
- userCache.federatedIdentityLinkUpdatedInvalidation(userId, invalidations);
- }
+// @Override
+// public void addInvalidations(UserCacheManager userCache, Set<String> invalidations) {
+// userCache.federatedIdentityLinkUpdatedInvalidation(userId, invalidations);
+// }
- public static class ExternalizerImpl implements Externalizer<UserFederationLinkUpdatedEvent> {
+// public static class ExternalizerImpl implements Externalizer<UserFederationLinkUpdatedEvent> {
- private static final int VERSION_1 = 1;
+// private static final int VERSION_1 = 1;
- @Override
- public void writeObject(ObjectOutput output, UserFederationLinkUpdatedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
+// @Override
+// public void writeObject(ObjectOutput output, UserFederationLinkUpdatedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
- MarshallUtil.marshallString(obj.userId, output);
- }
+// MarshallUtil.marshallString(obj.userId, output);
+// }
- @Override
- public UserFederationLinkUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
+// @Override
+// public UserFederationLinkUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
- public UserFederationLinkUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- UserFederationLinkUpdatedEvent res = new UserFederationLinkUpdatedEvent();
- res.userId = MarshallUtil.unmarshallString(input);
+// public UserFederationLinkUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// UserFederationLinkUpdatedEvent res = new UserFederationLinkUpdatedEvent();
+// res.userId = MarshallUtil.unmarshallString(input);
- return res;
- }
- }
-}
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserFullInvalidationEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserFullInvalidationEvent.java
index ebc4efa..f091bce 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserFullInvalidationEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserFullInvalidationEvent.java
@@ -1,125 +1,125 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.events;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import org.keycloak.models.FederatedIdentityModel;
-import org.keycloak.models.cache.infinispan.UserCacheManager;
-import org.keycloak.models.sessions.infinispan.util.KeycloakMarshallUtil;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * Used when user added/removed
- *
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(UserFullInvalidationEvent.ExternalizerImpl.class)
-public class UserFullInvalidationEvent extends InvalidationEvent implements UserCacheInvalidationEvent {
-
- private String userId;
- private String username;
- private String email;
- private String realmId;
- private boolean identityFederationEnabled;
- private Map<String, String> federatedIdentities;
-
- public static UserFullInvalidationEvent create(String userId, String username, String email, String realmId, boolean identityFederationEnabled, Collection<FederatedIdentityModel> federatedIdentities) {
- UserFullInvalidationEvent event = new UserFullInvalidationEvent();
- event.userId = userId;
- event.username = username;
- event.email = email;
- event.realmId = realmId;
-
- event.identityFederationEnabled = identityFederationEnabled;
- if (identityFederationEnabled) {
- event.federatedIdentities = new HashMap<>();
- for (FederatedIdentityModel socialLink : federatedIdentities) {
- event.federatedIdentities.put(socialLink.getIdentityProvider(), socialLink.getUserId());
- }
- }
-
- return event;
- }
-
- @Override
- public String getId() {
- return userId;
- }
-
- public Map<String, String> getFederatedIdentities() {
- return federatedIdentities;
- }
-
- @Override
- public String toString() {
- return String.format("UserFullInvalidationEvent [ userId=%s, username=%s, email=%s ]", userId, username, email);
- }
-
- @Override
- public void addInvalidations(UserCacheManager userCache, Set<String> invalidations) {
- userCache.fullUserInvalidation(userId, username, email, realmId, identityFederationEnabled, federatedIdentities, invalidations);
- }
-
- public static class ExternalizerImpl implements Externalizer<UserFullInvalidationEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, UserFullInvalidationEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.userId, output);
- MarshallUtil.marshallString(obj.username, output);
- MarshallUtil.marshallString(obj.email, output);
- MarshallUtil.marshallString(obj.realmId, output);
- output.writeBoolean(obj.identityFederationEnabled);
- KeycloakMarshallUtil.writeMap(obj.federatedIdentities, KeycloakMarshallUtil.STRING_EXT, KeycloakMarshallUtil.STRING_EXT, output);
- }
-
- @Override
- public UserFullInvalidationEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public UserFullInvalidationEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- UserFullInvalidationEvent res = new UserFullInvalidationEvent();
- res.userId = MarshallUtil.unmarshallString(input);
- res.username = MarshallUtil.unmarshallString(input);
- res.email = MarshallUtil.unmarshallString(input);
- res.realmId = MarshallUtil.unmarshallString(input);
- res.identityFederationEnabled = input.readBoolean();
- res.federatedIdentities = KeycloakMarshallUtil.readMap(input, KeycloakMarshallUtil.STRING_EXT, KeycloakMarshallUtil.STRING_EXT, HashMap::new);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.events;
+
+// import java.util.Collection;
+// import java.util.HashMap;
+// import java.util.Map;
+// import java.util.Set;
+
+// import org.keycloak.models.FederatedIdentityModel;
+// import org.keycloak.models.cache.infinispan.UserCacheManager;
+// import org.keycloak.models.sessions.infinispan.util.KeycloakMarshallUtil;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * Used when user added/removed
+// *
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(UserFullInvalidationEvent.ExternalizerImpl.class)
+// public class UserFullInvalidationEvent extends InvalidationEvent implements UserCacheInvalidationEvent {
+
+// private String userId;
+// private String username;
+// private String email;
+// private String realmId;
+// private boolean identityFederationEnabled;
+// private Map<String, String> federatedIdentities;
+
+// public static UserFullInvalidationEvent create(String userId, String username, String email, String realmId, boolean identityFederationEnabled, Collection<FederatedIdentityModel> federatedIdentities) {
+// UserFullInvalidationEvent event = new UserFullInvalidationEvent();
+// event.userId = userId;
+// event.username = username;
+// event.email = email;
+// event.realmId = realmId;
+
+// event.identityFederationEnabled = identityFederationEnabled;
+// if (identityFederationEnabled) {
+// event.federatedIdentities = new HashMap<>();
+// for (FederatedIdentityModel socialLink : federatedIdentities) {
+// event.federatedIdentities.put(socialLink.getIdentityProvider(), socialLink.getUserId());
+// }
+// }
+
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return userId;
+// }
+
+// public Map<String, String> getFederatedIdentities() {
+// return federatedIdentities;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("UserFullInvalidationEvent [ userId=%s, username=%s, email=%s ]", userId, username, email);
+// }
+
+// @Override
+// public void addInvalidations(UserCacheManager userCache, Set<String> invalidations) {
+// userCache.fullUserInvalidation(userId, username, email, realmId, identityFederationEnabled, federatedIdentities, invalidations);
+// }
+
+// public static class ExternalizerImpl implements Externalizer<UserFullInvalidationEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, UserFullInvalidationEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.userId, output);
+// MarshallUtil.marshallString(obj.username, output);
+// MarshallUtil.marshallString(obj.email, output);
+// MarshallUtil.marshallString(obj.realmId, output);
+// output.writeBoolean(obj.identityFederationEnabled);
+// KeycloakMarshallUtil.writeMap(obj.federatedIdentities, KeycloakMarshallUtil.STRING_EXT, KeycloakMarshallUtil.STRING_EXT, output);
+// }
+
+// @Override
+// public UserFullInvalidationEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public UserFullInvalidationEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// UserFullInvalidationEvent res = new UserFullInvalidationEvent();
+// res.userId = MarshallUtil.unmarshallString(input);
+// res.username = MarshallUtil.unmarshallString(input);
+// res.email = MarshallUtil.unmarshallString(input);
+// res.realmId = MarshallUtil.unmarshallString(input);
+// res.identityFederationEnabled = input.readBoolean();
+// res.federatedIdentities = KeycloakMarshallUtil.readMap(input, KeycloakMarshallUtil.STRING_EXT, KeycloakMarshallUtil.STRING_EXT, HashMap::new);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserUpdatedEvent.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserUpdatedEvent.java
index 0292653..d06bf6a 100644
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserUpdatedEvent.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/events/UserUpdatedEvent.java
@@ -1,99 +1,99 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan.events;
-
-import java.util.Set;
-
-import org.keycloak.models.cache.infinispan.UserCacheManager;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import org.infinispan.commons.marshall.Externalizer;
-import org.infinispan.commons.marshall.MarshallUtil;
-import org.infinispan.commons.marshall.SerializeWith;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@SerializeWith(UserUpdatedEvent.ExternalizerImpl.class)
-public class UserUpdatedEvent extends InvalidationEvent implements UserCacheInvalidationEvent {
-
- private String userId;
- private String username;
- private String email;
- private String realmId;
-
- public static UserUpdatedEvent create(String userId, String username, String email, String realmId) {
- UserUpdatedEvent event = new UserUpdatedEvent();
- event.userId = userId;
- event.username = username;
- event.email = email;
- event.realmId = realmId;
- return event;
- }
-
- @Override
- public String getId() {
- return userId;
- }
-
- @Override
- public String toString() {
- return String.format("UserUpdatedEvent [ userId=%s, username=%s, email=%s ]", userId, username, email);
- }
-
- @Override
- public void addInvalidations(UserCacheManager userCache, Set<String> invalidations) {
- userCache.userUpdatedInvalidations(userId, username, email, realmId, invalidations);
- }
-
- public static class ExternalizerImpl implements Externalizer<UserUpdatedEvent> {
-
- private static final int VERSION_1 = 1;
-
- @Override
- public void writeObject(ObjectOutput output, UserUpdatedEvent obj) throws IOException {
- output.writeByte(VERSION_1);
-
- MarshallUtil.marshallString(obj.userId, output);
- MarshallUtil.marshallString(obj.username, output);
- MarshallUtil.marshallString(obj.email, output);
- MarshallUtil.marshallString(obj.realmId, output);
- }
-
- @Override
- public UserUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
- switch (input.readByte()) {
- case VERSION_1:
- return readObjectVersion1(input);
- default:
- throw new IOException("Unknown version");
- }
- }
-
- public UserUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
- UserUpdatedEvent res = new UserUpdatedEvent();
- res.userId = MarshallUtil.unmarshallString(input);
- res.username = MarshallUtil.unmarshallString(input);
- res.email = MarshallUtil.unmarshallString(input);
- res.realmId = MarshallUtil.unmarshallString(input);
-
- return res;
- }
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan.events;
+
+// import java.util.Set;
+
+// import org.keycloak.models.cache.infinispan.UserCacheManager;
+// import java.io.IOException;
+// import java.io.ObjectInput;
+// import java.io.ObjectOutput;
+// import org.infinispan.commons.marshall.Externalizer;
+// import org.infinispan.commons.marshall.MarshallUtil;
+// import org.infinispan.commons.marshall.SerializeWith;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @SerializeWith(UserUpdatedEvent.ExternalizerImpl.class)
+// public class UserUpdatedEvent extends InvalidationEvent implements UserCacheInvalidationEvent {
+
+// private String userId;
+// private String username;
+// private String email;
+// private String realmId;
+
+// public static UserUpdatedEvent create(String userId, String username, String email, String realmId) {
+// UserUpdatedEvent event = new UserUpdatedEvent();
+// event.userId = userId;
+// event.username = username;
+// event.email = email;
+// event.realmId = realmId;
+// return event;
+// }
+
+// @Override
+// public String getId() {
+// return userId;
+// }
+
+// @Override
+// public String toString() {
+// return String.format("UserUpdatedEvent [ userId=%s, username=%s, email=%s ]", userId, username, email);
+// }
+
+// @Override
+// public void addInvalidations(UserCacheManager userCache, Set<String> invalidations) {
+// userCache.userUpdatedInvalidations(userId, username, email, realmId, invalidations);
+// }
+
+// public static class ExternalizerImpl implements Externalizer<UserUpdatedEvent> {
+
+// private static final int VERSION_1 = 1;
+
+// @Override
+// public void writeObject(ObjectOutput output, UserUpdatedEvent obj) throws IOException {
+// output.writeByte(VERSION_1);
+
+// MarshallUtil.marshallString(obj.userId, output);
+// MarshallUtil.marshallString(obj.username, output);
+// MarshallUtil.marshallString(obj.email, output);
+// MarshallUtil.marshallString(obj.realmId, output);
+// }
+
+// @Override
+// public UserUpdatedEvent readObject(ObjectInput input) throws IOException, ClassNotFoundException {
+// switch (input.readByte()) {
+// case VERSION_1:
+// return readObjectVersion1(input);
+// default:
+// throw new IOException("Unknown version");
+// }
+// }
+
+// public UserUpdatedEvent readObjectVersion1(ObjectInput input) throws IOException, ClassNotFoundException {
+// UserUpdatedEvent res = new UserUpdatedEvent();
+// res.userId = MarshallUtil.unmarshallString(input);
+// res.username = MarshallUtil.unmarshallString(input);
+// res.email = MarshallUtil.unmarshallString(input);
+// res.realmId = MarshallUtil.unmarshallString(input);
+
+// return res;
+// }
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/GroupAdapter.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/GroupAdapter.java
index 6a35951..bf7b374 100755
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/GroupAdapter.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/GroupAdapter.java
@@ -1,278 +1,278 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan;
-
-import org.keycloak.models.ClientModel;
-import org.keycloak.models.GroupModel;
-import org.keycloak.models.KeycloakSession;
-import org.keycloak.models.RealmModel;
-import org.keycloak.models.RoleContainerModel;
-import org.keycloak.models.RoleModel;
-import org.keycloak.models.cache.infinispan.entities.CachedGroup;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.function.Supplier;
-
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class GroupAdapter implements GroupModel {
-
- protected final CachedGroup cached;
- protected final RealmCacheSession cacheSession;
- protected final KeycloakSession keycloakSession;
- protected final RealmModel realm;
- private final Supplier<GroupModel> modelSupplier;
- protected volatile GroupModel updated;
-
- public GroupAdapter(CachedGroup cached, RealmCacheSession cacheSession, KeycloakSession keycloakSession, RealmModel realm) {
- this.cached = cached;
- this.cacheSession = cacheSession;
- this.keycloakSession = keycloakSession;
- this.realm = realm;
- modelSupplier = this::getGroupModel;
- }
-
- protected void getDelegateForUpdate() {
- if (updated == null) {
- cacheSession.registerGroupInvalidation(cached.getId());
- updated = modelSupplier.get();
- if (updated == null) throw new IllegalStateException("Not found in database");
- }
- }
-
- protected volatile boolean invalidated;
- public void invalidate() {
- invalidated = true;
- }
-
- protected boolean isUpdated() {
- if (updated != null) return true;
- if (!invalidated) return false;
- updated = cacheSession.getRealmDelegate().getGroupById(cached.getId(), realm);
- if (updated == null) throw new IllegalStateException("Not found in database");
- return true;
- }
-
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || !(o instanceof GroupModel)) return false;
-
- GroupModel that = (GroupModel) o;
-
- if (!cached.getId().equals(that.getId())) return false;
-
- return true;
- }
-
- @Override
- public int hashCode() {
- return cached.getId().hashCode();
- }
-
- @Override
- public String getId() {
- if (isUpdated()) return updated.getId();
- return cached.getId();
- }
-
- @Override
- public String getName() {
- if (isUpdated()) return updated.getName();
- return cached.getName();
- }
-
- @Override
- public void setName(String name) {
- getDelegateForUpdate();
- updated.setName(name);
-
- }
-
- @Override
- public void setSingleAttribute(String name, String value) {
- getDelegateForUpdate();
- updated.setSingleAttribute(name, value);
- }
-
- @Override
- public void setAttribute(String name, List<String> values) {
- getDelegateForUpdate();
- updated.setAttribute(name, values);
- }
-
- @Override
- public void removeAttribute(String name) {
- getDelegateForUpdate();
- updated.removeAttribute(name);
-
- }
-
- @Override
- public String getFirstAttribute(String name) {
- if (isUpdated()) return updated.getFirstAttribute(name);
- return cached.getAttributes(modelSupplier).getFirst(name);
- }
-
- @Override
- public List<String> getAttribute(String name) {
- List<String> values = cached.getAttributes(modelSupplier).get(name);
- if (values == null) return null;
- return values;
- }
-
- @Override
- public Map<String, List<String>> getAttributes() {
- return cached.getAttributes(modelSupplier);
- }
-
- @Override
- public Set<RoleModel> getRealmRoleMappings() {
- if (isUpdated()) return updated.getRealmRoleMappings();
- Set<RoleModel> roleMappings = getRoleMappings();
- Set<RoleModel> realmMappings = new HashSet<RoleModel>();
- for (RoleModel role : roleMappings) {
- RoleContainerModel container = role.getContainer();
- if (container instanceof RealmModel) {
- if (((RealmModel) container).getId().equals(realm.getId())) {
- realmMappings.add(role);
- }
- }
- }
- return realmMappings;
- }
-
- @Override
- public Set<RoleModel> getClientRoleMappings(ClientModel app) {
- if (isUpdated()) return updated.getClientRoleMappings(app);
- Set<RoleModel> roleMappings = getRoleMappings();
- Set<RoleModel> appMappings = new HashSet<RoleModel>();
- for (RoleModel role : roleMappings) {
- RoleContainerModel container = role.getContainer();
- if (container instanceof ClientModel) {
- if (((ClientModel) container).getId().equals(app.getId())) {
- appMappings.add(role);
- }
- }
- }
- return appMappings;
- }
-
- @Override
- public boolean hasRole(RoleModel role) {
- if (isUpdated()) return updated.hasRole(role);
- if (cached.getRoleMappings(modelSupplier).contains(role.getId())) return true;
-
- Set<RoleModel> mappings = getRoleMappings();
- for (RoleModel mapping: mappings) {
- if (mapping.hasRole(role)) return true;
- }
- return false;
- }
-
- @Override
- public void grantRole(RoleModel role) {
- getDelegateForUpdate();
- updated.grantRole(role);
- }
-
- @Override
- public Set<RoleModel> getRoleMappings() {
- if (isUpdated()) return updated.getRoleMappings();
- Set<RoleModel> roles = new HashSet<RoleModel>();
- for (String id : cached.getRoleMappings(modelSupplier)) {
- RoleModel roleById = keycloakSession.realms().getRoleById(id, realm);
- if (roleById == null) {
- // chance that role was removed, so just delegate to persistence and get user invalidated
- getDelegateForUpdate();
- return updated.getRoleMappings();
- }
- roles.add(roleById);
-
- }
- return roles;
- }
-
- @Override
- public void deleteRoleMapping(RoleModel role) {
- getDelegateForUpdate();
- updated.deleteRoleMapping(role);
- }
-
- @Override
- public GroupModel getParent() {
- if (isUpdated()) return updated.getParent();
- if (cached.getParentId() == null) return null;
- return keycloakSession.realms().getGroupById(cached.getParentId(), realm);
- }
-
- @Override
- public String getParentId() {
- if (isUpdated()) return updated.getParentId();
- return cached.getParentId();
- }
-
- @Override
- public Set<GroupModel> getSubGroups() {
- if (isUpdated()) return updated.getSubGroups();
- Set<GroupModel> subGroups = new HashSet<>();
- for (String id : cached.getSubGroups(modelSupplier)) {
- GroupModel subGroup = keycloakSession.realms().getGroupById(id, realm);
- if (subGroup == null) {
- // chance that role was removed, so just delegate to persistence and get user invalidated
- getDelegateForUpdate();
- return updated.getSubGroups();
-
- }
- subGroups.add(subGroup);
- }
- return subGroups;
- }
-
-
-
- @Override
- public void setParent(GroupModel group) {
- getDelegateForUpdate();
- updated.setParent(group);
-
- }
-
- @Override
- public void addChild(GroupModel subGroup) {
- getDelegateForUpdate();
- updated.addChild(subGroup);
-
- }
-
- @Override
- public void removeChild(GroupModel subGroup) {
- getDelegateForUpdate();
- updated.removeChild(subGroup);
- }
-
- private GroupModel getGroupModel() {
- return cacheSession.getRealmDelegate().getGroupById(cached.getId(), realm);
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan;
+
+// import org.keycloak.models.ClientModel;
+// import org.keycloak.models.GroupModel;
+// import org.keycloak.models.KeycloakSession;
+// import org.keycloak.models.RealmModel;
+// import org.keycloak.models.RoleContainerModel;
+// import org.keycloak.models.RoleModel;
+// import org.keycloak.models.cache.infinispan.entities.CachedGroup;
+
+// import java.util.HashSet;
+// import java.util.List;
+// import java.util.Map;
+// import java.util.Set;
+// import java.util.function.Supplier;
+
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public class GroupAdapter implements GroupModel {
+
+// protected final CachedGroup cached;
+// protected final RealmCacheSession cacheSession;
+// protected final KeycloakSession keycloakSession;
+// protected final RealmModel realm;
+// private final Supplier<GroupModel> modelSupplier;
+// protected volatile GroupModel updated;
+
+// public GroupAdapter(CachedGroup cached, Object cacheSession, KeycloakSession keycloakSession, RealmModel realm) {
+// this.cached = cached;
+// this.cacheSession = cacheSession;
+// this.keycloakSession = keycloakSession;
+// this.realm = realm;
+// modelSupplier = this::getGroupModel;
+// }
+
+// protected void getDelegateForUpdate() {
+// if (updated == null) {
+// cacheSession.registerGroupInvalidation(cached.getId());
+// updated = modelSupplier.get();
+// if (updated == null) throw new IllegalStateException("Not found in database");
+// }
+// }
+
+// protected volatile boolean invalidated;
+// public void invalidate() {
+// invalidated = true;
+// }
+
+// protected boolean isUpdated() {
+// if (updated != null) return true;
+// if (!invalidated) return false;
+// updated = cacheSession.getRealmDelegate().getGroupById(cached.getId(), realm);
+// if (updated == null) throw new IllegalStateException("Not found in database");
+// return true;
+// }
+
+
+// @Override
+// public boolean equals(Object o) {
+// if (this == o) return true;
+// if (o == null || !(o instanceof GroupModel)) return false;
+
+// GroupModel that = (GroupModel) o;
+
+// if (!cached.getId().equals(that.getId())) return false;
+
+// return true;
+// }
+
+// @Override
+// public int hashCode() {
+// return cached.getId().hashCode();
+// }
+
+// @Override
+// public String getId() {
+// if (isUpdated()) return updated.getId();
+// return cached.getId();
+// }
+
+// @Override
+// public String getName() {
+// if (isUpdated()) return updated.getName();
+// return cached.getName();
+// }
+
+// @Override
+// public void setName(String name) {
+// getDelegateForUpdate();
+// updated.setName(name);
+
+// }
+
+// @Override
+// public void setSingleAttribute(String name, String value) {
+// getDelegateForUpdate();
+// updated.setSingleAttribute(name, value);
+// }
+
+// @Override
+// public void setAttribute(String name, List<String> values) {
+// getDelegateForUpdate();
+// updated.setAttribute(name, values);
+// }
+
+// @Override
+// public void removeAttribute(String name) {
+// getDelegateForUpdate();
+// updated.removeAttribute(name);
+
+// }
+
+// @Override
+// public String getFirstAttribute(String name) {
+// if (isUpdated()) return updated.getFirstAttribute(name);
+// return cached.getAttributes(modelSupplier).getFirst(name);
+// }
+
+// @Override
+// public List<String> getAttribute(String name) {
+// List<String> values = cached.getAttributes(modelSupplier).get(name);
+// if (values == null) return null;
+// return values;
+// }
+
+// @Override
+// public Map<String, List<String>> getAttributes() {
+// return cached.getAttributes(modelSupplier);
+// }
+
+// @Override
+// public Set<RoleModel> getRealmRoleMappings() {
+// if (isUpdated()) return updated.getRealmRoleMappings();
+// Set<RoleModel> roleMappings = getRoleMappings();
+// Set<RoleModel> realmMappings = new HashSet<RoleModel>();
+// for (RoleModel role : roleMappings) {
+// RoleContainerModel container = role.getContainer();
+// if (container instanceof RealmModel) {
+// if (((RealmModel) container).getId().equals(realm.getId())) {
+// realmMappings.add(role);
+// }
+// }
+// }
+// return realmMappings;
+// }
+
+// @Override
+// public Set<RoleModel> getClientRoleMappings(ClientModel app) {
+// if (isUpdated()) return updated.getClientRoleMappings(app);
+// Set<RoleModel> roleMappings = getRoleMappings();
+// Set<RoleModel> appMappings = new HashSet<RoleModel>();
+// for (RoleModel role : roleMappings) {
+// RoleContainerModel container = role.getContainer();
+// if (container instanceof ClientModel) {
+// if (((ClientModel) container).getId().equals(app.getId())) {
+// appMappings.add(role);
+// }
+// }
+// }
+// return appMappings;
+// }
+
+// @Override
+// public boolean hasRole(RoleModel role) {
+// if (isUpdated()) return updated.hasRole(role);
+// if (cached.getRoleMappings(modelSupplier).contains(role.getId())) return true;
+
+// Set<RoleModel> mappings = getRoleMappings();
+// for (RoleModel mapping: mappings) {
+// if (mapping.hasRole(role)) return true;
+// }
+// return false;
+// }
+
+// @Override
+// public void grantRole(RoleModel role) {
+// getDelegateForUpdate();
+// updated.grantRole(role);
+// }
+
+// @Override
+// public Set<RoleModel> getRoleMappings() {
+// if (isUpdated()) return updated.getRoleMappings();
+// Set<RoleModel> roles = new HashSet<RoleModel>();
+// for (String id : cached.getRoleMappings(modelSupplier)) {
+// RoleModel roleById = keycloakSession.realms().getRoleById(id, realm);
+// if (roleById == null) {
+// // chance that role was removed, so just delegate to persistence and get user invalidated
+// getDelegateForUpdate();
+// return updated.getRoleMappings();
+// }
+// roles.add(roleById);
+
+// }
+// return roles;
+// }
+
+// @Override
+// public void deleteRoleMapping(RoleModel role) {
+// getDelegateForUpdate();
+// updated.deleteRoleMapping(role);
+// }
+
+// @Override
+// public GroupModel getParent() {
+// if (isUpdated()) return updated.getParent();
+// if (cached.getParentId() == null) return null;
+// return keycloakSession.realms().getGroupById(cached.getParentId(), realm);
+// }
+
+// @Override
+// public String getParentId() {
+// if (isUpdated()) return updated.getParentId();
+// return cached.getParentId();
+// }
+
+// @Override
+// public Set<GroupModel> getSubGroups() {
+// if (isUpdated()) return updated.getSubGroups();
+// Set<GroupModel> subGroups = new HashSet<>();
+// for (String id : cached.getSubGroups(modelSupplier)) {
+// GroupModel subGroup = keycloakSession.realms().getGroupById(id, realm);
+// if (subGroup == null) {
+// // chance that role was removed, so just delegate to persistence and get user invalidated
+// getDelegateForUpdate();
+// return updated.getSubGroups();
+
+// }
+// subGroups.add(subGroup);
+// }
+// return subGroups;
+// }
+
+
+
+// @Override
+// public void setParent(GroupModel group) {
+// getDelegateForUpdate();
+// updated.setParent(group);
+
+// }
+
+// @Override
+// public void addChild(GroupModel subGroup) {
+// getDelegateForUpdate();
+// updated.addChild(subGroup);
+
+// }
+
+// @Override
+// public void removeChild(GroupModel subGroup) {
+// getDelegateForUpdate();
+// updated.removeChild(subGroup);
+// }
+
+// private GroupModel getGroupModel() {
+// return cacheSession.getRealmDelegate().getGroupById(cached.getId(), realm);
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/InfinispanCacheRealmProviderFactory.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/InfinispanCacheRealmProviderFactory.java
index ef2ce2b..65726e8 100755
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/InfinispanCacheRealmProviderFactory.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/InfinispanCacheRealmProviderFactory.java
@@ -1,97 +1,97 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan;
-
-import org.infinispan.Cache;
-import org.jboss.logging.Logger;
-import org.keycloak.Config;
-import org.keycloak.cluster.ClusterEvent;
-import org.keycloak.cluster.ClusterProvider;
-import org.keycloak.connections.infinispan.InfinispanConnectionProvider;
-import org.keycloak.models.KeycloakSession;
-import org.keycloak.models.KeycloakSessionFactory;
-import org.keycloak.models.cache.CacheRealmProvider;
-import org.keycloak.models.cache.CacheRealmProviderFactory;
-import org.keycloak.models.cache.infinispan.entities.Revisioned;
-import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
-
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
- */
-public class InfinispanCacheRealmProviderFactory implements CacheRealmProviderFactory {
-
- private static final Logger log = Logger.getLogger(InfinispanCacheRealmProviderFactory.class);
- public static final String REALM_CLEAR_CACHE_EVENTS = "REALM_CLEAR_CACHE_EVENTS";
- public static final String REALM_INVALIDATION_EVENTS = "REALM_INVALIDATION_EVENTS";
-
- protected volatile RealmCacheManager realmCache;
-
- @Override
- public CacheRealmProvider create(KeycloakSession session) {
- lazyInit(session);
- return new RealmCacheSession(realmCache, session);
- }
-
- private void lazyInit(KeycloakSession session) {
- if (realmCache == null) {
- synchronized (this) {
- if (realmCache == null) {
- Cache<String, Revisioned> cache = session.getProvider(InfinispanConnectionProvider.class).getCache(InfinispanConnectionProvider.REALM_CACHE_NAME);
- Cache<String, Long> revisions = session.getProvider(InfinispanConnectionProvider.class).getCache(InfinispanConnectionProvider.REALM_REVISIONS_CACHE_NAME);
- realmCache = new RealmCacheManager(cache, revisions);
-
- ClusterProvider cluster = session.getProvider(ClusterProvider.class);
- cluster.registerListener(REALM_INVALIDATION_EVENTS, (ClusterEvent event) -> {
-
- InvalidationEvent invalidationEvent = (InvalidationEvent) event;
- realmCache.invalidationEventReceived(invalidationEvent);
-
- });
-
- cluster.registerListener(REALM_CLEAR_CACHE_EVENTS, (ClusterEvent event) -> {
-
- realmCache.clear();
-
- });
-
- log.debug("Registered cluster listeners");
- }
- }
- }
- }
-
- @Override
- public void init(Config.Scope config) {
- }
-
- @Override
- public void postInit(KeycloakSessionFactory factory) {
-
- }
-
- @Override
- public void close() {
- }
-
- @Override
- public String getId() {
- return "default";
- }
-
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan;
+
+// import org.infinispan.Cache;
+// import org.jboss.logging.Logger;
+// import org.keycloak.Config;
+// import org.keycloak.cluster.ClusterEvent;
+// import org.keycloak.cluster.ClusterProvider;
+// import org.keycloak.connections.infinispan.InfinispanConnectionProvider;
+// import org.keycloak.models.KeycloakSession;
+// import org.keycloak.models.KeycloakSessionFactory;
+// import org.keycloak.models.cache.CacheRealmProvider;
+// import org.keycloak.models.cache.CacheRealmProviderFactory;
+// import org.keycloak.models.cache.infinispan.entities.Revisioned;
+// import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
+
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
+// */
+// public class InfinispanCacheRealmProviderFactory implements CacheRealmProviderFactory {
+
+// private static final Logger log = Logger.getLogger(InfinispanCacheRealmProviderFactory.class);
+// public static final String REALM_CLEAR_CACHE_EVENTS = "REALM_CLEAR_CACHE_EVENTS";
+// public static final String REALM_INVALIDATION_EVENTS = "REALM_INVALIDATION_EVENTS";
+
+// protected volatile RealmCacheManager realmCache;
+
+// @Override
+// public CacheRealmProvider create(KeycloakSession session) {
+// lazyInit(session);
+// return new RealmCacheSession(realmCache, session);
+// }
+
+// private void lazyInit(KeycloakSession session) {
+// if (realmCache == null) {
+// synchronized (this) {
+// if (realmCache == null) {
+// Cache<String, Revisioned> cache = session.getProvider(InfinispanConnectionProvider.class).getCache(InfinispanConnectionProvider.REALM_CACHE_NAME);
+// Cache<String, Long> revisions = session.getProvider(InfinispanConnectionProvider.class).getCache(InfinispanConnectionProvider.REALM_REVISIONS_CACHE_NAME);
+// realmCache = new RealmCacheManager(cache, revisions);
+
+// ClusterProvider cluster = session.getProvider(ClusterProvider.class);
+// cluster.registerListener(REALM_INVALIDATION_EVENTS, (ClusterEvent event) -> {
+
+// InvalidationEvent invalidationEvent = (InvalidationEvent) event;
+// realmCache.invalidationEventReceived(invalidationEvent);
+
+// });
+
+// cluster.registerListener(REALM_CLEAR_CACHE_EVENTS, (ClusterEvent event) -> {
+
+// realmCache.clear();
+
+// });
+
+// log.debug("Registered cluster listeners");
+// }
+// }
+// }
+// }
+
+// @Override
+// public void init(Config.Scope config) {
+// }
+
+// @Override
+// public void postInit(KeycloakSessionFactory factory) {
+
+// }
+
+// @Override
+// public void close() {
+// }
+
+// @Override
+// public String getId() {
+// return "default";
+// }
+
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/InfinispanUserCacheProviderFactory.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/InfinispanUserCacheProviderFactory.java
index 4d0f445..22a4c2f 100755
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/InfinispanUserCacheProviderFactory.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/InfinispanUserCacheProviderFactory.java
@@ -1,100 +1,100 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan;
-
-import org.infinispan.Cache;
-import org.jboss.logging.Logger;
-import org.keycloak.Config;
-import org.keycloak.cluster.ClusterEvent;
-import org.keycloak.cluster.ClusterProvider;
-import org.keycloak.connections.infinispan.InfinispanConnectionProvider;
-import org.keycloak.models.KeycloakSession;
-import org.keycloak.models.KeycloakSessionFactory;
-import org.keycloak.models.cache.UserCache;
-import org.keycloak.models.cache.UserCacheProviderFactory;
-import org.keycloak.models.cache.infinispan.entities.Revisioned;
-import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
-
-/**
- * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
- */
-public class InfinispanUserCacheProviderFactory implements UserCacheProviderFactory {
-
- private static final Logger log = Logger.getLogger(InfinispanUserCacheProviderFactory.class);
- public static final String USER_CLEAR_CACHE_EVENTS = "USER_CLEAR_CACHE_EVENTS";
- public static final String USER_INVALIDATION_EVENTS = "USER_INVALIDATION_EVENTS";
-
- protected volatile UserCacheManager userCache;
-
-
-
- @Override
- public UserCache create(KeycloakSession session) {
- lazyInit(session);
- return new UserCacheSession(userCache, session);
- }
-
- private void lazyInit(KeycloakSession session) {
- if (userCache == null) {
- synchronized (this) {
- if (userCache == null) {
- Cache<String, Revisioned> cache = session.getProvider(InfinispanConnectionProvider.class).getCache(InfinispanConnectionProvider.USER_CACHE_NAME);
- Cache<String, Long> revisions = session.getProvider(InfinispanConnectionProvider.class).getCache(InfinispanConnectionProvider.USER_REVISIONS_CACHE_NAME);
- userCache = new UserCacheManager(cache, revisions);
-
- ClusterProvider cluster = session.getProvider(ClusterProvider.class);
-
- cluster.registerListener(USER_INVALIDATION_EVENTS, (ClusterEvent event) -> {
-
- InvalidationEvent invalidationEvent = (InvalidationEvent) event;
- userCache.invalidationEventReceived(invalidationEvent);
-
- });
-
- cluster.registerListener(USER_CLEAR_CACHE_EVENTS, (ClusterEvent event) -> {
-
- userCache.clear();
-
- });
-
- log.debug("Registered cluster listeners");
- }
- }
- }
- }
-
- @Override
- public void init(Config.Scope config) {
- }
-
- @Override
- public void postInit(KeycloakSessionFactory factory) {
-
- }
-
- @Override
- public void close() {
- }
-
- @Override
- public String getId() {
- return "default";
- }
-
-
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan;
+
+// import org.infinispan.Cache;
+// import org.jboss.logging.Logger;
+// import org.keycloak.Config;
+// import org.keycloak.cluster.ClusterEvent;
+// import org.keycloak.cluster.ClusterProvider;
+// import org.keycloak.connections.infinispan.InfinispanConnectionProvider;
+// import org.keycloak.models.KeycloakSession;
+// import org.keycloak.models.KeycloakSessionFactory;
+// import org.keycloak.models.cache.UserCache;
+// import org.keycloak.models.cache.UserCacheProviderFactory;
+// import org.keycloak.models.cache.infinispan.entities.Revisioned;
+// import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
+
+// /**
+// * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
+// */
+// public class InfinispanUserCacheProviderFactory implements UserCacheProviderFactory {
+
+// private static final Logger log = Logger.getLogger(InfinispanUserCacheProviderFactory.class);
+// public static final String USER_CLEAR_CACHE_EVENTS = "USER_CLEAR_CACHE_EVENTS";
+// public static final String USER_INVALIDATION_EVENTS = "USER_INVALIDATION_EVENTS";
+
+// protected volatile UserCacheManager userCache;
+
+
+
+// @Override
+// public UserCache create(KeycloakSession session) {
+// lazyInit(session);
+// return new UserCacheSession(userCache, session);
+// }
+
+// private void lazyInit(KeycloakSession session) {
+// if (userCache == null) {
+// synchronized (this) {
+// if (userCache == null) {
+// Cache<String, Revisioned> cache = session.getProvider(InfinispanConnectionProvider.class).getCache(InfinispanConnectionProvider.USER_CACHE_NAME);
+// Cache<String, Long> revisions = session.getProvider(InfinispanConnectionProvider.class).getCache(InfinispanConnectionProvider.USER_REVISIONS_CACHE_NAME);
+// userCache = new UserCacheManager(cache, revisions);
+
+// ClusterProvider cluster = session.getProvider(ClusterProvider.class);
+
+// cluster.registerListener(USER_INVALIDATION_EVENTS, (ClusterEvent event) -> {
+
+// InvalidationEvent invalidationEvent = (InvalidationEvent) event;
+// userCache.invalidationEventReceived(invalidationEvent);
+
+// });
+
+// cluster.registerListener(USER_CLEAR_CACHE_EVENTS, (ClusterEvent event) -> {
+
+// userCache.clear();
+
+// });
+
+// log.debug("Registered cluster listeners");
+// }
+// }
+// }
+// }
+
+// @Override
+// public void init(Config.Scope config) {
+// }
+
+// @Override
+// public void postInit(KeycloakSessionFactory factory) {
+
+// }
+
+// @Override
+// public void close() {
+// }
+
+// @Override
+// public String getId() {
+// return "default";
+// }
+
+
+// }
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 62aee89..9ad7a1a 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
@@ -1,1572 +1,1572 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan;
-
-import org.keycloak.Config;
-import org.keycloak.common.enums.SslRequired;
-import org.keycloak.component.ComponentModel;
-import org.keycloak.models.*;
-import org.keycloak.models.cache.CachedRealmModel;
-import org.keycloak.models.cache.infinispan.entities.CachedRealm;
-import org.keycloak.storage.UserStorageProvider;
-import org.keycloak.storage.client.ClientStorageProvider;
-
-import java.util.*;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class RealmAdapter implements CachedRealmModel {
- protected CachedRealm cached;
- protected RealmCacheSession cacheSession;
- protected volatile RealmModel updated;
- protected KeycloakSession session;
-
- public RealmAdapter(KeycloakSession session, CachedRealm cached, RealmCacheSession cacheSession) {
- this.cached = cached;
- this.cacheSession = cacheSession;
- this.session = session;
- }
-
- @Override
- public RealmModel getDelegateForUpdate() {
- if (updated == null) {
- cacheSession.registerRealmInvalidation(cached.getId(), cached.getName());
- updated = cacheSession.getRealmDelegate().getRealm(cached.getId());
- if (updated == null) throw new IllegalStateException("Not found in database");
- }
- return updated;
- }
-
- protected volatile boolean invalidated;
-
- protected void invalidateFlag() {
- invalidated = true;
-
- }
-
- @Override
- public void invalidate() {
- invalidated = true;
- getDelegateForUpdate();
- }
-
- @Override
- public long getCacheTimestamp() {
- return cached.getCacheTimestamp();
- }
-
- @Override
- public ConcurrentHashMap getCachedWith() {
- return cached.getCachedWith();
- }
-
- protected boolean isUpdated() {
- if (updated != null) return true;
- if (!invalidated) return false;
- updated = cacheSession.getRealmDelegate().getRealm(cached.getId());
- if (updated == null) throw new IllegalStateException("Not found in database");
- return true;
- }
-
-
- @Override
- public String getId() {
- if (isUpdated()) return updated.getId();
- return cached.getId();
- }
-
- @Override
- public String getName() {
- if (isUpdated()) return updated.getName();
- return cached.getName();
- }
-
- @Override
- public void setName(String name) {
- getDelegateForUpdate();
- updated.setName(name);
- }
-
- @Override
- public String getDisplayName() {
- if (isUpdated()) return updated.getDisplayName();
- return cached.getDisplayName();
- }
-
- @Override
- public void setDisplayName(String displayName) {
- getDelegateForUpdate();
- updated.setDisplayName(displayName);
- }
-
- @Override
- public String getDisplayNameHtml() {
- if (isUpdated()) return updated.getDisplayNameHtml();
- return cached.getDisplayNameHtml();
- }
-
- @Override
- public void setDisplayNameHtml(String displayNameHtml) {
- getDelegateForUpdate();
- updated.setDisplayNameHtml(displayNameHtml);
- }
-
- @Override
- public boolean isEnabled() {
- if (isUpdated()) return updated.isEnabled();
- return cached.isEnabled();
- }
-
- @Override
- public void setEnabled(boolean enabled) {
- getDelegateForUpdate();
- updated.setEnabled(enabled);
- }
-
- @Override
- public boolean isUserManagedAccessAllowed() {
- if (isUpdated()) return updated.isEnabled();
- return cached.isAllowUserManagedAccess();
- }
-
- @Override
- public void setUserManagedAccessAllowed(boolean userManagedAccessAllowed) {
- getDelegateForUpdate();
- updated.setUserManagedAccessAllowed(userManagedAccessAllowed);
- }
-
- @Override
- public SslRequired getSslRequired() {
- if (isUpdated()) return updated.getSslRequired();
- return cached.getSslRequired();
- }
-
- @Override
- public void setSslRequired(SslRequired sslRequired) {
- getDelegateForUpdate();
- updated.setSslRequired(sslRequired);
- }
-
- @Override
- public boolean isRegistrationAllowed() {
- if (isUpdated()) return updated.isRegistrationAllowed();
- return cached.isRegistrationAllowed();
- }
-
- @Override
- public void setRegistrationAllowed(boolean registrationAllowed) {
- getDelegateForUpdate();
- updated.setRegistrationAllowed(registrationAllowed);
- }
-
- @Override
- public boolean isRegistrationEmailAsUsername() {
- if (isUpdated()) return updated.isRegistrationEmailAsUsername();
- return cached.isRegistrationEmailAsUsername();
- }
-
- @Override
- public void setRegistrationEmailAsUsername(boolean registrationEmailAsUsername) {
- getDelegateForUpdate();
- updated.setRegistrationEmailAsUsername(registrationEmailAsUsername);
- }
-
- @Override
- public boolean isRememberMe() {
- if (isUpdated()) return updated.isRememberMe();
- return cached.isRememberMe();
- }
-
- @Override
- public void setRememberMe(boolean rememberMe) {
- getDelegateForUpdate();
- updated.setRememberMe(rememberMe);
- }
-
- @Override
- public String getDefaultSignatureAlgorithm() {
- if(isUpdated()) return updated.getDefaultSignatureAlgorithm();
- return cached.getDefaultSignatureAlgorithm();
- }
-
- @Override
- public void setDefaultSignatureAlgorithm(String defaultSignatureAlgorithm) {
- getDelegateForUpdate();
- updated.setDefaultSignatureAlgorithm(defaultSignatureAlgorithm);
- }
-
- @Override
- public boolean isBruteForceProtected() {
- if (isUpdated()) return updated.isBruteForceProtected();
- return cached.isBruteForceProtected();
- }
-
- @Override
- public void setBruteForceProtected(boolean value) {
- getDelegateForUpdate();
- updated.setBruteForceProtected(value);
- }
-
- @Override
- public boolean isPermanentLockout() {
- if(isUpdated()) return updated.isPermanentLockout();
- return cached.isPermanentLockout();
- }
-
- @Override
- public void setPermanentLockout(final boolean val) {
- getDelegateForUpdate();
- updated.setPermanentLockout(val);
- }
-
- @Override
- public int getMaxFailureWaitSeconds() {
- if (isUpdated()) return updated.getMaxFailureWaitSeconds();
- return cached.getMaxFailureWaitSeconds();
- }
-
- @Override
- public void setMaxFailureWaitSeconds(int val) {
- getDelegateForUpdate();
- updated.setMaxFailureWaitSeconds(val);
- }
-
- @Override
- public int getWaitIncrementSeconds() {
- if (isUpdated()) return updated.getWaitIncrementSeconds();
- return cached.getWaitIncrementSeconds();
- }
-
- @Override
- public void setWaitIncrementSeconds(int val) {
- getDelegateForUpdate();
- updated.setWaitIncrementSeconds(val);
- }
-
- @Override
- public int getMinimumQuickLoginWaitSeconds() {
- if (isUpdated()) return updated.getMinimumQuickLoginWaitSeconds();
- return cached.getMinimumQuickLoginWaitSeconds();
- }
-
- @Override
- public void setMinimumQuickLoginWaitSeconds(int val) {
- getDelegateForUpdate();
- updated.setMinimumQuickLoginWaitSeconds(val);
- }
-
- @Override
- public long getQuickLoginCheckMilliSeconds() {
- if (isUpdated()) return updated.getQuickLoginCheckMilliSeconds();
- return cached.getQuickLoginCheckMilliSeconds();
- }
-
- @Override
- public void setQuickLoginCheckMilliSeconds(long val) {
- getDelegateForUpdate();
- updated.setQuickLoginCheckMilliSeconds(val);
- }
-
- @Override
- public int getMaxDeltaTimeSeconds() {
- if (isUpdated()) return updated.getMaxDeltaTimeSeconds();
- return cached.getMaxDeltaTimeSeconds();
- }
-
- @Override
- public void setMaxDeltaTimeSeconds(int val) {
- getDelegateForUpdate();
- updated.setMaxDeltaTimeSeconds(val);
- }
-
- @Override
- public int getFailureFactor() {
- if (isUpdated()) return updated.getFailureFactor();
- return cached.getFailureFactor();
- }
-
- @Override
- public void setFailureFactor(int failureFactor) {
- getDelegateForUpdate();
- updated.setFailureFactor(failureFactor);
- }
-
- @Override
- public boolean isVerifyEmail() {
- if (isUpdated()) return updated.isVerifyEmail();
- return cached.isVerifyEmail();
- }
-
- @Override
- public void setVerifyEmail(boolean verifyEmail) {
- getDelegateForUpdate();
- updated.setVerifyEmail(verifyEmail);
- }
-
- @Override
- public boolean isLoginWithEmailAllowed() {
- if (isUpdated()) return updated.isLoginWithEmailAllowed();
- return cached.isLoginWithEmailAllowed();
- }
-
- @Override
- public void setLoginWithEmailAllowed(boolean loginWithEmailAllowed) {
- getDelegateForUpdate();
- updated.setLoginWithEmailAllowed(loginWithEmailAllowed);
- }
-
- @Override
- public boolean isDuplicateEmailsAllowed() {
- if (isUpdated()) return updated.isDuplicateEmailsAllowed();
- return cached.isDuplicateEmailsAllowed();
- }
-
- @Override
- public void setDuplicateEmailsAllowed(boolean duplicateEmailsAllowed) {
- getDelegateForUpdate();
- updated.setDuplicateEmailsAllowed(duplicateEmailsAllowed);
- }
-
- @Override
- public boolean isResetPasswordAllowed() {
- if (isUpdated()) return updated.isResetPasswordAllowed();
- return cached.isResetPasswordAllowed();
- }
-
- @Override
- public void setResetPasswordAllowed(boolean resetPasswordAllowed) {
- getDelegateForUpdate();
- updated.setResetPasswordAllowed(resetPasswordAllowed);
- }
-
- @Override
- public boolean isEditUsernameAllowed() {
- if (isUpdated()) return updated.isEditUsernameAllowed();
- return cached.isEditUsernameAllowed();
- }
-
- @Override
- public void setEditUsernameAllowed(boolean editUsernameAllowed) {
- getDelegateForUpdate();
- updated.setEditUsernameAllowed(editUsernameAllowed);
- }
-
- @Override
- public boolean isRevokeRefreshToken() {
- if (isUpdated()) return updated.isRevokeRefreshToken();
- return cached.isRevokeRefreshToken();
- }
-
- @Override
- public void setRevokeRefreshToken(boolean revokeRefreshToken) {
- getDelegateForUpdate();
- updated.setRevokeRefreshToken(revokeRefreshToken);
- }
-
- @Override
- public int getRefreshTokenMaxReuse() {
- if (isUpdated()) return updated.getRefreshTokenMaxReuse();
- return cached.getRefreshTokenMaxReuse();
- }
-
- @Override
- public void setRefreshTokenMaxReuse(int refreshTokenMaxReuse) {
- getDelegateForUpdate();
- updated.setRefreshTokenMaxReuse(refreshTokenMaxReuse);
- }
-
- @Override
- public int getSsoSessionIdleTimeout() {
- if (isUpdated()) return updated.getSsoSessionIdleTimeout();
- return cached.getSsoSessionIdleTimeout();
- }
-
- @Override
- public void setSsoSessionIdleTimeout(int seconds) {
- getDelegateForUpdate();
- updated.setSsoSessionIdleTimeout(seconds);
- }
-
- @Override
- public int getSsoSessionMaxLifespan() {
- if (isUpdated()) return updated.getSsoSessionMaxLifespan();
- return cached.getSsoSessionMaxLifespan();
- }
-
- @Override
- public void setSsoSessionMaxLifespan(int seconds) {
- getDelegateForUpdate();
- updated.setSsoSessionMaxLifespan(seconds);
- }
-
- @Override
- public int getSsoSessionIdleTimeoutRememberMe() {
- if (updated != null) return updated.getSsoSessionIdleTimeoutRememberMe();
- return cached.getSsoSessionIdleTimeoutRememberMe();
- }
-
- @Override
- public void setSsoSessionIdleTimeoutRememberMe(int seconds) {
- getDelegateForUpdate();
- updated.setSsoSessionIdleTimeoutRememberMe(seconds);
- }
-
- @Override
- public int getSsoSessionMaxLifespanRememberMe() {
- if (updated != null) return updated.getSsoSessionMaxLifespanRememberMe();
- return cached.getSsoSessionMaxLifespanRememberMe();
- }
-
- @Override
- public void setSsoSessionMaxLifespanRememberMe(int seconds) {
- getDelegateForUpdate();
- updated.setSsoSessionMaxLifespanRememberMe(seconds);
- }
-
- @Override
- public int getOfflineSessionIdleTimeout() {
- if (isUpdated()) return updated.getOfflineSessionIdleTimeout();
- return cached.getOfflineSessionIdleTimeout();
- }
-
-
- @Override
- public void setOfflineSessionIdleTimeout(int seconds) {
- getDelegateForUpdate();
- updated.setOfflineSessionIdleTimeout(seconds);
- }
-
- // KEYCLOAK-7688 Offline Session Max for Offline Token
- @Override
- public boolean isOfflineSessionMaxLifespanEnabled() {
- if (isUpdated()) return updated.isOfflineSessionMaxLifespanEnabled();
- return cached.isOfflineSessionMaxLifespanEnabled();
- }
-
- @Override
- public void setOfflineSessionMaxLifespanEnabled(boolean offlineSessionMaxLifespanEnabled) {
- getDelegateForUpdate();
- updated.setOfflineSessionMaxLifespanEnabled(offlineSessionMaxLifespanEnabled);
- }
-
- @Override
- public int getOfflineSessionMaxLifespan() {
- if (isUpdated()) return updated.getOfflineSessionMaxLifespan();
- return cached.getOfflineSessionMaxLifespan();
- }
-
- @Override
- public void setOfflineSessionMaxLifespan(int seconds) {
- getDelegateForUpdate();
- updated.setOfflineSessionMaxLifespan(seconds);
- }
-
- @Override
- public int getAccessTokenLifespan() {
- if (isUpdated()) return updated.getAccessTokenLifespan();
- return cached.getAccessTokenLifespan();
- }
-
- @Override
- public void setAccessTokenLifespan(int seconds) {
- getDelegateForUpdate();
- updated.setAccessTokenLifespan(seconds);
- }
-
- @Override
- public int getAccessTokenLifespanForImplicitFlow() {
- if (isUpdated()) return updated.getAccessTokenLifespanForImplicitFlow();
- return cached.getAccessTokenLifespanForImplicitFlow();
- }
-
- @Override
- public void setAccessTokenLifespanForImplicitFlow(int seconds) {
- getDelegateForUpdate();
- updated.setAccessTokenLifespanForImplicitFlow(seconds);
- }
-
- @Override
- public int getAccessCodeLifespan() {
- if (isUpdated()) return updated.getAccessCodeLifespan();
- return cached.getAccessCodeLifespan();
- }
-
- @Override
- public void setAccessCodeLifespan(int seconds) {
- getDelegateForUpdate();
- updated.setAccessCodeLifespan(seconds);
- }
-
- @Override
- public int getAccessCodeLifespanUserAction() {
- if (isUpdated()) return updated.getAccessCodeLifespanUserAction();
- return cached.getAccessCodeLifespanUserAction();
- }
-
- @Override
- public void setAccessCodeLifespanUserAction(int seconds) {
- getDelegateForUpdate();
- updated.setAccessCodeLifespanUserAction(seconds);
- }
-
- @Override
- public Map<String, Integer> getUserActionTokenLifespans() {
- if (isUpdated()) return updated.getUserActionTokenLifespans();
- return cached.getUserActionTokenLifespans();
- }
-
- @Override
- public int getAccessCodeLifespanLogin() {
- if (isUpdated()) return updated.getAccessCodeLifespanLogin();
- return cached.getAccessCodeLifespanLogin();
- }
-
- @Override
- public void setAccessCodeLifespanLogin(int seconds) {
- getDelegateForUpdate();
- updated.setAccessCodeLifespanLogin(seconds);
- }
-
- @Override
- public int getActionTokenGeneratedByAdminLifespan() {
- if (isUpdated()) return updated.getActionTokenGeneratedByAdminLifespan();
- return cached.getActionTokenGeneratedByAdminLifespan();
- }
-
- @Override
- public void setActionTokenGeneratedByAdminLifespan(int seconds) {
- getDelegateForUpdate();
- updated.setActionTokenGeneratedByAdminLifespan(seconds);
- }
-
- @Override
- public int getActionTokenGeneratedByUserLifespan() {
- if (isUpdated()) return updated.getActionTokenGeneratedByUserLifespan();
- return cached.getActionTokenGeneratedByUserLifespan();
- }
-
- @Override
- public void setActionTokenGeneratedByUserLifespan(int seconds) {
- getDelegateForUpdate();
- updated.setActionTokenGeneratedByUserLifespan(seconds);
- }
-
- @Override
- public int getActionTokenGeneratedByUserLifespan(String actionTokenId) {
- if (isUpdated()) return updated.getActionTokenGeneratedByUserLifespan(actionTokenId);
- return cached.getActionTokenGeneratedByUserLifespan(actionTokenId);
- }
-
- @Override
- public void setActionTokenGeneratedByUserLifespan(String actionTokenId, Integer seconds) {
- if (seconds != null) {
- getDelegateForUpdate();
- updated.setActionTokenGeneratedByUserLifespan(actionTokenId, seconds);
- }
- }
-
- @Override
- public List<RequiredCredentialModel> getRequiredCredentials() {
- if (isUpdated()) return updated.getRequiredCredentials();
- return cached.getRequiredCredentials();
- }
-
- @Override
- public void addRequiredCredential(String cred) {
- getDelegateForUpdate();
- updated.addRequiredCredential(cred);
- }
-
- @Override
- public PasswordPolicy getPasswordPolicy() {
- if (isUpdated()) return updated.getPasswordPolicy();
- return cached.getPasswordPolicy();
- }
-
- @Override
- public void setPasswordPolicy(PasswordPolicy policy) {
- getDelegateForUpdate();
- updated.setPasswordPolicy(policy);
- }
-
- @Override
- public OTPPolicy getOTPPolicy() {
- if (isUpdated()) return updated.getOTPPolicy();
- return cached.getOtpPolicy();
- }
-
- @Override
- public void setOTPPolicy(OTPPolicy policy) {
- getDelegateForUpdate();
- updated.setOTPPolicy(policy);
-
- }
-
- @Override
- public RoleModel getRoleById(String id) {
- if (isUpdated()) return updated.getRoleById(id);
- return cacheSession.getRoleById(id, this);
- }
-
- @Override
- public List<GroupModel> getDefaultGroups() {
- if (isUpdated()) return updated.getDefaultGroups();
-
- List<GroupModel> defaultGroups = new LinkedList<>();
- for (String id : cached.getDefaultGroups()) {
- defaultGroups.add(cacheSession.getGroupById(id, this));
- }
- return Collections.unmodifiableList(defaultGroups);
-
- }
-
- @Override
- public void addDefaultGroup(GroupModel group) {
- getDelegateForUpdate();
- updated.addDefaultGroup(group);
-
- }
-
- @Override
- public void removeDefaultGroup(GroupModel group) {
- getDelegateForUpdate();
- updated.removeDefaultGroup(group);
-
- }
-
- @Override
- public List<String> getDefaultRoles() {
- if (isUpdated()) return updated.getDefaultRoles();
- return cached.getDefaultRoles();
- }
-
- @Override
- public void addDefaultRole(String name) {
- getDelegateForUpdate();
- updated.addDefaultRole(name);
- }
-
- @Override
- public void updateDefaultRoles(String... defaultRoles) {
- getDelegateForUpdate();
- updated.updateDefaultRoles(defaultRoles);
- }
-
- @Override
- public void removeDefaultRoles(String... defaultRoles) {
- getDelegateForUpdate();
- updated.removeDefaultRoles(defaultRoles);
-
- }
-
- @Override
- public List<ClientModel> getClients() {
- return cacheSession.getClients(this);
-
- }
-
- @Override
- public ClientModel addClient(String name) {
- return cacheSession.addClient(this, name);
- }
-
- @Override
- public ClientModel addClient(String id, String clientId) {
- return cacheSession.addClient(this, id, clientId);
- }
-
- @Override
- public boolean removeClient(String id) {
- return cacheSession.removeClient(id, this);
- }
-
- @Override
- public ClientModel getClientById(String id) {
- if (isUpdated()) return updated.getClientById(id);
- return cacheSession.getClientById(id, this);
- }
-
- @Override
- public ClientModel getClientByClientId(String clientId) {
- return cacheSession.getClientByClientId(clientId, this);
- }
-
- @Override
- public void updateRequiredCredentials(Set<String> creds) {
- getDelegateForUpdate();
- updated.updateRequiredCredentials(creds);
- }
-
- @Override
- public Map<String, String> getBrowserSecurityHeaders() {
- if (isUpdated()) return updated.getBrowserSecurityHeaders();
- return cached.getBrowserSecurityHeaders();
- }
-
- @Override
- public void setBrowserSecurityHeaders(Map<String, String> headers) {
- getDelegateForUpdate();
- updated.setBrowserSecurityHeaders(headers);
-
- }
-
- @Override
- public Map<String, String> getSmtpConfig() {
- if (isUpdated()) return updated.getSmtpConfig();
- return cached.getSmtpConfig();
- }
-
- @Override
- public void setSmtpConfig(Map<String, String> smtpConfig) {
- getDelegateForUpdate();
- updated.setSmtpConfig(smtpConfig);
- }
-
-
- @Override
- public List<IdentityProviderModel> getIdentityProviders() {
- if (isUpdated()) return updated.getIdentityProviders();
- return cached.getIdentityProviders();
- }
-
- @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;
- }
-
- @Override
- public void addIdentityProvider(IdentityProviderModel identityProvider) {
- getDelegateForUpdate();
- updated.addIdentityProvider(identityProvider);
- }
-
- @Override
- public void updateIdentityProvider(IdentityProviderModel identityProvider) {
- getDelegateForUpdate();
- updated.updateIdentityProvider(identityProvider);
- }
-
- @Override
- public void removeIdentityProviderByAlias(String alias) {
- getDelegateForUpdate();
- updated.removeIdentityProviderByAlias(alias);
- }
-
- @Override
- public String getLoginTheme() {
- if (isUpdated()) return updated.getLoginTheme();
- return cached.getLoginTheme();
- }
-
- @Override
- public void setLoginTheme(String name) {
- getDelegateForUpdate();
- updated.setLoginTheme(name);
- }
-
- @Override
- public String getAccountTheme() {
- if (isUpdated()) return updated.getAccountTheme();
- return cached.getAccountTheme();
- }
-
- @Override
- public void setAccountTheme(String name) {
- getDelegateForUpdate();
- updated.setAccountTheme(name);
- }
-
- @Override
- public String getAdminTheme() {
- if (isUpdated()) return updated.getAdminTheme();
- return cached.getAdminTheme();
- }
-
- @Override
- public void setAdminTheme(String name) {
- getDelegateForUpdate();
- updated.setAdminTheme(name);
- }
-
- @Override
- public String getEmailTheme() {
- if (isUpdated()) return updated.getEmailTheme();
- return cached.getEmailTheme();
- }
-
- @Override
- public void setEmailTheme(String name) {
- getDelegateForUpdate();
- updated.setEmailTheme(name);
- }
-
- @Override
- public int getNotBefore() {
- if (isUpdated()) return updated.getNotBefore();
- return cached.getNotBefore();
- }
-
- @Override
- public void setNotBefore(int notBefore) {
- getDelegateForUpdate();
- updated.setNotBefore(notBefore);
- }
-
- @Override
- public boolean isEventsEnabled() {
- if (isUpdated()) return updated.isEventsEnabled();
- return cached.isEventsEnabled();
- }
-
- @Override
- public void setEventsEnabled(boolean enabled) {
- getDelegateForUpdate();
- updated.setEventsEnabled(enabled);
- }
-
- @Override
- public long getEventsExpiration() {
- if (isUpdated()) return updated.getEventsExpiration();
- return cached.getEventsExpiration();
- }
-
- @Override
- public void setEventsExpiration(long expiration) {
- getDelegateForUpdate();
- updated.setEventsExpiration(expiration);
- }
-
- @Override
- public Set<String> getEventsListeners() {
- if (isUpdated()) return updated.getEventsListeners();
- return cached.getEventsListeners();
- }
-
- @Override
- public void setEventsListeners(Set<String> listeners) {
- getDelegateForUpdate();
- updated.setEventsListeners(listeners);
- }
-
- @Override
- public Set<String> getEnabledEventTypes() {
- if (isUpdated()) return updated.getEnabledEventTypes();
- return cached.getEnabledEventTypes();
- }
-
- @Override
- public void setEnabledEventTypes(Set<String> enabledEventTypes) {
- getDelegateForUpdate();
- updated.setEnabledEventTypes(enabledEventTypes);
- }
-
- @Override
- public boolean isAdminEventsEnabled() {
- if (isUpdated()) return updated.isAdminEventsEnabled();
- return cached.isAdminEventsEnabled();
- }
-
- @Override
- public void setAdminEventsEnabled(boolean enabled) {
- getDelegateForUpdate();
- updated.setAdminEventsEnabled(enabled);
- }
-
- @Override
- public boolean isAdminEventsDetailsEnabled() {
- if (isUpdated()) return updated.isAdminEventsDetailsEnabled();
- return cached.isAdminEventsDetailsEnabled();
- }
-
- @Override
- public void setAdminEventsDetailsEnabled(boolean enabled) {
- getDelegateForUpdate();
- updated.setAdminEventsDetailsEnabled(enabled);
- }
-
- @Override
- public ClientModel getMasterAdminClient() {
- return cached.getMasterAdminClient()==null ? null : cacheSession.getRealm(Config.getAdminRealm()).getClientById(cached.getMasterAdminClient());
- }
-
- @Override
- public void setMasterAdminClient(ClientModel client) {
- getDelegateForUpdate();
- updated.setMasterAdminClient(client);
- }
-
- @Override
- public RoleModel getRole(String name) {
- return cacheSession.getRealmRole(this, name);
- }
-
- @Override
- public Set<RoleModel> getRoles() {
- return cacheSession.getRealmRoles(this);
- }
-
-
- @Override
- public RoleModel addRole(String name) {
- return cacheSession.addRealmRole(this, name);
- }
-
- @Override
- public RoleModel addRole(String id, String name) {
- return cacheSession.addRealmRole(this, id, name);
- }
-
- @Override
- public boolean removeRole(RoleModel role) {
- return cacheSession.removeRole(this, role);
- }
-
-
- @Override
- public boolean isIdentityFederationEnabled() {
- if (isUpdated()) return updated.isIdentityFederationEnabled();
- return cached.isIdentityFederationEnabled();
- }
-
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || !(o instanceof RealmModel)) return false;
-
- RealmModel that = (RealmModel) o;
- return that.getId().equals(getId());
- }
-
- @Override
- public int hashCode() {
- return getId().hashCode();
- }
-
- @Override
- public boolean isInternationalizationEnabled() {
- if (isUpdated()) return updated.isInternationalizationEnabled();
- return cached.isInternationalizationEnabled();
- }
-
- @Override
- public void setInternationalizationEnabled(boolean enabled) {
- getDelegateForUpdate();
- updated.setInternationalizationEnabled(enabled);
- }
-
- @Override
- public Set<String> getSupportedLocales() {
- if (isUpdated()) return updated.getSupportedLocales();
- return cached.getSupportedLocales();
- }
-
- @Override
- public void setSupportedLocales(Set<String> locales) {
- getDelegateForUpdate();
- updated.setSupportedLocales(locales);
- }
-
- @Override
- public String getDefaultLocale() {
- if (isUpdated()) return updated.getDefaultLocale();
- return cached.getDefaultLocale();
- }
-
- @Override
- public void setDefaultLocale(String locale) {
- updated.setDefaultLocale(locale);
- }
-
- @Override
- public Set<IdentityProviderMapperModel> getIdentityProviderMappers() {
- if (isUpdated()) return updated.getIdentityProviderMappers();
- return cached.getIdentityProviderMapperSet();
- }
-
- @Override
- public Set<IdentityProviderMapperModel> getIdentityProviderMappersByAlias(String brokerAlias) {
- if (isUpdated()) return updated.getIdentityProviderMappersByAlias(brokerAlias);
- Set<IdentityProviderMapperModel> mappings = new HashSet<>();
- List<IdentityProviderMapperModel> list = cached.getIdentityProviderMappers().getList(brokerAlias);
- for (IdentityProviderMapperModel entity : list) {
- mappings.add(entity);
- }
- return Collections.unmodifiableSet(mappings);
- }
-
- @Override
- public IdentityProviderMapperModel addIdentityProviderMapper(IdentityProviderMapperModel model) {
- getDelegateForUpdate();
- return updated.addIdentityProviderMapper(model);
- }
-
- @Override
- public void removeIdentityProviderMapper(IdentityProviderMapperModel mapping) {
- getDelegateForUpdate();
- updated.removeIdentityProviderMapper(mapping);
- }
-
- @Override
- public void updateIdentityProviderMapper(IdentityProviderMapperModel mapping) {
- getDelegateForUpdate();
- updated.updateIdentityProviderMapper(mapping);
- }
-
- @Override
- public IdentityProviderMapperModel getIdentityProviderMapperById(String id) {
- if (isUpdated()) return updated.getIdentityProviderMapperById(id);
- for (List<IdentityProviderMapperModel> models : cached.getIdentityProviderMappers().values()) {
- for (IdentityProviderMapperModel model : models) {
- if (model.getId().equals(id)) return model;
- }
- }
- return null;
- }
-
- @Override
- public IdentityProviderMapperModel getIdentityProviderMapperByName(String alias, String name) {
- if (isUpdated()) return updated.getIdentityProviderMapperByName(alias, name);
- List<IdentityProviderMapperModel> models = cached.getIdentityProviderMappers().getList(alias);
- if (models == null) return null;
- for (IdentityProviderMapperModel model : models) {
- if (model.getName().equals(name)) return model;
- }
- return null;
- }
-
- @Override
- public AuthenticationFlowModel getBrowserFlow() {
- if (isUpdated()) return updated.getBrowserFlow();
- return cached.getBrowserFlow();
- }
-
- @Override
- public void setBrowserFlow(AuthenticationFlowModel flow) {
- getDelegateForUpdate();
- updated.setBrowserFlow(flow);
-
- }
-
- @Override
- public AuthenticationFlowModel getRegistrationFlow() {
- if (isUpdated()) return updated.getRegistrationFlow();
- return cached.getRegistrationFlow();
- }
-
- @Override
- public void setRegistrationFlow(AuthenticationFlowModel flow) {
- getDelegateForUpdate();
- updated.setRegistrationFlow(flow);
-
- }
-
- @Override
- public AuthenticationFlowModel getDirectGrantFlow() {
- if (isUpdated()) return updated.getDirectGrantFlow();
- return cached.getDirectGrantFlow();
- }
-
- @Override
- public void setDirectGrantFlow(AuthenticationFlowModel flow) {
- getDelegateForUpdate();
- updated.setDirectGrantFlow(flow);
-
- }
- @Override
- public AuthenticationFlowModel getResetCredentialsFlow() {
- if (isUpdated()) return updated.getResetCredentialsFlow();
- return cached.getResetCredentialsFlow();
- }
-
- @Override
- public void setResetCredentialsFlow(AuthenticationFlowModel flow) {
- getDelegateForUpdate();
- updated.setResetCredentialsFlow(flow);
-
- }
-
- @Override
- public AuthenticationFlowModel getClientAuthenticationFlow() {
- if (isUpdated()) return updated.getClientAuthenticationFlow();
- return cached.getClientAuthenticationFlow();
- }
-
- @Override
- public void setClientAuthenticationFlow(AuthenticationFlowModel flow) {
- getDelegateForUpdate();
- updated.setClientAuthenticationFlow(flow);
- }
-
- @Override
- public AuthenticationFlowModel getDockerAuthenticationFlow() {
- if (isUpdated()) return updated.getDockerAuthenticationFlow();
- return cached.getDockerAuthenticationFlow();
- }
-
- @Override
- public void setDockerAuthenticationFlow(final AuthenticationFlowModel flow) {
- getDelegateForUpdate();
- updated.setDockerAuthenticationFlow(flow);
- }
-
- @Override
- public List<AuthenticationFlowModel> getAuthenticationFlows() {
- if (isUpdated()) return updated.getAuthenticationFlows();
- return cached.getAuthenticationFlowList();
- }
-
- @Override
- public AuthenticationFlowModel getFlowByAlias(String alias) {
- for (AuthenticationFlowModel flow : getAuthenticationFlows()) {
- if (flow.getAlias().equals(alias)) {
- return flow;
- }
- }
- return null;
- }
-
- @Override
- public AuthenticatorConfigModel getAuthenticatorConfigByAlias(String alias) {
- for (AuthenticatorConfigModel config : getAuthenticatorConfigs()) {
- if (config.getAlias().equals(alias)) {
- return config;
- }
- }
- return null;
- }
-
-
- @Override
- public AuthenticationFlowModel addAuthenticationFlow(AuthenticationFlowModel model) {
- getDelegateForUpdate();
- return updated.addAuthenticationFlow(model);
- }
-
- @Override
- public AuthenticationFlowModel getAuthenticationFlowById(String id) {
- if (isUpdated()) return updated.getAuthenticationFlowById(id);
- return cached.getAuthenticationFlows().get(id);
- }
-
- @Override
- public void removeAuthenticationFlow(AuthenticationFlowModel model) {
- getDelegateForUpdate();
- updated.removeAuthenticationFlow(model);
-
- }
-
- @Override
- public void updateAuthenticationFlow(AuthenticationFlowModel model) {
- getDelegateForUpdate();
- updated.updateAuthenticationFlow(model);
-
- }
-
- @Override
- public List<AuthenticationExecutionModel> getAuthenticationExecutions(String flowId) {
- if (isUpdated()) return updated.getAuthenticationExecutions(flowId);
- return cached.getAuthenticationExecutions().get(flowId);
- }
-
- @Override
- public AuthenticationExecutionModel getAuthenticationExecutionById(String id) {
- if (isUpdated()) return updated.getAuthenticationExecutionById(id);
- return cached.getExecutionsById().get(id);
- }
-
- @Override
- public AuthenticationExecutionModel addAuthenticatorExecution(AuthenticationExecutionModel model) {
- getDelegateForUpdate();
- return updated.addAuthenticatorExecution(model);
- }
-
- @Override
- public void updateAuthenticatorExecution(AuthenticationExecutionModel model) {
- getDelegateForUpdate();
- updated.updateAuthenticatorExecution(model);
-
- }
-
- @Override
- public void removeAuthenticatorExecution(AuthenticationExecutionModel model) {
- getDelegateForUpdate();
- updated.removeAuthenticatorExecution(model);
-
- }
-
- @Override
- public List<AuthenticatorConfigModel> getAuthenticatorConfigs() {
- if (isUpdated()) return updated.getAuthenticatorConfigs();
- List<AuthenticatorConfigModel> models = new ArrayList<>();
- models.addAll(cached.getAuthenticatorConfigs().values());
- return Collections.unmodifiableList(models);
- }
-
- @Override
- public AuthenticatorConfigModel addAuthenticatorConfig(AuthenticatorConfigModel model) {
- getDelegateForUpdate();
- return updated.addAuthenticatorConfig(model);
- }
-
- @Override
- public void updateAuthenticatorConfig(AuthenticatorConfigModel model) {
- getDelegateForUpdate();
- updated.updateAuthenticatorConfig(model);
-
- }
-
- @Override
- public void removeAuthenticatorConfig(AuthenticatorConfigModel model) {
- getDelegateForUpdate();
- updated.removeAuthenticatorConfig(model);
-
- }
-
- @Override
- public AuthenticatorConfigModel getAuthenticatorConfigById(String id) {
- if (isUpdated()) return updated.getAuthenticatorConfigById(id);
- return cached.getAuthenticatorConfigs().get(id);
- }
-
- @Override
- public List<RequiredActionProviderModel> getRequiredActionProviders() {
- if (isUpdated()) return updated.getRequiredActionProviders();
- return cached.getRequiredActionProviderList();
- }
-
- @Override
- public RequiredActionProviderModel addRequiredActionProvider(RequiredActionProviderModel model) {
- getDelegateForUpdate();
- return updated.addRequiredActionProvider(model);
- }
-
- @Override
- public void updateRequiredActionProvider(RequiredActionProviderModel model) {
- getDelegateForUpdate();
- updated.updateRequiredActionProvider(model);
-
- }
-
- @Override
- public void removeRequiredActionProvider(RequiredActionProviderModel model) {
- getDelegateForUpdate();
- updated.removeRequiredActionProvider(model);
-
- }
-
- @Override
- public RequiredActionProviderModel getRequiredActionProviderById(String id) {
- if (isUpdated()) return updated.getRequiredActionProviderById(id);
- return cached.getRequiredActionProviders().get(id);
- }
-
- @Override
- public RequiredActionProviderModel getRequiredActionProviderByAlias(String alias) {
- if (isUpdated()) return updated.getRequiredActionProviderByAlias(alias);
- return cached.getRequiredActionProvidersByAlias().get(alias);
- }
-
- @Override
- public GroupModel createGroup(String name) {
- return cacheSession.createGroup(this, name);
- }
-
- @Override
- public GroupModel createGroup(String id, String name) {
- return cacheSession.createGroup(this, id, name);
- }
-
- @Override
- public void moveGroup(GroupModel group, GroupModel toParent) {
- cacheSession.moveGroup(this, group, toParent);
- }
-
- @Override
- public GroupModel getGroupById(String id) {
- return cacheSession.getGroupById(id, this);
- }
-
- @Override
- public List<GroupModel> getGroups() {
- return cacheSession.getGroups(this);
- }
-
- @Override
- public Long getGroupsCount(Boolean onlyTopGroups) {
- return cacheSession.getGroupsCount(this, onlyTopGroups);
- }
-
- @Override
- public Long getGroupsCountByNameContaining(String search) {
- return cacheSession.getGroupsCountByNameContaining(this, search);
- }
-
- @Override
- public List<GroupModel> getTopLevelGroups() {
- return cacheSession.getTopLevelGroups(this);
- }
-
- @Override
- public List<GroupModel> getTopLevelGroups(Integer first, Integer max) {
- return cacheSession.getTopLevelGroups(this, first, max);
- }
-
- @Override
- public List<GroupModel> searchForGroupByName(String search, Integer first, Integer max) {
- return cacheSession.searchForGroupByName(this, search, first, max);
- }
-
- @Override
- public boolean removeGroup(GroupModel group) {
- return cacheSession.removeGroup(this, group);
- }
-
- @Override
- public List<ClientScopeModel> getClientScopes() {
- if (isUpdated()) return updated.getClientScopes();
- List<String> clientScopes = cached.getClientScopes();
- if (clientScopes.isEmpty()) return Collections.EMPTY_LIST;
- List<ClientScopeModel> apps = new LinkedList<ClientScopeModel>();
- for (String id : clientScopes) {
- ClientScopeModel model = cacheSession.getClientScopeById(id, this);
- if (model == null) {
- throw new IllegalStateException("Cached clientScope not found: " + id);
- }
- apps.add(model);
- }
- return Collections.unmodifiableList(apps);
-
- }
-
- @Override
- public ClientScopeModel addClientScope(String name) {
- getDelegateForUpdate();
- ClientScopeModel app = updated.addClientScope(name);
- cacheSession.registerClientScopeInvalidation(app.getId());
- return app;
- }
-
- @Override
- public ClientScopeModel addClientScope(String id, String name) {
- getDelegateForUpdate();
- ClientScopeModel app = updated.addClientScope(id, name);
- cacheSession.registerClientScopeInvalidation(app.getId());
- return app;
- }
-
- @Override
- public boolean removeClientScope(String id) {
- cacheSession.registerClientScopeInvalidation(id);
- getDelegateForUpdate();
- return updated.removeClientScope(id);
- }
-
- @Override
- public ClientScopeModel getClientScopeById(String id) {
- if (isUpdated()) return updated.getClientScopeById(id);
- return cacheSession.getClientScopeById(id, this);
- }
-
- @Override
- public void addDefaultClientScope(ClientScopeModel clientScope, boolean defaultScope) {
- getDelegateForUpdate();
- updated.addDefaultClientScope(clientScope, defaultScope);
- }
-
- @Override
- public void removeDefaultClientScope(ClientScopeModel clientScope) {
- getDelegateForUpdate();
- updated.removeDefaultClientScope(clientScope);
- }
-
- @Override
- public List<ClientScopeModel> getDefaultClientScopes(boolean defaultScope) {
- if (isUpdated()) return updated.getDefaultClientScopes(defaultScope);
-
- List<String> clientScopeIds = defaultScope ? cached.getDefaultDefaultClientScopes() : cached.getOptionalDefaultClientScopes();
-
- List<ClientScopeModel> clientScopes = new LinkedList<>();
- for (String scopeId : clientScopeIds) {
- ClientScopeModel clientScope = cacheSession.getClientScopeById(scopeId, this);
- if (clientScope != null) {
- clientScopes.add(clientScope);
- }
- }
- return clientScopes;
- }
-
- @Override
- public ComponentModel addComponentModel(ComponentModel model) {
- getDelegateForUpdate();
- executeEvictions(model);
- return updated.addComponentModel(model);
- }
-
- @Override
- public ComponentModel importComponentModel(ComponentModel model) {
- getDelegateForUpdate();
- executeEvictions(model);
- return updated.importComponentModel(model);
- }
-
- public void executeEvictions(ComponentModel model) {
- if (model == null) return;
- // If not realm component, check to see if it is a user storage provider child component (i.e. LDAP mapper)
- if (model.getParentId() != null && !model.getParentId().equals(getId())) {
- ComponentModel parent = getComponent(model.getParentId());
- if (parent != null && UserStorageProvider.class.getName().equals(parent.getProviderType())) {
- session.userCache().evict(this);
- }
- return;
- }
-
- // invalidate entire user cache if we're dealing with user storage SPI
- if (UserStorageProvider.class.getName().equals(model.getProviderType())) {
- session.userCache().evict(this);
- }
- // invalidate entire realm if we're dealing with client storage SPI
- // entire realm because of client roles, client lists, and clients
- if (ClientStorageProvider.class.getName().equals(model.getProviderType())) {
- cacheSession.evictRealmOnRemoval(this);
- }
- }
-
- @Override
- public void updateComponent(ComponentModel component) {
- getDelegateForUpdate();
- executeEvictions(component);
- updated.updateComponent(component);
-
- }
-
- @Override
- public void removeComponent(ComponentModel component) {
- getDelegateForUpdate();
- executeEvictions(component);
- updated.removeComponent(component);
-
- }
-
- @Override
- public void removeComponents(String parentId) {
- getDelegateForUpdate();
- updated.removeComponents(parentId);
-
- }
-
- @Override
- public List<ComponentModel> getComponents(String parentId, String providerType) {
- if (isUpdated()) return updated.getComponents(parentId, providerType);
- List<ComponentModel> components = cached.getComponentsByParentAndType().getList(parentId + providerType);
- if (components == null) return Collections.EMPTY_LIST;
- return Collections.unmodifiableList(components);
- }
-
- @Override
- public List<ComponentModel> getComponents(String parentId) {
- if (isUpdated()) return updated.getComponents(parentId);
- List<ComponentModel> components = cached.getComponentsByParent().getList(parentId);
- if (components == null) return Collections.EMPTY_LIST;
- return Collections.unmodifiableList(components);
- }
-
- @Override
- public List<ComponentModel> getComponents() {
- if (isUpdated()) return updated.getComponents();
- List<ComponentModel> results = new LinkedList<>();
- results.addAll(cached.getComponents().values());
- return Collections.unmodifiableList(results);
- }
-
- @Override
- public ComponentModel getComponent(String id) {
- if (isUpdated()) return updated.getComponent(id);
- return cached.getComponents().get(id);
- }
-
- public void setAttribute(String name, String value) {
- getDelegateForUpdate();
- updated.setAttribute(name, value);
- }
-
- @Override
- public void setAttribute(String name, Boolean value) {
- getDelegateForUpdate();
- updated.setAttribute(name, value);
- }
-
- @Override
- public void setAttribute(String name, Integer value) {
- getDelegateForUpdate();
- updated.setAttribute(name, value);
- }
-
- @Override
- public void setAttribute(String name, Long value) {
- getDelegateForUpdate();
- updated.setAttribute(name, value);
- }
-
- @Override
- public void removeAttribute(String name) {
- getDelegateForUpdate();
- updated.removeAttribute(name);
- }
-
- @Override
- public String getAttribute(String name) {
- if (isUpdated()) return updated.getAttribute(name);
- return cached.getAttribute(name);
- }
-
- @Override
- public Integer getAttribute(String name, Integer defaultValue) {
- if (isUpdated()) return updated.getAttribute(name, defaultValue);
- return cached.getAttribute(name, defaultValue);
- }
-
- @Override
- public Long getAttribute(String name, Long defaultValue) {
- if (isUpdated()) return updated.getAttribute(name, defaultValue);
- return cached.getAttribute(name, defaultValue);
- }
-
- @Override
- public Boolean getAttribute(String name, Boolean defaultValue) {
- if (isUpdated()) return updated.getAttribute(name, defaultValue);
- return cached.getAttribute(name, defaultValue);
- }
-
- @Override
- public Map<String, String> getAttributes() {
- if (isUpdated()) return updated.getAttributes();
- return cached.getAttributes();
- }
-
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan;
+
+// import org.keycloak.Config;
+// import org.keycloak.common.enums.SslRequired;
+// import org.keycloak.component.ComponentModel;
+// import org.keycloak.models.*;
+// import org.keycloak.models.cache.CachedRealmModel;
+// import org.keycloak.models.cache.infinispan.entities.CachedRealm;
+// import org.keycloak.storage.UserStorageProvider;
+// import org.keycloak.storage.client.ClientStorageProvider;
+
+// import java.util.*;
+// import java.util.concurrent.ConcurrentHashMap;
+
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public class RealmAdapter implements CachedRealmModel {
+// protected CachedRealm cached;
+// protected RealmCacheSession cacheSession;
+// protected volatile RealmModel updated;
+// protected KeycloakSession session;
+
+// public RealmAdapter(KeycloakSession session, CachedRealm cached, RealmCacheSession cacheSession) {
+// this.cached = cached;
+// this.cacheSession = cacheSession;
+// this.session = session;
+// }
+
+// @Override
+// public RealmModel getDelegateForUpdate() {
+// if (updated == null) {
+// cacheSession.registerRealmInvalidation(cached.getId(), cached.getName());
+// updated = cacheSession.getRealmDelegate().getRealm(cached.getId());
+// if (updated == null) throw new IllegalStateException("Not found in database");
+// }
+// return updated;
+// }
+
+// protected volatile boolean invalidated;
+
+// protected void invalidateFlag() {
+// invalidated = true;
+
+// }
+
+// @Override
+// public void invalidate() {
+// invalidated = true;
+// getDelegateForUpdate();
+// }
+
+// @Override
+// public long getCacheTimestamp() {
+// return cached.getCacheTimestamp();
+// }
+
+// @Override
+// public ConcurrentHashMap getCachedWith() {
+// return cached.getCachedWith();
+// }
+
+// protected boolean isUpdated() {
+// if (updated != null) return true;
+// if (!invalidated) return false;
+// updated = cacheSession.getRealmDelegate().getRealm(cached.getId());
+// if (updated == null) throw new IllegalStateException("Not found in database");
+// return true;
+// }
+
+
+// @Override
+// public String getId() {
+// if (isUpdated()) return updated.getId();
+// return cached.getId();
+// }
+
+// @Override
+// public String getName() {
+// if (isUpdated()) return updated.getName();
+// return cached.getName();
+// }
+
+// @Override
+// public void setName(String name) {
+// getDelegateForUpdate();
+// updated.setName(name);
+// }
+
+// @Override
+// public String getDisplayName() {
+// if (isUpdated()) return updated.getDisplayName();
+// return cached.getDisplayName();
+// }
+
+// @Override
+// public void setDisplayName(String displayName) {
+// getDelegateForUpdate();
+// updated.setDisplayName(displayName);
+// }
+
+// @Override
+// public String getDisplayNameHtml() {
+// if (isUpdated()) return updated.getDisplayNameHtml();
+// return cached.getDisplayNameHtml();
+// }
+
+// @Override
+// public void setDisplayNameHtml(String displayNameHtml) {
+// getDelegateForUpdate();
+// updated.setDisplayNameHtml(displayNameHtml);
+// }
+
+// @Override
+// public boolean isEnabled() {
+// if (isUpdated()) return updated.isEnabled();
+// return cached.isEnabled();
+// }
+
+// @Override
+// public void setEnabled(boolean enabled) {
+// getDelegateForUpdate();
+// updated.setEnabled(enabled);
+// }
+
+// @Override
+// public boolean isUserManagedAccessAllowed() {
+// if (isUpdated()) return updated.isEnabled();
+// return cached.isAllowUserManagedAccess();
+// }
+
+// @Override
+// public void setUserManagedAccessAllowed(boolean userManagedAccessAllowed) {
+// getDelegateForUpdate();
+// updated.setUserManagedAccessAllowed(userManagedAccessAllowed);
+// }
+
+// @Override
+// public SslRequired getSslRequired() {
+// if (isUpdated()) return updated.getSslRequired();
+// return cached.getSslRequired();
+// }
+
+// @Override
+// public void setSslRequired(SslRequired sslRequired) {
+// getDelegateForUpdate();
+// updated.setSslRequired(sslRequired);
+// }
+
+// @Override
+// public boolean isRegistrationAllowed() {
+// if (isUpdated()) return updated.isRegistrationAllowed();
+// return cached.isRegistrationAllowed();
+// }
+
+// @Override
+// public void setRegistrationAllowed(boolean registrationAllowed) {
+// getDelegateForUpdate();
+// updated.setRegistrationAllowed(registrationAllowed);
+// }
+
+// @Override
+// public boolean isRegistrationEmailAsUsername() {
+// if (isUpdated()) return updated.isRegistrationEmailAsUsername();
+// return cached.isRegistrationEmailAsUsername();
+// }
+
+// @Override
+// public void setRegistrationEmailAsUsername(boolean registrationEmailAsUsername) {
+// getDelegateForUpdate();
+// updated.setRegistrationEmailAsUsername(registrationEmailAsUsername);
+// }
+
+// @Override
+// public boolean isRememberMe() {
+// if (isUpdated()) return updated.isRememberMe();
+// return cached.isRememberMe();
+// }
+
+// @Override
+// public void setRememberMe(boolean rememberMe) {
+// getDelegateForUpdate();
+// updated.setRememberMe(rememberMe);
+// }
+
+// @Override
+// public String getDefaultSignatureAlgorithm() {
+// if(isUpdated()) return updated.getDefaultSignatureAlgorithm();
+// return cached.getDefaultSignatureAlgorithm();
+// }
+
+// @Override
+// public void setDefaultSignatureAlgorithm(String defaultSignatureAlgorithm) {
+// getDelegateForUpdate();
+// updated.setDefaultSignatureAlgorithm(defaultSignatureAlgorithm);
+// }
+
+// @Override
+// public boolean isBruteForceProtected() {
+// if (isUpdated()) return updated.isBruteForceProtected();
+// return cached.isBruteForceProtected();
+// }
+
+// @Override
+// public void setBruteForceProtected(boolean value) {
+// getDelegateForUpdate();
+// updated.setBruteForceProtected(value);
+// }
+
+// @Override
+// public boolean isPermanentLockout() {
+// if(isUpdated()) return updated.isPermanentLockout();
+// return cached.isPermanentLockout();
+// }
+
+// @Override
+// public void setPermanentLockout(final boolean val) {
+// getDelegateForUpdate();
+// updated.setPermanentLockout(val);
+// }
+
+// @Override
+// public int getMaxFailureWaitSeconds() {
+// if (isUpdated()) return updated.getMaxFailureWaitSeconds();
+// return cached.getMaxFailureWaitSeconds();
+// }
+
+// @Override
+// public void setMaxFailureWaitSeconds(int val) {
+// getDelegateForUpdate();
+// updated.setMaxFailureWaitSeconds(val);
+// }
+
+// @Override
+// public int getWaitIncrementSeconds() {
+// if (isUpdated()) return updated.getWaitIncrementSeconds();
+// return cached.getWaitIncrementSeconds();
+// }
+
+// @Override
+// public void setWaitIncrementSeconds(int val) {
+// getDelegateForUpdate();
+// updated.setWaitIncrementSeconds(val);
+// }
+
+// @Override
+// public int getMinimumQuickLoginWaitSeconds() {
+// if (isUpdated()) return updated.getMinimumQuickLoginWaitSeconds();
+// return cached.getMinimumQuickLoginWaitSeconds();
+// }
+
+// @Override
+// public void setMinimumQuickLoginWaitSeconds(int val) {
+// getDelegateForUpdate();
+// updated.setMinimumQuickLoginWaitSeconds(val);
+// }
+
+// @Override
+// public long getQuickLoginCheckMilliSeconds() {
+// if (isUpdated()) return updated.getQuickLoginCheckMilliSeconds();
+// return cached.getQuickLoginCheckMilliSeconds();
+// }
+
+// @Override
+// public void setQuickLoginCheckMilliSeconds(long val) {
+// getDelegateForUpdate();
+// updated.setQuickLoginCheckMilliSeconds(val);
+// }
+
+// @Override
+// public int getMaxDeltaTimeSeconds() {
+// if (isUpdated()) return updated.getMaxDeltaTimeSeconds();
+// return cached.getMaxDeltaTimeSeconds();
+// }
+
+// @Override
+// public void setMaxDeltaTimeSeconds(int val) {
+// getDelegateForUpdate();
+// updated.setMaxDeltaTimeSeconds(val);
+// }
+
+// @Override
+// public int getFailureFactor() {
+// if (isUpdated()) return updated.getFailureFactor();
+// return cached.getFailureFactor();
+// }
+
+// @Override
+// public void setFailureFactor(int failureFactor) {
+// getDelegateForUpdate();
+// updated.setFailureFactor(failureFactor);
+// }
+
+// @Override
+// public boolean isVerifyEmail() {
+// if (isUpdated()) return updated.isVerifyEmail();
+// return cached.isVerifyEmail();
+// }
+
+// @Override
+// public void setVerifyEmail(boolean verifyEmail) {
+// getDelegateForUpdate();
+// updated.setVerifyEmail(verifyEmail);
+// }
+
+// @Override
+// public boolean isLoginWithEmailAllowed() {
+// if (isUpdated()) return updated.isLoginWithEmailAllowed();
+// return cached.isLoginWithEmailAllowed();
+// }
+
+// @Override
+// public void setLoginWithEmailAllowed(boolean loginWithEmailAllowed) {
+// getDelegateForUpdate();
+// updated.setLoginWithEmailAllowed(loginWithEmailAllowed);
+// }
+
+// @Override
+// public boolean isDuplicateEmailsAllowed() {
+// if (isUpdated()) return updated.isDuplicateEmailsAllowed();
+// return cached.isDuplicateEmailsAllowed();
+// }
+
+// @Override
+// public void setDuplicateEmailsAllowed(boolean duplicateEmailsAllowed) {
+// getDelegateForUpdate();
+// updated.setDuplicateEmailsAllowed(duplicateEmailsAllowed);
+// }
+
+// @Override
+// public boolean isResetPasswordAllowed() {
+// if (isUpdated()) return updated.isResetPasswordAllowed();
+// return cached.isResetPasswordAllowed();
+// }
+
+// @Override
+// public void setResetPasswordAllowed(boolean resetPasswordAllowed) {
+// getDelegateForUpdate();
+// updated.setResetPasswordAllowed(resetPasswordAllowed);
+// }
+
+// @Override
+// public boolean isEditUsernameAllowed() {
+// if (isUpdated()) return updated.isEditUsernameAllowed();
+// return cached.isEditUsernameAllowed();
+// }
+
+// @Override
+// public void setEditUsernameAllowed(boolean editUsernameAllowed) {
+// getDelegateForUpdate();
+// updated.setEditUsernameAllowed(editUsernameAllowed);
+// }
+
+// @Override
+// public boolean isRevokeRefreshToken() {
+// if (isUpdated()) return updated.isRevokeRefreshToken();
+// return cached.isRevokeRefreshToken();
+// }
+
+// @Override
+// public void setRevokeRefreshToken(boolean revokeRefreshToken) {
+// getDelegateForUpdate();
+// updated.setRevokeRefreshToken(revokeRefreshToken);
+// }
+
+// @Override
+// public int getRefreshTokenMaxReuse() {
+// if (isUpdated()) return updated.getRefreshTokenMaxReuse();
+// return cached.getRefreshTokenMaxReuse();
+// }
+
+// @Override
+// public void setRefreshTokenMaxReuse(int refreshTokenMaxReuse) {
+// getDelegateForUpdate();
+// updated.setRefreshTokenMaxReuse(refreshTokenMaxReuse);
+// }
+
+// @Override
+// public int getSsoSessionIdleTimeout() {
+// if (isUpdated()) return updated.getSsoSessionIdleTimeout();
+// return cached.getSsoSessionIdleTimeout();
+// }
+
+// @Override
+// public void setSsoSessionIdleTimeout(int seconds) {
+// getDelegateForUpdate();
+// updated.setSsoSessionIdleTimeout(seconds);
+// }
+
+// @Override
+// public int getSsoSessionMaxLifespan() {
+// if (isUpdated()) return updated.getSsoSessionMaxLifespan();
+// return cached.getSsoSessionMaxLifespan();
+// }
+
+// @Override
+// public void setSsoSessionMaxLifespan(int seconds) {
+// getDelegateForUpdate();
+// updated.setSsoSessionMaxLifespan(seconds);
+// }
+
+// @Override
+// public int getSsoSessionIdleTimeoutRememberMe() {
+// if (updated != null) return updated.getSsoSessionIdleTimeoutRememberMe();
+// return cached.getSsoSessionIdleTimeoutRememberMe();
+// }
+
+// @Override
+// public void setSsoSessionIdleTimeoutRememberMe(int seconds) {
+// getDelegateForUpdate();
+// updated.setSsoSessionIdleTimeoutRememberMe(seconds);
+// }
+
+// @Override
+// public int getSsoSessionMaxLifespanRememberMe() {
+// if (updated != null) return updated.getSsoSessionMaxLifespanRememberMe();
+// return cached.getSsoSessionMaxLifespanRememberMe();
+// }
+
+// @Override
+// public void setSsoSessionMaxLifespanRememberMe(int seconds) {
+// getDelegateForUpdate();
+// updated.setSsoSessionMaxLifespanRememberMe(seconds);
+// }
+
+// @Override
+// public int getOfflineSessionIdleTimeout() {
+// if (isUpdated()) return updated.getOfflineSessionIdleTimeout();
+// return cached.getOfflineSessionIdleTimeout();
+// }
+
+
+// @Override
+// public void setOfflineSessionIdleTimeout(int seconds) {
+// getDelegateForUpdate();
+// updated.setOfflineSessionIdleTimeout(seconds);
+// }
+
+// // KEYCLOAK-7688 Offline Session Max for Offline Token
+// @Override
+// public boolean isOfflineSessionMaxLifespanEnabled() {
+// if (isUpdated()) return updated.isOfflineSessionMaxLifespanEnabled();
+// return cached.isOfflineSessionMaxLifespanEnabled();
+// }
+
+// @Override
+// public void setOfflineSessionMaxLifespanEnabled(boolean offlineSessionMaxLifespanEnabled) {
+// getDelegateForUpdate();
+// updated.setOfflineSessionMaxLifespanEnabled(offlineSessionMaxLifespanEnabled);
+// }
+
+// @Override
+// public int getOfflineSessionMaxLifespan() {
+// if (isUpdated()) return updated.getOfflineSessionMaxLifespan();
+// return cached.getOfflineSessionMaxLifespan();
+// }
+
+// @Override
+// public void setOfflineSessionMaxLifespan(int seconds) {
+// getDelegateForUpdate();
+// updated.setOfflineSessionMaxLifespan(seconds);
+// }
+
+// @Override
+// public int getAccessTokenLifespan() {
+// if (isUpdated()) return updated.getAccessTokenLifespan();
+// return cached.getAccessTokenLifespan();
+// }
+
+// @Override
+// public void setAccessTokenLifespan(int seconds) {
+// getDelegateForUpdate();
+// updated.setAccessTokenLifespan(seconds);
+// }
+
+// @Override
+// public int getAccessTokenLifespanForImplicitFlow() {
+// if (isUpdated()) return updated.getAccessTokenLifespanForImplicitFlow();
+// return cached.getAccessTokenLifespanForImplicitFlow();
+// }
+
+// @Override
+// public void setAccessTokenLifespanForImplicitFlow(int seconds) {
+// getDelegateForUpdate();
+// updated.setAccessTokenLifespanForImplicitFlow(seconds);
+// }
+
+// @Override
+// public int getAccessCodeLifespan() {
+// if (isUpdated()) return updated.getAccessCodeLifespan();
+// return cached.getAccessCodeLifespan();
+// }
+
+// @Override
+// public void setAccessCodeLifespan(int seconds) {
+// getDelegateForUpdate();
+// updated.setAccessCodeLifespan(seconds);
+// }
+
+// @Override
+// public int getAccessCodeLifespanUserAction() {
+// if (isUpdated()) return updated.getAccessCodeLifespanUserAction();
+// return cached.getAccessCodeLifespanUserAction();
+// }
+
+// @Override
+// public void setAccessCodeLifespanUserAction(int seconds) {
+// getDelegateForUpdate();
+// updated.setAccessCodeLifespanUserAction(seconds);
+// }
+
+// @Override
+// public Map<String, Integer> getUserActionTokenLifespans() {
+// if (isUpdated()) return updated.getUserActionTokenLifespans();
+// return cached.getUserActionTokenLifespans();
+// }
+
+// @Override
+// public int getAccessCodeLifespanLogin() {
+// if (isUpdated()) return updated.getAccessCodeLifespanLogin();
+// return cached.getAccessCodeLifespanLogin();
+// }
+
+// @Override
+// public void setAccessCodeLifespanLogin(int seconds) {
+// getDelegateForUpdate();
+// updated.setAccessCodeLifespanLogin(seconds);
+// }
+
+// @Override
+// public int getActionTokenGeneratedByAdminLifespan() {
+// if (isUpdated()) return updated.getActionTokenGeneratedByAdminLifespan();
+// return cached.getActionTokenGeneratedByAdminLifespan();
+// }
+
+// @Override
+// public void setActionTokenGeneratedByAdminLifespan(int seconds) {
+// getDelegateForUpdate();
+// updated.setActionTokenGeneratedByAdminLifespan(seconds);
+// }
+
+// @Override
+// public int getActionTokenGeneratedByUserLifespan() {
+// if (isUpdated()) return updated.getActionTokenGeneratedByUserLifespan();
+// return cached.getActionTokenGeneratedByUserLifespan();
+// }
+
+// @Override
+// public void setActionTokenGeneratedByUserLifespan(int seconds) {
+// getDelegateForUpdate();
+// updated.setActionTokenGeneratedByUserLifespan(seconds);
+// }
+
+// @Override
+// public int getActionTokenGeneratedByUserLifespan(String actionTokenId) {
+// if (isUpdated()) return updated.getActionTokenGeneratedByUserLifespan(actionTokenId);
+// return cached.getActionTokenGeneratedByUserLifespan(actionTokenId);
+// }
+
+// @Override
+// public void setActionTokenGeneratedByUserLifespan(String actionTokenId, Integer seconds) {
+// if (seconds != null) {
+// getDelegateForUpdate();
+// updated.setActionTokenGeneratedByUserLifespan(actionTokenId, seconds);
+// }
+// }
+
+// @Override
+// public List<RequiredCredentialModel> getRequiredCredentials() {
+// if (isUpdated()) return updated.getRequiredCredentials();
+// return cached.getRequiredCredentials();
+// }
+
+// @Override
+// public void addRequiredCredential(String cred) {
+// getDelegateForUpdate();
+// updated.addRequiredCredential(cred);
+// }
+
+// @Override
+// public PasswordPolicy getPasswordPolicy() {
+// if (isUpdated()) return updated.getPasswordPolicy();
+// return cached.getPasswordPolicy();
+// }
+
+// @Override
+// public void setPasswordPolicy(PasswordPolicy policy) {
+// getDelegateForUpdate();
+// updated.setPasswordPolicy(policy);
+// }
+
+// @Override
+// public OTPPolicy getOTPPolicy() {
+// if (isUpdated()) return updated.getOTPPolicy();
+// return cached.getOtpPolicy();
+// }
+
+// @Override
+// public void setOTPPolicy(OTPPolicy policy) {
+// getDelegateForUpdate();
+// updated.setOTPPolicy(policy);
+
+// }
+
+// @Override
+// public RoleModel getRoleById(String id) {
+// if (isUpdated()) return updated.getRoleById(id);
+// return cacheSession.getRoleById(id, this);
+// }
+
+// @Override
+// public List<GroupModel> getDefaultGroups() {
+// if (isUpdated()) return updated.getDefaultGroups();
+
+// List<GroupModel> defaultGroups = new LinkedList<>();
+// for (String id : cached.getDefaultGroups()) {
+// defaultGroups.add(cacheSession.getGroupById(id, this));
+// }
+// return Collections.unmodifiableList(defaultGroups);
+
+// }
+
+// @Override
+// public void addDefaultGroup(GroupModel group) {
+// getDelegateForUpdate();
+// updated.addDefaultGroup(group);
+
+// }
+
+// @Override
+// public void removeDefaultGroup(GroupModel group) {
+// getDelegateForUpdate();
+// updated.removeDefaultGroup(group);
+
+// }
+
+// @Override
+// public List<String> getDefaultRoles() {
+// if (isUpdated()) return updated.getDefaultRoles();
+// return cached.getDefaultRoles();
+// }
+
+// @Override
+// public void addDefaultRole(String name) {
+// getDelegateForUpdate();
+// updated.addDefaultRole(name);
+// }
+
+// @Override
+// public void updateDefaultRoles(String... defaultRoles) {
+// getDelegateForUpdate();
+// updated.updateDefaultRoles(defaultRoles);
+// }
+
+// @Override
+// public void removeDefaultRoles(String... defaultRoles) {
+// getDelegateForUpdate();
+// updated.removeDefaultRoles(defaultRoles);
+
+// }
+
+// @Override
+// public List<ClientModel> getClients() {
+// return cacheSession.getClients(this);
+
+// }
+
+// @Override
+// public ClientModel addClient(String name) {
+// return cacheSession.addClient(this, name);
+// }
+
+// @Override
+// public ClientModel addClient(String id, String clientId) {
+// return cacheSession.addClient(this, id, clientId);
+// }
+
+// @Override
+// public boolean removeClient(String id) {
+// return cacheSession.removeClient(id, this);
+// }
+
+// @Override
+// public ClientModel getClientById(String id) {
+// if (isUpdated()) return updated.getClientById(id);
+// return cacheSession.getClientById(id, this);
+// }
+
+// @Override
+// public ClientModel getClientByClientId(String clientId) {
+// return cacheSession.getClientByClientId(clientId, this);
+// }
+
+// @Override
+// public void updateRequiredCredentials(Set<String> creds) {
+// getDelegateForUpdate();
+// updated.updateRequiredCredentials(creds);
+// }
+
+// @Override
+// public Map<String, String> getBrowserSecurityHeaders() {
+// if (isUpdated()) return updated.getBrowserSecurityHeaders();
+// return cached.getBrowserSecurityHeaders();
+// }
+
+// @Override
+// public void setBrowserSecurityHeaders(Map<String, String> headers) {
+// getDelegateForUpdate();
+// updated.setBrowserSecurityHeaders(headers);
+
+// }
+
+// @Override
+// public Map<String, String> getSmtpConfig() {
+// if (isUpdated()) return updated.getSmtpConfig();
+// return cached.getSmtpConfig();
+// }
+
+// @Override
+// public void setSmtpConfig(Map<String, String> smtpConfig) {
+// getDelegateForUpdate();
+// updated.setSmtpConfig(smtpConfig);
+// }
+
+
+// @Override
+// public List<IdentityProviderModel> getIdentityProviders() {
+// if (isUpdated()) return updated.getIdentityProviders();
+// return cached.getIdentityProviders();
+// }
+
+// @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;
+// }
+
+// @Override
+// public void addIdentityProvider(IdentityProviderModel identityProvider) {
+// getDelegateForUpdate();
+// updated.addIdentityProvider(identityProvider);
+// }
+
+// @Override
+// public void updateIdentityProvider(IdentityProviderModel identityProvider) {
+// getDelegateForUpdate();
+// updated.updateIdentityProvider(identityProvider);
+// }
+
+// @Override
+// public void removeIdentityProviderByAlias(String alias) {
+// getDelegateForUpdate();
+// updated.removeIdentityProviderByAlias(alias);
+// }
+
+// @Override
+// public String getLoginTheme() {
+// if (isUpdated()) return updated.getLoginTheme();
+// return cached.getLoginTheme();
+// }
+
+// @Override
+// public void setLoginTheme(String name) {
+// getDelegateForUpdate();
+// updated.setLoginTheme(name);
+// }
+
+// @Override
+// public String getAccountTheme() {
+// if (isUpdated()) return updated.getAccountTheme();
+// return cached.getAccountTheme();
+// }
+
+// @Override
+// public void setAccountTheme(String name) {
+// getDelegateForUpdate();
+// updated.setAccountTheme(name);
+// }
+
+// @Override
+// public String getAdminTheme() {
+// if (isUpdated()) return updated.getAdminTheme();
+// return cached.getAdminTheme();
+// }
+
+// @Override
+// public void setAdminTheme(String name) {
+// getDelegateForUpdate();
+// updated.setAdminTheme(name);
+// }
+
+// @Override
+// public String getEmailTheme() {
+// if (isUpdated()) return updated.getEmailTheme();
+// return cached.getEmailTheme();
+// }
+
+// @Override
+// public void setEmailTheme(String name) {
+// getDelegateForUpdate();
+// updated.setEmailTheme(name);
+// }
+
+// @Override
+// public int getNotBefore() {
+// if (isUpdated()) return updated.getNotBefore();
+// return cached.getNotBefore();
+// }
+
+// @Override
+// public void setNotBefore(int notBefore) {
+// getDelegateForUpdate();
+// updated.setNotBefore(notBefore);
+// }
+
+// @Override
+// public boolean isEventsEnabled() {
+// if (isUpdated()) return updated.isEventsEnabled();
+// return cached.isEventsEnabled();
+// }
+
+// @Override
+// public void setEventsEnabled(boolean enabled) {
+// getDelegateForUpdate();
+// updated.setEventsEnabled(enabled);
+// }
+
+// @Override
+// public long getEventsExpiration() {
+// if (isUpdated()) return updated.getEventsExpiration();
+// return cached.getEventsExpiration();
+// }
+
+// @Override
+// public void setEventsExpiration(long expiration) {
+// getDelegateForUpdate();
+// updated.setEventsExpiration(expiration);
+// }
+
+// @Override
+// public Set<String> getEventsListeners() {
+// if (isUpdated()) return updated.getEventsListeners();
+// return cached.getEventsListeners();
+// }
+
+// @Override
+// public void setEventsListeners(Set<String> listeners) {
+// getDelegateForUpdate();
+// updated.setEventsListeners(listeners);
+// }
+
+// @Override
+// public Set<String> getEnabledEventTypes() {
+// if (isUpdated()) return updated.getEnabledEventTypes();
+// return cached.getEnabledEventTypes();
+// }
+
+// @Override
+// public void setEnabledEventTypes(Set<String> enabledEventTypes) {
+// getDelegateForUpdate();
+// updated.setEnabledEventTypes(enabledEventTypes);
+// }
+
+// @Override
+// public boolean isAdminEventsEnabled() {
+// if (isUpdated()) return updated.isAdminEventsEnabled();
+// return cached.isAdminEventsEnabled();
+// }
+
+// @Override
+// public void setAdminEventsEnabled(boolean enabled) {
+// getDelegateForUpdate();
+// updated.setAdminEventsEnabled(enabled);
+// }
+
+// @Override
+// public boolean isAdminEventsDetailsEnabled() {
+// if (isUpdated()) return updated.isAdminEventsDetailsEnabled();
+// return cached.isAdminEventsDetailsEnabled();
+// }
+
+// @Override
+// public void setAdminEventsDetailsEnabled(boolean enabled) {
+// getDelegateForUpdate();
+// updated.setAdminEventsDetailsEnabled(enabled);
+// }
+
+// @Override
+// public ClientModel getMasterAdminClient() {
+// return cached.getMasterAdminClient()==null ? null : cacheSession.getRealm(Config.getAdminRealm()).getClientById(cached.getMasterAdminClient());
+// }
+
+// @Override
+// public void setMasterAdminClient(ClientModel client) {
+// getDelegateForUpdate();
+// updated.setMasterAdminClient(client);
+// }
+
+// @Override
+// public RoleModel getRole(String name) {
+// return cacheSession.getRealmRole(this, name);
+// }
+
+// @Override
+// public Set<RoleModel> getRoles() {
+// return cacheSession.getRealmRoles(this);
+// }
+
+
+// @Override
+// public RoleModel addRole(String name) {
+// return cacheSession.addRealmRole(this, name);
+// }
+
+// @Override
+// public RoleModel addRole(String id, String name) {
+// return cacheSession.addRealmRole(this, id, name);
+// }
+
+// @Override
+// public boolean removeRole(RoleModel role) {
+// return cacheSession.removeRole(this, role);
+// }
+
+
+// @Override
+// public boolean isIdentityFederationEnabled() {
+// if (isUpdated()) return updated.isIdentityFederationEnabled();
+// return cached.isIdentityFederationEnabled();
+// }
+
+
+// @Override
+// public boolean equals(Object o) {
+// if (this == o) return true;
+// if (o == null || !(o instanceof RealmModel)) return false;
+
+// RealmModel that = (RealmModel) o;
+// return that.getId().equals(getId());
+// }
+
+// @Override
+// public int hashCode() {
+// return getId().hashCode();
+// }
+
+// @Override
+// public boolean isInternationalizationEnabled() {
+// if (isUpdated()) return updated.isInternationalizationEnabled();
+// return cached.isInternationalizationEnabled();
+// }
+
+// @Override
+// public void setInternationalizationEnabled(boolean enabled) {
+// getDelegateForUpdate();
+// updated.setInternationalizationEnabled(enabled);
+// }
+
+// @Override
+// public Set<String> getSupportedLocales() {
+// if (isUpdated()) return updated.getSupportedLocales();
+// return cached.getSupportedLocales();
+// }
+
+// @Override
+// public void setSupportedLocales(Set<String> locales) {
+// getDelegateForUpdate();
+// updated.setSupportedLocales(locales);
+// }
+
+// @Override
+// public String getDefaultLocale() {
+// if (isUpdated()) return updated.getDefaultLocale();
+// return cached.getDefaultLocale();
+// }
+
+// @Override
+// public void setDefaultLocale(String locale) {
+// updated.setDefaultLocale(locale);
+// }
+
+// @Override
+// public Set<IdentityProviderMapperModel> getIdentityProviderMappers() {
+// if (isUpdated()) return updated.getIdentityProviderMappers();
+// return cached.getIdentityProviderMapperSet();
+// }
+
+// @Override
+// public Set<IdentityProviderMapperModel> getIdentityProviderMappersByAlias(String brokerAlias) {
+// if (isUpdated()) return updated.getIdentityProviderMappersByAlias(brokerAlias);
+// Set<IdentityProviderMapperModel> mappings = new HashSet<>();
+// List<IdentityProviderMapperModel> list = cached.getIdentityProviderMappers().getList(brokerAlias);
+// for (IdentityProviderMapperModel entity : list) {
+// mappings.add(entity);
+// }
+// return Collections.unmodifiableSet(mappings);
+// }
+
+// @Override
+// public IdentityProviderMapperModel addIdentityProviderMapper(IdentityProviderMapperModel model) {
+// getDelegateForUpdate();
+// return updated.addIdentityProviderMapper(model);
+// }
+
+// @Override
+// public void removeIdentityProviderMapper(IdentityProviderMapperModel mapping) {
+// getDelegateForUpdate();
+// updated.removeIdentityProviderMapper(mapping);
+// }
+
+// @Override
+// public void updateIdentityProviderMapper(IdentityProviderMapperModel mapping) {
+// getDelegateForUpdate();
+// updated.updateIdentityProviderMapper(mapping);
+// }
+
+// @Override
+// public IdentityProviderMapperModel getIdentityProviderMapperById(String id) {
+// if (isUpdated()) return updated.getIdentityProviderMapperById(id);
+// for (List<IdentityProviderMapperModel> models : cached.getIdentityProviderMappers().values()) {
+// for (IdentityProviderMapperModel model : models) {
+// if (model.getId().equals(id)) return model;
+// }
+// }
+// return null;
+// }
+
+// @Override
+// public IdentityProviderMapperModel getIdentityProviderMapperByName(String alias, String name) {
+// if (isUpdated()) return updated.getIdentityProviderMapperByName(alias, name);
+// List<IdentityProviderMapperModel> models = cached.getIdentityProviderMappers().getList(alias);
+// if (models == null) return null;
+// for (IdentityProviderMapperModel model : models) {
+// if (model.getName().equals(name)) return model;
+// }
+// return null;
+// }
+
+// @Override
+// public AuthenticationFlowModel getBrowserFlow() {
+// if (isUpdated()) return updated.getBrowserFlow();
+// return cached.getBrowserFlow();
+// }
+
+// @Override
+// public void setBrowserFlow(AuthenticationFlowModel flow) {
+// getDelegateForUpdate();
+// updated.setBrowserFlow(flow);
+
+// }
+
+// @Override
+// public AuthenticationFlowModel getRegistrationFlow() {
+// if (isUpdated()) return updated.getRegistrationFlow();
+// return cached.getRegistrationFlow();
+// }
+
+// @Override
+// public void setRegistrationFlow(AuthenticationFlowModel flow) {
+// getDelegateForUpdate();
+// updated.setRegistrationFlow(flow);
+
+// }
+
+// @Override
+// public AuthenticationFlowModel getDirectGrantFlow() {
+// if (isUpdated()) return updated.getDirectGrantFlow();
+// return cached.getDirectGrantFlow();
+// }
+
+// @Override
+// public void setDirectGrantFlow(AuthenticationFlowModel flow) {
+// getDelegateForUpdate();
+// updated.setDirectGrantFlow(flow);
+
+// }
+// @Override
+// public AuthenticationFlowModel getResetCredentialsFlow() {
+// if (isUpdated()) return updated.getResetCredentialsFlow();
+// return cached.getResetCredentialsFlow();
+// }
+
+// @Override
+// public void setResetCredentialsFlow(AuthenticationFlowModel flow) {
+// getDelegateForUpdate();
+// updated.setResetCredentialsFlow(flow);
+
+// }
+
+// @Override
+// public AuthenticationFlowModel getClientAuthenticationFlow() {
+// if (isUpdated()) return updated.getClientAuthenticationFlow();
+// return cached.getClientAuthenticationFlow();
+// }
+
+// @Override
+// public void setClientAuthenticationFlow(AuthenticationFlowModel flow) {
+// getDelegateForUpdate();
+// updated.setClientAuthenticationFlow(flow);
+// }
+
+// @Override
+// public AuthenticationFlowModel getDockerAuthenticationFlow() {
+// if (isUpdated()) return updated.getDockerAuthenticationFlow();
+// return cached.getDockerAuthenticationFlow();
+// }
+
+// @Override
+// public void setDockerAuthenticationFlow(final AuthenticationFlowModel flow) {
+// getDelegateForUpdate();
+// updated.setDockerAuthenticationFlow(flow);
+// }
+
+// @Override
+// public List<AuthenticationFlowModel> getAuthenticationFlows() {
+// if (isUpdated()) return updated.getAuthenticationFlows();
+// return cached.getAuthenticationFlowList();
+// }
+
+// @Override
+// public AuthenticationFlowModel getFlowByAlias(String alias) {
+// for (AuthenticationFlowModel flow : getAuthenticationFlows()) {
+// if (flow.getAlias().equals(alias)) {
+// return flow;
+// }
+// }
+// return null;
+// }
+
+// @Override
+// public AuthenticatorConfigModel getAuthenticatorConfigByAlias(String alias) {
+// for (AuthenticatorConfigModel config : getAuthenticatorConfigs()) {
+// if (config.getAlias().equals(alias)) {
+// return config;
+// }
+// }
+// return null;
+// }
+
+
+// @Override
+// public AuthenticationFlowModel addAuthenticationFlow(AuthenticationFlowModel model) {
+// getDelegateForUpdate();
+// return updated.addAuthenticationFlow(model);
+// }
+
+// @Override
+// public AuthenticationFlowModel getAuthenticationFlowById(String id) {
+// if (isUpdated()) return updated.getAuthenticationFlowById(id);
+// return cached.getAuthenticationFlows().get(id);
+// }
+
+// @Override
+// public void removeAuthenticationFlow(AuthenticationFlowModel model) {
+// getDelegateForUpdate();
+// updated.removeAuthenticationFlow(model);
+
+// }
+
+// @Override
+// public void updateAuthenticationFlow(AuthenticationFlowModel model) {
+// getDelegateForUpdate();
+// updated.updateAuthenticationFlow(model);
+
+// }
+
+// @Override
+// public List<AuthenticationExecutionModel> getAuthenticationExecutions(String flowId) {
+// if (isUpdated()) return updated.getAuthenticationExecutions(flowId);
+// return cached.getAuthenticationExecutions().get(flowId);
+// }
+
+// @Override
+// public AuthenticationExecutionModel getAuthenticationExecutionById(String id) {
+// if (isUpdated()) return updated.getAuthenticationExecutionById(id);
+// return cached.getExecutionsById().get(id);
+// }
+
+// @Override
+// public AuthenticationExecutionModel addAuthenticatorExecution(AuthenticationExecutionModel model) {
+// getDelegateForUpdate();
+// return updated.addAuthenticatorExecution(model);
+// }
+
+// @Override
+// public void updateAuthenticatorExecution(AuthenticationExecutionModel model) {
+// getDelegateForUpdate();
+// updated.updateAuthenticatorExecution(model);
+
+// }
+
+// @Override
+// public void removeAuthenticatorExecution(AuthenticationExecutionModel model) {
+// getDelegateForUpdate();
+// updated.removeAuthenticatorExecution(model);
+
+// }
+
+// @Override
+// public List<AuthenticatorConfigModel> getAuthenticatorConfigs() {
+// if (isUpdated()) return updated.getAuthenticatorConfigs();
+// List<AuthenticatorConfigModel> models = new ArrayList<>();
+// models.addAll(cached.getAuthenticatorConfigs().values());
+// return Collections.unmodifiableList(models);
+// }
+
+// @Override
+// public AuthenticatorConfigModel addAuthenticatorConfig(AuthenticatorConfigModel model) {
+// getDelegateForUpdate();
+// return updated.addAuthenticatorConfig(model);
+// }
+
+// @Override
+// public void updateAuthenticatorConfig(AuthenticatorConfigModel model) {
+// getDelegateForUpdate();
+// updated.updateAuthenticatorConfig(model);
+
+// }
+
+// @Override
+// public void removeAuthenticatorConfig(AuthenticatorConfigModel model) {
+// getDelegateForUpdate();
+// updated.removeAuthenticatorConfig(model);
+
+// }
+
+// @Override
+// public AuthenticatorConfigModel getAuthenticatorConfigById(String id) {
+// if (isUpdated()) return updated.getAuthenticatorConfigById(id);
+// return cached.getAuthenticatorConfigs().get(id);
+// }
+
+// @Override
+// public List<RequiredActionProviderModel> getRequiredActionProviders() {
+// if (isUpdated()) return updated.getRequiredActionProviders();
+// return cached.getRequiredActionProviderList();
+// }
+
+// @Override
+// public RequiredActionProviderModel addRequiredActionProvider(RequiredActionProviderModel model) {
+// getDelegateForUpdate();
+// return updated.addRequiredActionProvider(model);
+// }
+
+// @Override
+// public void updateRequiredActionProvider(RequiredActionProviderModel model) {
+// getDelegateForUpdate();
+// updated.updateRequiredActionProvider(model);
+
+// }
+
+// @Override
+// public void removeRequiredActionProvider(RequiredActionProviderModel model) {
+// getDelegateForUpdate();
+// updated.removeRequiredActionProvider(model);
+
+// }
+
+// @Override
+// public RequiredActionProviderModel getRequiredActionProviderById(String id) {
+// if (isUpdated()) return updated.getRequiredActionProviderById(id);
+// return cached.getRequiredActionProviders().get(id);
+// }
+
+// @Override
+// public RequiredActionProviderModel getRequiredActionProviderByAlias(String alias) {
+// if (isUpdated()) return updated.getRequiredActionProviderByAlias(alias);
+// return cached.getRequiredActionProvidersByAlias().get(alias);
+// }
+
+// @Override
+// public GroupModel createGroup(String name) {
+// return cacheSession.createGroup(this, name);
+// }
+
+// @Override
+// public GroupModel createGroup(String id, String name) {
+// return cacheSession.createGroup(this, id, name);
+// }
+
+// @Override
+// public void moveGroup(GroupModel group, GroupModel toParent) {
+// cacheSession.moveGroup(this, group, toParent);
+// }
+
+// @Override
+// public GroupModel getGroupById(String id) {
+// return cacheSession.getGroupById(id, this);
+// }
+
+// @Override
+// public List<GroupModel> getGroups() {
+// return cacheSession.getGroups(this);
+// }
+
+// @Override
+// public Long getGroupsCount(Boolean onlyTopGroups) {
+// return cacheSession.getGroupsCount(this, onlyTopGroups);
+// }
+
+// @Override
+// public Long getGroupsCountByNameContaining(String search) {
+// return cacheSession.getGroupsCountByNameContaining(this, search);
+// }
+
+// @Override
+// public List<GroupModel> getTopLevelGroups() {
+// return cacheSession.getTopLevelGroups(this);
+// }
+
+// @Override
+// public List<GroupModel> getTopLevelGroups(Integer first, Integer max) {
+// return cacheSession.getTopLevelGroups(this, first, max);
+// }
+
+// @Override
+// public List<GroupModel> searchForGroupByName(String search, Integer first, Integer max) {
+// return cacheSession.searchForGroupByName(this, search, first, max);
+// }
+
+// @Override
+// public boolean removeGroup(GroupModel group) {
+// return cacheSession.removeGroup(this, group);
+// }
+
+// @Override
+// public List<ClientScopeModel> getClientScopes() {
+// if (isUpdated()) return updated.getClientScopes();
+// List<String> clientScopes = cached.getClientScopes();
+// if (clientScopes.isEmpty()) return Collections.EMPTY_LIST;
+// List<ClientScopeModel> apps = new LinkedList<ClientScopeModel>();
+// for (String id : clientScopes) {
+// ClientScopeModel model = cacheSession.getClientScopeById(id, this);
+// if (model == null) {
+// throw new IllegalStateException("Cached clientScope not found: " + id);
+// }
+// apps.add(model);
+// }
+// return Collections.unmodifiableList(apps);
+
+// }
+
+// @Override
+// public ClientScopeModel addClientScope(String name) {
+// getDelegateForUpdate();
+// ClientScopeModel app = updated.addClientScope(name);
+// cacheSession.registerClientScopeInvalidation(app.getId());
+// return app;
+// }
+
+// @Override
+// public ClientScopeModel addClientScope(String id, String name) {
+// getDelegateForUpdate();
+// ClientScopeModel app = updated.addClientScope(id, name);
+// cacheSession.registerClientScopeInvalidation(app.getId());
+// return app;
+// }
+
+// @Override
+// public boolean removeClientScope(String id) {
+// cacheSession.registerClientScopeInvalidation(id);
+// getDelegateForUpdate();
+// return updated.removeClientScope(id);
+// }
+
+// @Override
+// public ClientScopeModel getClientScopeById(String id) {
+// if (isUpdated()) return updated.getClientScopeById(id);
+// return cacheSession.getClientScopeById(id, this);
+// }
+
+// @Override
+// public void addDefaultClientScope(ClientScopeModel clientScope, boolean defaultScope) {
+// getDelegateForUpdate();
+// updated.addDefaultClientScope(clientScope, defaultScope);
+// }
+
+// @Override
+// public void removeDefaultClientScope(ClientScopeModel clientScope) {
+// getDelegateForUpdate();
+// updated.removeDefaultClientScope(clientScope);
+// }
+
+// @Override
+// public List<ClientScopeModel> getDefaultClientScopes(boolean defaultScope) {
+// if (isUpdated()) return updated.getDefaultClientScopes(defaultScope);
+
+// List<String> clientScopeIds = defaultScope ? cached.getDefaultDefaultClientScopes() : cached.getOptionalDefaultClientScopes();
+
+// List<ClientScopeModel> clientScopes = new LinkedList<>();
+// for (String scopeId : clientScopeIds) {
+// ClientScopeModel clientScope = cacheSession.getClientScopeById(scopeId, this);
+// if (clientScope != null) {
+// clientScopes.add(clientScope);
+// }
+// }
+// return clientScopes;
+// }
+
+// @Override
+// public ComponentModel addComponentModel(ComponentModel model) {
+// getDelegateForUpdate();
+// executeEvictions(model);
+// return updated.addComponentModel(model);
+// }
+
+// @Override
+// public ComponentModel importComponentModel(ComponentModel model) {
+// getDelegateForUpdate();
+// executeEvictions(model);
+// return updated.importComponentModel(model);
+// }
+
+// public void executeEvictions(ComponentModel model) {
+// if (model == null) return;
+// // If not realm component, check to see if it is a user storage provider child component (i.e. LDAP mapper)
+// if (model.getParentId() != null && !model.getParentId().equals(getId())) {
+// ComponentModel parent = getComponent(model.getParentId());
+// if (parent != null && UserStorageProvider.class.getName().equals(parent.getProviderType())) {
+// session.userCache().evict(this);
+// }
+// return;
+// }
+
+// // invalidate entire user cache if we're dealing with user storage SPI
+// if (UserStorageProvider.class.getName().equals(model.getProviderType())) {
+// session.userCache().evict(this);
+// }
+// // invalidate entire realm if we're dealing with client storage SPI
+// // entire realm because of client roles, client lists, and clients
+// if (ClientStorageProvider.class.getName().equals(model.getProviderType())) {
+// cacheSession.evictRealmOnRemoval(this);
+// }
+// }
+
+// @Override
+// public void updateComponent(ComponentModel component) {
+// getDelegateForUpdate();
+// executeEvictions(component);
+// updated.updateComponent(component);
+
+// }
+
+// @Override
+// public void removeComponent(ComponentModel component) {
+// getDelegateForUpdate();
+// executeEvictions(component);
+// updated.removeComponent(component);
+
+// }
+
+// @Override
+// public void removeComponents(String parentId) {
+// getDelegateForUpdate();
+// updated.removeComponents(parentId);
+
+// }
+
+// @Override
+// public List<ComponentModel> getComponents(String parentId, String providerType) {
+// if (isUpdated()) return updated.getComponents(parentId, providerType);
+// List<ComponentModel> components = cached.getComponentsByParentAndType().getList(parentId + providerType);
+// if (components == null) return Collections.EMPTY_LIST;
+// return Collections.unmodifiableList(components);
+// }
+
+// @Override
+// public List<ComponentModel> getComponents(String parentId) {
+// if (isUpdated()) return updated.getComponents(parentId);
+// List<ComponentModel> components = cached.getComponentsByParent().getList(parentId);
+// if (components == null) return Collections.EMPTY_LIST;
+// return Collections.unmodifiableList(components);
+// }
+
+// @Override
+// public List<ComponentModel> getComponents() {
+// if (isUpdated()) return updated.getComponents();
+// List<ComponentModel> results = new LinkedList<>();
+// results.addAll(cached.getComponents().values());
+// return Collections.unmodifiableList(results);
+// }
+
+// @Override
+// public ComponentModel getComponent(String id) {
+// if (isUpdated()) return updated.getComponent(id);
+// return cached.getComponents().get(id);
+// }
+
+// public void setAttribute(String name, String value) {
+// getDelegateForUpdate();
+// updated.setAttribute(name, value);
+// }
+
+// @Override
+// public void setAttribute(String name, Boolean value) {
+// getDelegateForUpdate();
+// updated.setAttribute(name, value);
+// }
+
+// @Override
+// public void setAttribute(String name, Integer value) {
+// getDelegateForUpdate();
+// updated.setAttribute(name, value);
+// }
+
+// @Override
+// public void setAttribute(String name, Long value) {
+// getDelegateForUpdate();
+// updated.setAttribute(name, value);
+// }
+
+// @Override
+// public void removeAttribute(String name) {
+// getDelegateForUpdate();
+// updated.removeAttribute(name);
+// }
+
+// @Override
+// public String getAttribute(String name) {
+// if (isUpdated()) return updated.getAttribute(name);
+// return cached.getAttribute(name);
+// }
+
+// @Override
+// public Integer getAttribute(String name, Integer defaultValue) {
+// if (isUpdated()) return updated.getAttribute(name, defaultValue);
+// return cached.getAttribute(name, defaultValue);
+// }
+
+// @Override
+// public Long getAttribute(String name, Long defaultValue) {
+// if (isUpdated()) return updated.getAttribute(name, defaultValue);
+// return cached.getAttribute(name, defaultValue);
+// }
+
+// @Override
+// public Boolean getAttribute(String name, Boolean defaultValue) {
+// if (isUpdated()) return updated.getAttribute(name, defaultValue);
+// return cached.getAttribute(name, defaultValue);
+// }
+
+// @Override
+// public Map<String, String> getAttributes() {
+// if (isUpdated()) return updated.getAttributes();
+// return cached.getAttributes();
+// }
+
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmCacheManager.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmCacheManager.java
index ed562ac..f936934 100755
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmCacheManager.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RealmCacheManager.java
@@ -1,105 +1,105 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan;
-
-import org.infinispan.Cache;
-import org.jboss.logging.Logger;
-import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
-import org.keycloak.models.cache.infinispan.entities.Revisioned;
-import org.keycloak.models.cache.infinispan.events.RealmCacheInvalidationEvent;
-import org.keycloak.models.cache.infinispan.stream.GroupListPredicate;
-import org.keycloak.models.cache.infinispan.stream.HasRolePredicate;
-import org.keycloak.models.cache.infinispan.stream.InClientPredicate;
-import org.keycloak.models.cache.infinispan.stream.InRealmPredicate;
-
-import java.util.Set;
-
-/**
- * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
- */
-public class RealmCacheManager extends CacheManager {
-
- private static final Logger logger = Logger.getLogger(RealmCacheManager.class);
-
- @Override
- protected Logger getLogger() {
- return logger;
- }
-
- public RealmCacheManager(Cache<String, Revisioned> cache, Cache<String, Long> revisions) {
- super(cache, revisions);
- }
-
-
- public void realmUpdated(String id, String name, Set<String> invalidations) {
- invalidations.add(id);
- invalidations.add(RealmCacheSession.getRealmByNameCacheKey(name));
- }
-
- public void realmRemoval(String id, String name, Set<String> invalidations) {
- realmUpdated(id, name, invalidations);
-
- addInvalidations(InRealmPredicate.create().realm(id), invalidations);
- }
-
- public void roleAdded(String roleContainerId, Set<String> invalidations) {
- invalidations.add(RealmCacheSession.getRolesCacheKey(roleContainerId));
- }
-
- public void roleUpdated(String roleContainerId, String roleName, Set<String> invalidations) {
- invalidations.add(RealmCacheSession.getRoleByNameCacheKey(roleContainerId, roleName));
- }
-
- public void roleRemoval(String id, String roleName, String roleContainerId, Set<String> invalidations) {
- invalidations.add(RealmCacheSession.getRolesCacheKey(roleContainerId));
- invalidations.add(RealmCacheSession.getRoleByNameCacheKey(roleContainerId, roleName));
-
- addInvalidations(HasRolePredicate.create().role(id), invalidations);
- }
-
- public void groupQueriesInvalidations(String realmId, Set<String> invalidations) {
- invalidations.add(RealmCacheSession.getGroupsQueryCacheKey(realmId));
- invalidations.add(RealmCacheSession.getTopGroupsQueryCacheKey(realmId));
- addInvalidations(GroupListPredicate.create().realm(realmId), invalidations);
- }
-
- public void clientAdded(String realmId, String clientUUID, String clientId, Set<String> invalidations) {
- invalidations.add(RealmCacheSession.getRealmClientsQueryCacheKey(realmId));
- }
-
- public void clientUpdated(String realmId, String clientUuid, String clientId, Set<String> invalidations) {
- invalidations.add(RealmCacheSession.getClientByClientIdCacheKey(clientId, realmId));
- }
-
- // Client roles invalidated separately
- public void clientRemoval(String realmId, String clientUUID, String clientId, Set<String> invalidations) {
- invalidations.add(RealmCacheSession.getRealmClientsQueryCacheKey(realmId));
- invalidations.add(RealmCacheSession.getClientByClientIdCacheKey(clientId, realmId));
-
- addInvalidations(InClientPredicate.create().client(clientUUID), invalidations);
- }
-
-
- @Override
- protected void addInvalidationsFromEvent(InvalidationEvent event, Set<String> invalidations) {
- invalidations.add(event.getId());
-
- ((RealmCacheInvalidationEvent) event).addInvalidations(this, invalidations);
- }
-
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan;
+
+// import org.infinispan.Cache;
+// import org.jboss.logging.Logger;
+// import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
+// import org.keycloak.models.cache.infinispan.entities.Revisioned;
+// import org.keycloak.models.cache.infinispan.events.RealmCacheInvalidationEvent;
+// import org.keycloak.models.cache.infinispan.stream.GroupListPredicate;
+// import org.keycloak.models.cache.infinispan.stream.HasRolePredicate;
+// import org.keycloak.models.cache.infinispan.stream.InClientPredicate;
+// import org.keycloak.models.cache.infinispan.stream.InRealmPredicate;
+
+// import java.util.Set;
+
+// /**
+// * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
+// */
+// public class RealmCacheManager extends CacheManager {
+
+// private static final Logger logger = Logger.getLogger(RealmCacheManager.class);
+
+// @Override
+// protected Logger getLogger() {
+// return logger;
+// }
+
+// public RealmCacheManager(Cache<String, Revisioned> cache, Cache<String, Long> revisions) {
+// super(cache, revisions);
+// }
+
+
+// public void realmUpdated(String id, String name, Set<String> invalidations) {
+// invalidations.add(id);
+// invalidations.add(RealmCacheSession.getRealmByNameCacheKey(name));
+// }
+
+// public void realmRemoval(String id, String name, Set<String> invalidations) {
+// realmUpdated(id, name, invalidations);
+
+// addInvalidations(InRealmPredicate.create().realm(id), invalidations);
+// }
+
+// public void roleAdded(String roleContainerId, Set<String> invalidations) {
+// invalidations.add(RealmCacheSession.getRolesCacheKey(roleContainerId));
+// }
+
+// public void roleUpdated(String roleContainerId, String roleName, Set<String> invalidations) {
+// invalidations.add(RealmCacheSession.getRoleByNameCacheKey(roleContainerId, roleName));
+// }
+
+// public void roleRemoval(String id, String roleName, String roleContainerId, Set<String> invalidations) {
+// invalidations.add(RealmCacheSession.getRolesCacheKey(roleContainerId));
+// invalidations.add(RealmCacheSession.getRoleByNameCacheKey(roleContainerId, roleName));
+
+// addInvalidations(HasRolePredicate.create().role(id), invalidations);
+// }
+
+// public void groupQueriesInvalidations(String realmId, Set<String> invalidations) {
+// invalidations.add(RealmCacheSession.getGroupsQueryCacheKey(realmId));
+// invalidations.add(RealmCacheSession.getTopGroupsQueryCacheKey(realmId));
+// addInvalidations(GroupListPredicate.create().realm(realmId), invalidations);
+// }
+
+// public void clientAdded(String realmId, String clientUUID, String clientId, Set<String> invalidations) {
+// invalidations.add(RealmCacheSession.getRealmClientsQueryCacheKey(realmId));
+// }
+
+// public void clientUpdated(String realmId, String clientUuid, String clientId, Set<String> invalidations) {
+// invalidations.add(RealmCacheSession.getClientByClientIdCacheKey(clientId, realmId));
+// }
+
+// // Client roles invalidated separately
+// public void clientRemoval(String realmId, String clientUUID, String clientId, Set<String> invalidations) {
+// invalidations.add(RealmCacheSession.getRealmClientsQueryCacheKey(realmId));
+// invalidations.add(RealmCacheSession.getClientByClientIdCacheKey(clientId, realmId));
+
+// addInvalidations(InClientPredicate.create().client(clientUUID), invalidations);
+// }
+
+
+// @Override
+// protected void addInvalidationsFromEvent(InvalidationEvent event, Set<String> invalidations) {
+// invalidations.add(event.getId());
+
+// ((RealmCacheInvalidationEvent) event).addInvalidations(this, invalidations);
+// }
+
+// }
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 e781c6f..f2ca4ca 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
@@ -1,1199 +1,1200 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan;
-
-import org.jboss.logging.Logger;
-import org.keycloak.cluster.ClusterProvider;
-import org.keycloak.component.ComponentModel;
-import org.keycloak.migration.MigrationModel;
-import org.keycloak.models.*;
-import org.keycloak.models.cache.CacheRealmProvider;
-import org.keycloak.models.cache.CachedRealmModel;
-import org.keycloak.models.cache.infinispan.entities.*;
-import org.keycloak.models.cache.infinispan.events.*;
-import org.keycloak.models.utils.KeycloakModelUtils;
-import org.keycloak.storage.StorageId;
-import org.keycloak.storage.client.ClientStorageProviderModel;
-
-import java.util.*;
-
-
-/**
- * - the high level architecture of this cache is an invalidation cache.
- * - the cache is manual/custom versioned. When a model is updated, we remove it from the cache
- * which causes an invalidation message to be sent across the cluster.
- * - We had to do it this way because Infinispan REPEATABLE_READ
- * wouldn't cut it in invalidation mode. Also, REPEATABLE_READ doesn't work very well on relationships and items that are
- * not in the cache.
- * - There are two Infinispan caches. One clustered that holds actual objects and a another local one that holds revision
- * numbers of cached objects. Whenever a cached object is removed (invalidated), the local revision
- * cache number or that key is bumped higher based on a local version counter. Whenever a cache entry is fetched, this
- * revision number is also fetched and compared against the revision number in the cache entry to see if the cache entry
- * is stale. Whenever a cache entry is added, this revision number is also checked against the revision cache.
- * - Revision entries are actually never removed (although they could be evicted by cache eviction policies). The reason for this
- * is that it is possible for a stale object to be inserted if one thread loads and the data is updated in the database before
- * it is added to the cache. So, we keep the version number around for this.
- * - In a transaction, objects are registered to be invalidated. If an object is marked for invalidation within a transaction
- * a cached object should never be returned. An DB adapter should always be returned.
- * - After DB commits, the objects marked for invalidation are invalidated, or rather removed from the cache. At this time
- * the revision cache entry for this object has its version number bumped.
- * - Whenever an object is marked for invalidation, the cache is also searched for any objects that are related to this object
- * and need to also be evicted/removed. We use the Infinispan Stream SPI for this.
- *
- * ClientList caches:
- * - lists of clients are cached in a specific cache entry i.e. realm clients, find client by clientId
- * - realm client lists need to be invalidated and evited whenever a client is added or removed from a realm. RealmProvider
- * now has addClient/removeClient at its top level. All adapaters should use these methods so that the appropriate invalidations
- * can be registered.
- * - whenever a client is added/removed the realm of the client is added to a listInvalidations set
- * this set must be checked before sending back or caching a cached query. This check is required to
- * avoid caching an uncommitted removal/add in a query cache.
- * - when a client is removed, any queries that contain that client must also be removed.
- * - a client removal will also cause anything that is contained and cached within that client to be removed
- *
- * Clustered caches:
- * - There is a Infinispan @Listener registered. If an invalidation event happens, this is treated like
- * the object was removed from the database and will perform evictions based on that assumption.
- * - Eviction events will also cascade other evictions, but not assume this is a db removal.
- * - With an invalidation cache, if you remove an entry on node 1 and this entry does not exist on node 2, node 2 will not receive a @Listener invalidation event.
- * so, hat we have to put a marker entry in the invalidation cache before we read from the DB, so if the DB changes in between reading and adding a cache entry, the cache will be notified and bump
- * the version information.
- *
- * DBs with Repeatable Read:
- * - DBs like MySQL are Repeatable Read by default. So, if you query a Client for instance, it will always return the same result in the same transaction even if the DB
- * was updated in between these queries. This makes it possible to store stale cache entries. To avoid this problem, this class stores the current local version counter
- * at the beginningof the transaction. Whenever an entry is added to the cache, the current coutner is compared against the counter at the beginning of the tx. If the current
- * is greater, then don't cache.
- *
- * Groups and Roles:
- * - roles are tricky because of composites. Composite lists are cached too. So, when a role is removed
- * we also iterate and invalidate any role or group that contains that role being removed.
- *
- * - any relationship should be resolved from session.realms(). For example if JPA.getClientByClientId() is invoked,
- * JPA should find the id of the client and then call session.realms().getClientById(). THis is to ensure that the cached
- * object is invoked and all proper invalidation are being invoked.
- *
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class RealmCacheSession implements CacheRealmProvider {
- protected static final Logger logger = Logger.getLogger(RealmCacheSession.class);
- public static final String REALM_CLIENTS_QUERY_SUFFIX = ".realm.clients";
- public static final String ROLES_QUERY_SUFFIX = ".roles";
- protected RealmCacheManager cache;
- protected KeycloakSession session;
- protected RealmProvider realmDelegate;
- protected ClientProvider clientDelegate;
- protected boolean transactionActive;
- protected boolean setRollbackOnly;
-
- protected Map<String, RealmAdapter> managedRealms = new HashMap<>();
- protected Map<String, ClientModel> managedApplications = new HashMap<>();
- protected Map<String, ClientScopeAdapter> managedClientScopes = new HashMap<>();
- protected Map<String, RoleAdapter> managedRoles = new HashMap<>();
- protected Map<String, GroupAdapter> managedGroups = new HashMap<>();
- protected Set<String> listInvalidations = new HashSet<>();
- protected Set<String> invalidations = new HashSet<>();
- protected Set<InvalidationEvent> invalidationEvents = new HashSet<>(); // Events to be sent across cluster
-
- protected boolean clearAll;
- protected final long startupRevision;
-
- public RealmCacheSession(RealmCacheManager cache, KeycloakSession session) {
- this.cache = cache;
- this.session = session;
- this.startupRevision = cache.getCurrentCounter();
- session.getTransactionManager().enlistPrepare(getPrepareTransaction());
- session.getTransactionManager().enlistAfterCompletion(getAfterTransaction());
- }
-
- public long getStartupRevision() {
- return startupRevision;
- }
-
- public boolean isInvalid(String id) {
- return invalidations.contains(id);
- }
-
- @Override
- public void clear() {
- ClusterProvider cluster = session.getProvider(ClusterProvider.class);
- cluster.notify(InfinispanCacheRealmProviderFactory.REALM_CLEAR_CACHE_EVENTS, new ClearCacheEvent(), false, ClusterProvider.DCNotify.ALL_DCS);
- }
-
- @Override
- public MigrationModel getMigrationModel() {
- return getRealmDelegate().getMigrationModel();
- }
-
- @Override
- public RealmProvider getRealmDelegate() {
- if (!transactionActive) throw new IllegalStateException("Cannot access delegate without a transaction");
- if (realmDelegate != null) return realmDelegate;
- realmDelegate = session.realmLocalStorage();
- return realmDelegate;
- }
- public ClientProvider getClientDelegate() {
- if (!transactionActive) throw new IllegalStateException("Cannot access delegate without a transaction");
- if (clientDelegate != null) return clientDelegate;
- clientDelegate = session.clientStorageManager();
- return clientDelegate;
- }
-
-
-
-
- @Override
- public void registerRealmInvalidation(String id, String name) {
- cache.realmUpdated(id, name, invalidations);
- RealmAdapter adapter = managedRealms.get(id);
- if (adapter != null) adapter.invalidateFlag();
-
- invalidationEvents.add(RealmUpdatedEvent.create(id, name));
- }
-
- @Override
- public void registerClientInvalidation(String id, String clientId, String realmId) {
- invalidateClient(id);
- invalidationEvents.add(ClientUpdatedEvent.create(id, clientId, realmId));
- cache.clientUpdated(realmId, id, clientId, invalidations);
- }
-
- private void invalidateClient(String id) {
- invalidations.add(id);
- ClientModel adapter = managedApplications.get(id);
- if (adapter != null && adapter instanceof ClientAdapter) ((ClientAdapter)adapter).invalidate();
- }
-
- @Override
- public void registerClientScopeInvalidation(String id) {
- invalidateClientScope(id);
- // Note: Adding/Removing client template is supposed to invalidate CachedRealm as well, so the list of clientScopes is invalidated.
- // But separate RealmUpdatedEvent will be sent for it. So ClientTemplateEvent don't need to take care of it.
- invalidationEvents.add(ClientTemplateEvent.create(id));
- }
-
- private void invalidateClientScope(String id) {
- invalidations.add(id);
- ClientScopeAdapter adapter = managedClientScopes.get(id);
- if (adapter != null) adapter.invalidate();
- }
-
- @Override
- public void registerRoleInvalidation(String id, String roleName, String roleContainerId) {
- invalidateRole(id);
- cache.roleUpdated(roleContainerId, roleName, invalidations);
- invalidationEvents.add(RoleUpdatedEvent.create(id, roleName, roleContainerId));
- }
-
- private void roleRemovalInvalidations(String roleId, String roleName, String roleContainerId) {
- Set<String> newInvalidations = new HashSet<>();
- cache.roleRemoval(roleId, roleName, roleContainerId, newInvalidations);
- invalidations.addAll(newInvalidations);
- // need to make sure that scope and group mapping clients and groups are invalidated
- for (String id : newInvalidations) {
- ClientModel adapter = managedApplications.get(id);
- if (adapter != null && adapter instanceof ClientAdapter){
- ((ClientAdapter)adapter).invalidate();
- continue;
- }
- GroupAdapter group = managedGroups.get(id);
- if (group != null) {
- group.invalidate();
- continue;
- }
- ClientScopeAdapter clientScope = managedClientScopes.get(id);
- if (clientScope != null) {
- clientScope.invalidate();
- continue;
- }
- RoleAdapter role = managedRoles.get(id);
- if (role != null) {
- role.invalidate();
- continue;
- }
-
-
- }
- }
-
-
-
-
- private void invalidateRole(String id) {
- invalidations.add(id);
- RoleAdapter adapter = managedRoles.get(id);
- if (adapter != null) adapter.invalidate();
- }
-
- private void addedRole(String roleId, String roleContainerId) {
- // this is needed so that a new role that hasn't been committed isn't cached in a query
- listInvalidations.add(roleContainerId);
-
- invalidateRole(roleId);
- cache.roleAdded(roleContainerId, invalidations);
- invalidationEvents.add(RoleAddedEvent.create(roleId, roleContainerId));
- }
-
- @Override
- public void registerGroupInvalidation(String id) {
- invalidateGroup(id, null, false);
- addGroupEventIfAbsent(GroupUpdatedEvent.create(id));
- }
-
- private void invalidateGroup(String id, String realmId, boolean invalidateQueries) {
- invalidateGroup(id);
- if (invalidateQueries) {
- cache.groupQueriesInvalidations(realmId, invalidations);
- }
- }
-
- private void invalidateGroup(String id) {
- invalidations.add(id);
- GroupAdapter adapter = managedGroups.get(id);
- if (adapter != null) adapter.invalidate();
- }
-
- protected void runInvalidations() {
- for (String id : invalidations) {
- cache.invalidateObject(id);
- }
-
- cache.sendInvalidationEvents(session, invalidationEvents, InfinispanCacheRealmProviderFactory.REALM_INVALIDATION_EVENTS);
- }
-
- private KeycloakTransaction getPrepareTransaction() {
- return new KeycloakTransaction() {
- @Override
- public void begin() {
- transactionActive = true;
- }
-
- @Override
- public void commit() {
- /* THIS WAS CAUSING DEADLOCK IN A CLUSTER
- if (delegate == null) return;
- List<String> locks = new LinkedList<>();
- locks.addAll(invalidations);
-
- Collections.sort(locks); // lock ordering
- cache.getRevisions().startBatch();
-
- if (!locks.isEmpty()) cache.getRevisions().getAdvancedCache().lock(locks);
- */
-
- }
-
- @Override
- public void rollback() {
- setRollbackOnly = true;
- transactionActive = false;
- }
-
- @Override
- public void setRollbackOnly() {
- setRollbackOnly = true;
- }
-
- @Override
- public boolean getRollbackOnly() {
- return setRollbackOnly;
- }
-
- @Override
- public boolean isActive() {
- return transactionActive;
- }
- };
- }
-
- private KeycloakTransaction getAfterTransaction() {
- return new KeycloakTransaction() {
- @Override
- public void begin() {
- transactionActive = true;
- }
-
- @Override
- public void commit() {
- try {
- if (clearAll) {
- cache.clear();
- }
- runInvalidations();
- transactionActive = false;
- } finally {
- cache.endRevisionBatch();
- }
- }
-
- @Override
- public void rollback() {
- try {
- setRollbackOnly = true;
- runInvalidations();
- transactionActive = false;
- } finally {
- cache.endRevisionBatch();
- }
- }
-
- @Override
- public void setRollbackOnly() {
- setRollbackOnly = true;
- }
-
- @Override
- public boolean getRollbackOnly() {
- return setRollbackOnly;
- }
-
- @Override
- public boolean isActive() {
- return transactionActive;
- }
- };
- }
-
- @Override
- public RealmModel createRealm(String name) {
- RealmModel realm = getRealmDelegate().createRealm(name);
- registerRealmInvalidation(realm.getId(), realm.getName());
- return realm;
- }
-
- @Override
- public RealmModel createRealm(String id, String name) {
- RealmModel realm = getRealmDelegate().createRealm(id, name);
- registerRealmInvalidation(realm.getId(), realm.getName());
- return realm;
- }
-
- @Override
- public RealmModel getRealm(String id) {
- CachedRealm cached = cache.get(id, CachedRealm.class);
- if (cached != null) {
- logger.tracev("by id cache hit: {0}", cached.getName());
- }
- boolean wasCached = false;
- if (cached == null) {
- Long loaded = cache.getCurrentRevision(id);
- RealmModel model = getRealmDelegate().getRealm(id);
- if (model == null) return null;
- if (invalidations.contains(id)) return model;
- cached = new CachedRealm(loaded, model);
- cache.addRevisioned(cached, startupRevision);
- wasCached =true;
- } else if (invalidations.contains(id)) {
- return getRealmDelegate().getRealm(id);
- } else if (managedRealms.containsKey(id)) {
- return managedRealms.get(id);
- }
- RealmAdapter adapter = new RealmAdapter(session, cached, this);
- if (wasCached) {
- CachedRealmModel.RealmCachedEvent event = new CachedRealmModel.RealmCachedEvent() {
- @Override
- public CachedRealmModel getRealm() {
- return adapter;
- }
-
- @Override
- public KeycloakSession getKeycloakSession() {
- return session;
- }
- };
- session.getKeycloakSessionFactory().publish(event);
- }
- managedRealms.put(id, adapter);
- return adapter;
- }
-
- @Override
- public RealmModel getRealmByName(String name) {
- String cacheKey = getRealmByNameCacheKey(name);
- RealmListQuery query = cache.get(cacheKey, RealmListQuery.class);
- if (query != null) {
- logger.tracev("realm by name cache hit: {0}", name);
- }
- if (query == null) {
- Long loaded = cache.getCurrentRevision(cacheKey);
- RealmModel model = getRealmDelegate().getRealmByName(name);
- if (model == null) return null;
- if (invalidations.contains(model.getId())) return model;
- query = new RealmListQuery(loaded, cacheKey, model.getId());
- cache.addRevisioned(query, startupRevision);
- return model;
- } else if (invalidations.contains(cacheKey)) {
- return getRealmDelegate().getRealmByName(name);
- } else {
- String realmId = query.getRealms().iterator().next();
- if (invalidations.contains(realmId)) {
- return getRealmDelegate().getRealmByName(name);
- }
- return getRealm(realmId);
- }
- }
-
- static String getRealmByNameCacheKey(String name) {
- return "realm.query.by.name." + name;
- }
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan;
+
+// import org.jboss.logging.Logger;
+// import org.keycloak.cluster.ClusterProvider;
+// import org.keycloak.component.ComponentModel;
+// import org.keycloak.migration.MigrationModel;
+// import org.keycloak.models.*;
+// import org.keycloak.models.cache.CacheRealmProvider;
+// import org.keycloak.models.cache.CachedRealmModel;
+// import org.keycloak.models.cache.infinispan.entities.*;
+// import org.keycloak.models.cache.infinispan.events.*;
+// import org.keycloak.models.utils.KeycloakModelUtils;
+// import org.keycloak.storage.StorageId;
+// import org.keycloak.storage.client.ClientStorageProviderModel;
+
+// import java.util.*;
+
+
+// /**
+// * - the high level architecture of this cache is an invalidation cache.
+// * - the cache is manual/custom versioned. When a model is updated, we remove it from the cache
+// * which causes an invalidation message to be sent across the cluster.
+// * - We had to do it this way because Infinispan REPEATABLE_READ
+// * wouldn't cut it in invalidation mode. Also, REPEATABLE_READ doesn't work very well on relationships and items that are
+// * not in the cache.
+// * - There are two Infinispan caches. One clustered that holds actual objects and a another local one that holds revision
+// * numbers of cached objects. Whenever a cached object is removed (invalidated), the local revision
+// * cache number or that key is bumped higher based on a local version counter. Whenever a cache entry is fetched, this
+// * revision number is also fetched and compared against the revision number in the cache entry to see if the cache entry
+// * is stale. Whenever a cache entry is added, this revision number is also checked against the revision cache.
+// * - Revision entries are actually never removed (although they could be evicted by cache eviction policies). The reason for this
+// * is that it is possible for a stale object to be inserted if one thread loads and the data is updated in the database before
+// * it is added to the cache. So, we keep the version number around for this.
+// * - In a transaction, objects are registered to be invalidated. If an object is marked for invalidation within a transaction
+// * a cached object should never be returned. An DB adapter should always be returned.
+// * - After DB commits, the objects marked for invalidation are invalidated, or rather removed from the cache. At this time
+// * the revision cache entry for this object has its version number bumped.
+// * - Whenever an object is marked for invalidation, the cache is also searched for any objects that are related to this object
+// * and need to also be evicted/removed. We use the Infinispan Stream SPI for this.
+// *
+// * ClientList caches:
+// * - lists of clients are cached in a specific cache entry i.e. realm clients, find client by clientId
+// * - realm client lists need to be invalidated and evited whenever a client is added or removed from a realm. RealmProvider
+// * now has addClient/removeClient at its top level. All adapaters should use these methods so that the appropriate invalidations
+// * can be registered.
+// * - whenever a client is added/removed the realm of the client is added to a listInvalidations set
+// * this set must be checked before sending back or caching a cached query. This check is required to
+// * avoid caching an uncommitted removal/add in a query cache.
+// * - when a client is removed, any queries that contain that client must also be removed.
+// * - a client removal will also cause anything that is contained and cached within that client to be removed
+// *
+// * Clustered caches:
+// * - There is a Infinispan @Listener registered. If an invalidation event happens, this is treated like
+// * the object was removed from the database and will perform evictions based on that assumption.
+// * - Eviction events will also cascade other evictions, but not assume this is a db removal.
+// * - With an invalidation cache, if you remove an entry on node 1 and this entry does not exist on node 2, node 2 will not receive a @Listener invalidation event.
+// * so, hat we have to put a marker entry in the invalidation cache before we read from the DB, so if the DB changes in between reading and adding a cache entry, the cache will be notified and bump
+// * the version information.
+// *
+// * DBs with Repeatable Read:
+// * - DBs like MySQL are Repeatable Read by default. So, if you query a Client for instance, it will always return the same result in the same transaction even if the DB
+// * was updated in between these queries. This makes it possible to store stale cache entries. To avoid this problem, this class stores the current local version counter
+// * at the beginningof the transaction. Whenever an entry is added to the cache, the current coutner is compared against the counter at the beginning of the tx. If the current
+// * is greater, then don't cache.
+// *
+// * Groups and Roles:
+// * - roles are tricky because of composites. Composite lists are cached too. So, when a role is removed
+// * we also iterate and invalidate any role or group that contains that role being removed.
+// *
+// * - any relationship should be resolved from session.realms(). For example if JPA.getClientByClientId() is invoked,
+// * JPA should find the id of the client and then call session.realms().getClientById(). THis is to ensure that the cached
+// * object is invoked and all proper invalidation are being invoked.
+// *
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public class RealmCacheSession implements CacheRealmProvider {
+// protected static final Logger logger = Logger.getLogger(RealmCacheSession.class);
+// public static final String REALM_CLIENTS_QUERY_SUFFIX = ".realm.clients";
+// public static final String ROLES_QUERY_SUFFIX = ".roles";
+// protected RealmCacheManager cache;
+// protected KeycloakSession session;
+// protected RealmProvider realmDelegate;
+// protected ClientProvider clientDelegate;
+// protected boolean transactionActive;
+// protected boolean setRollbackOnly;
+
+// protected Map<String, RealmAdapter> managedRealms = new HashMap<>();
+// protected Map<String, ClientModel> managedApplications = new HashMap<>();
+// protected Map<String, ClientScopeAdapter> managedClientScopes = new HashMap<>();
+// protected Map<String, RoleAdapter> managedRoles = new HashMap<>();
+// protected Map<String, GroupAdapter> managedGroups = new HashMap<>();
+// protected Set<String> listInvalidations = new HashSet<>();
+// protected Set<String> invalidations = new HashSet<>();
+// protected Set<InvalidationEvent> invalidationEvents = new HashSet<>(); // Events to be sent across cluster
+
+// protected boolean clearAll;
+// protected final long startupRevision;
+
+// public RealmCacheSession(RealmCacheManager cache, KeycloakSession session) {
+// this.cache = cache;
+// this.session = session;
+// this.startupRevision = cache.getCurrentCounter();
+// session.getTransactionManager().enlistPrepare(getPrepareTransaction());
+// session.getTransactionManager().enlistAfterCompletion(getAfterTransaction());
+// }
+
+// public long getStartupRevision() {
+// return startupRevision;
+// }
+
+// public boolean isInvalid(String id) {
+// return invalidations.contains(id);
+// }
+
+// @Override
+// public void clear() {
+// ClusterProvider cluster = session.getProvider(ClusterProvider.class);
+// cluster.notify(InfinispanCacheRealmProviderFactory.REALM_CLEAR_CACHE_EVENTS, new ClearCacheEvent(), false, ClusterProvider.DCNotify.ALL_DCS);
+// }
+
+// @Override
+// public MigrationModel getMigrationModel() {
+// return getRealmDelegate().getMigrationModel();
+// }
+
+// @Override
+// public RealmProvider getRealmDelegate() {
+// if (!transactionActive) throw new IllegalStateException("Cannot access delegate without a transaction");
+// if (realmDelegate != null) return realmDelegate;
+// realmDelegate = session.realmLocalStorage();
+// return realmDelegate;
+// }
+// public ClientProvider getClientDelegate() {
+// if (!transactionActive) throw new IllegalStateException("Cannot access delegate without a transaction");
+// if (clientDelegate != null) return clientDelegate;
+// clientDelegate = session.clientStorageManager();
+// return clientDelegate;
+// }
+
+
+
+
+// @Override
+// public void registerRealmInvalidation(String id, String name) {
+// cache.realmUpdated(id, name, invalidations);
+// RealmAdapter adapter = managedRealms.get(id);
+// if (adapter != null) adapter.invalidateFlag();
+
+// invalidationEvents.add(RealmUpdatedEvent.create(id, name));
+// }
+
+// @Override
+// public void registerClientInvalidation(String id, String clientId, String realmId) {
+// // invalidateClient(id);
+// invalidationEvents.add(ClientUpdatedEvent.create(id, clientId, realmId));
+// cache.clientUpdated(realmId, id, clientId, invalidations);
+// }
+
+// // private void invalidateClient(String id) {
+// // invalidations.add(id);
+// // ClientModel adapter = managedApplications.get(id);
+// // if (adapter != null && adapter instanceof ClientAdapter) ((ClientAdapter)adapter).invalidate();
+// // }
+
+// @Override
+// public void registerClientScopeInvalidation(String id) {
+// invalidateClientScope(id);
+// // Note: Adding/Removing client template is supposed to invalidate CachedRealm as well, so the list of clientScopes is invalidated.
+// // But separate RealmUpdatedEvent will be sent for it. So ClientTemplateEvent don't need to take care of it.
+// invalidationEvents.add(ClientTemplateEvent.create(id));
+// }
+
+// private void invalidateClientScope(String id) {
+// invalidations.add(id);
+// ClientScopeAdapter adapter = managedClientScopes.get(id);
+// if (adapter != null) adapter.invalidate();
+// }
+
+// @Override
+// public void registerRoleInvalidation(String id, String roleName, String roleContainerId) {
+// invalidateRole(id);
+// cache.roleUpdated(roleContainerId, roleName, invalidations);
+// invalidationEvents.add(RoleUpdatedEvent.create(id, roleName, roleContainerId));
+// }
+
+// private void roleRemovalInvalidations(String roleId, String roleName, String roleContainerId) {
+// Set<String> newInvalidations = new HashSet<>();
+// cache.roleRemoval(roleId, roleName, roleContainerId, newInvalidations);
+// invalidations.addAll(newInvalidations);
+// // need to make sure that scope and group mapping clients and groups are invalidated
+// for (String id : newInvalidations) {
+// ClientModel adapter = managedApplications.get(id);
+// // if (adapter != null && adapter instanceof ClientAdapter){
+// // ((ClientAdapter)adapter).invalidate();
+// // continue;
+// // }
+// GroupAdapter group = managedGroups.get(id);
+// if (group != null) {
+// group.invalidate();
+// continue;
+// }
+// ClientScopeAdapter clientScope = managedClientScopes.get(id);
+// if (clientScope != null) {
+// clientScope.invalidate();
+// continue;
+// }
+// RoleAdapter role = managedRoles.get(id);
+// if (role != null) {
+// role.invalidate();
+// continue;
+// }
+
+
+// }
+// }
+
+
+
+
+// private void invalidateRole(String id) {
+// invalidations.add(id);
+// RoleAdapter adapter = managedRoles.get(id);
+// if (adapter != null) adapter.invalidate();
+// }
+
+// private void addedRole(String roleId, String roleContainerId) {
+// // this is needed so that a new role that hasn't been committed isn't cached in a query
+// listInvalidations.add(roleContainerId);
+
+// invalidateRole(roleId);
+// cache.roleAdded(roleContainerId, invalidations);
+// invalidationEvents.add(RoleAddedEvent.create(roleId, roleContainerId));
+// }
+
+// @Override
+// public void registerGroupInvalidation(String id) {
+// invalidateGroup(id, null, false);
+// addGroupEventIfAbsent(GroupUpdatedEvent.create(id));
+// }
+
+// private void invalidateGroup(String id, String realmId, boolean invalidateQueries) {
+// invalidateGroup(id);
+// if (invalidateQueries) {
+// cache.groupQueriesInvalidations(realmId, invalidations);
+// }
+// }
+
+// private void invalidateGroup(String id) {
+// invalidations.add(id);
+// GroupAdapter adapter = managedGroups.get(id);
+// if (adapter != null) adapter.invalidate();
+// }
+
+// protected void runInvalidations() {
+// for (String id : invalidations) {
+// cache.invalidateObject(id);
+// }
+
+// cache.sendInvalidationEvents(session, invalidationEvents, InfinispanCacheRealmProviderFactory.REALM_INVALIDATION_EVENTS);
+// }
+
+// private KeycloakTransaction getPrepareTransaction() {
+// return new KeycloakTransaction() {
+// @Override
+// public void begin() {
+// transactionActive = true;
+// }
+
+// @Override
+// public void commit() {
+// /* THIS WAS CAUSING DEADLOCK IN A CLUSTER
+// if (delegate == null) return;
+// List<String> locks = new LinkedList<>();
+// locks.addAll(invalidations);
+
+// Collections.sort(locks); // lock ordering
+// cache.getRevisions().startBatch();
+
+// if (!locks.isEmpty()) cache.getRevisions().getAdvancedCache().lock(locks);
+// */
+
+// }
+
+// @Override
+// public void rollback() {
+// setRollbackOnly = true;
+// transactionActive = false;
+// }
+
+// @Override
+// public void setRollbackOnly() {
+// setRollbackOnly = true;
+// }
+
+// @Override
+// public boolean getRollbackOnly() {
+// return setRollbackOnly;
+// }
+
+// @Override
+// public boolean isActive() {
+// return transactionActive;
+// }
+// };
+// }
+
+// private KeycloakTransaction getAfterTransaction() {
+// return new KeycloakTransaction() {
+// @Override
+// public void begin() {
+// transactionActive = true;
+// }
+
+// @Override
+// public void commit() {
+// try {
+// if (clearAll) {
+// cache.clear();
+// }
+// runInvalidations();
+// transactionActive = false;
+// } finally {
+// cache.endRevisionBatch();
+// }
+// }
+
+// @Override
+// public void rollback() {
+// try {
+// setRollbackOnly = true;
+// runInvalidations();
+// transactionActive = false;
+// } finally {
+// cache.endRevisionBatch();
+// }
+// }
+
+// @Override
+// public void setRollbackOnly() {
+// setRollbackOnly = true;
+// }
+
+// @Override
+// public boolean getRollbackOnly() {
+// return setRollbackOnly;
+// }
+
+// @Override
+// public boolean isActive() {
+// return transactionActive;
+// }
+// };
+// }
+
+// @Override
+// public RealmModel createRealm(String name) {
+// RealmModel realm = getRealmDelegate().createRealm(name);
+// registerRealmInvalidation(realm.getId(), realm.getName());
+// return realm;
+// }
+
+// @Override
+// public RealmModel createRealm(String id, String name) {
+// RealmModel realm = getRealmDelegate().createRealm(id, name);
+// registerRealmInvalidation(realm.getId(), realm.getName());
+// return realm;
+// }
+
+// @Override
+// public RealmModel getRealm(String id) {
+// CachedRealm cached = cache.get(id, CachedRealm.class);
+// if (cached != null) {
+// logger.tracev("by id cache hit: {0}", cached.getName());
+// }
+// boolean wasCached = false;
+// if (cached == null) {
+// Long loaded = cache.getCurrentRevision(id);
+// RealmModel model = getRealmDelegate().getRealm(id);
+// if (model == null) return null;
+// if (invalidations.contains(id)) return model;
+// cached = new CachedRealm(loaded, model);
+// cache.addRevisioned(cached, startupRevision);
+// wasCached =true;
+// } else if (invalidations.contains(id)) {
+// return getRealmDelegate().getRealm(id);
+// } else if (managedRealms.containsKey(id)) {
+// return managedRealms.get(id);
+// }
+// RealmAdapter adapter = new RealmAdapter(session, cached, this);
+// if (wasCached) {
+// CachedRealmModel.RealmCachedEvent event = new CachedRealmModel.RealmCachedEvent() {
+// @Override
+// public CachedRealmModel getRealm() {
+// return adapter;
+// }
+
+// @Override
+// public KeycloakSession getKeycloakSession() {
+// return session;
+// }
+// };
+// session.getKeycloakSessionFactory().publish(event);
+// }
+// managedRealms.put(id, adapter);
+// return adapter;
+// }
+
+// @Override
+// public RealmModel getRealmByName(String name) {
+// String cacheKey = getRealmByNameCacheKey(name);
+// RealmListQuery query = cache.get(cacheKey, RealmListQuery.class);
+// if (query != null) {
+// logger.tracev("realm by name cache hit: {0}", name);
+// }
+// if (query == null) {
+// Long loaded = cache.getCurrentRevision(cacheKey);
+// RealmModel model = getRealmDelegate().getRealmByName(name);
+// if (model == null) return null;
+// if (invalidations.contains(model.getId())) return model;
+// query = new RealmListQuery(loaded, cacheKey, model.getId());
+// cache.addRevisioned(query, startupRevision);
+// return model;
+// } else if (invalidations.contains(cacheKey)) {
+// return getRealmDelegate().getRealmByName(name);
+// } else {
+// String realmId = query.getRealms().iterator().next();
+// if (invalidations.contains(realmId)) {
+// return getRealmDelegate().getRealmByName(name);
+// }
+// return getRealm(realmId);
+// }
+// }
+
+// static String getRealmByNameCacheKey(String name) {
+// return "realm.query.by.name." + name;
+// }
- @Override
- public List<RealmModel> getRealmsWithProviderType(Class<?> type) {
- // Retrieve realms from backend
- List<RealmModel> backendRealms = getRealmDelegate().getRealmsWithProviderType(type);
- return getRealms(backendRealms);
- }
-
- @Override
- public List<RealmModel> getRealms() {
- // Retrieve realms from backend
- List<RealmModel> backendRealms = getRealmDelegate().getRealms();
- return getRealms(backendRealms);
- }
-
- private List<RealmModel> getRealms(List<RealmModel> backendRealms) {
- // Return cache delegates to ensure cache invalidated during write operations
- List<RealmModel> cachedRealms = new LinkedList<RealmModel>();
- for (RealmModel realm : backendRealms) {
- RealmModel cached = getRealm(realm.getId());
- cachedRealms.add(cached);
- }
- return cachedRealms;
- }
-
- @Override
- public boolean removeRealm(String id) {
- RealmModel realm = getRealm(id);
- if (realm == null) return false;
-
- evictRealmOnRemoval(realm);
- return getRealmDelegate().removeRealm(id);
- }
-
- public void evictRealmOnRemoval(RealmModel realm) {
- cache.invalidateObject(realm.getId());
- invalidationEvents.add(RealmRemovedEvent.create(realm.getId(), realm.getName()));
- cache.realmRemoval(realm.getId(), realm.getName(), invalidations);
- }
-
-
- @Override
- public ClientModel addClient(RealmModel realm, String clientId) {
- ClientModel client = getRealmDelegate().addClient(realm, clientId);
- return addedClient(realm, client);
- }
-
- @Override
- public ClientModel addClient(RealmModel realm, String id, String clientId) {
- ClientModel client = getRealmDelegate().addClient(realm, id, clientId);
- return addedClient(realm, client);
- }
-
- private ClientModel addedClient(RealmModel realm, ClientModel client) {
- logger.trace("added Client.....");
-
- invalidateClient(client.getId());
- // this is needed so that a client that hasn't been committed isn't cached in a query
- listInvalidations.add(realm.getId());
-
- invalidationEvents.add(ClientAddedEvent.create(client.getId(), client.getClientId(), realm.getId()));
- cache.clientAdded(realm.getId(), client.getId(), client.getClientId(), invalidations);
- return client;
- }
-
- static String getRealmClientsQueryCacheKey(String realm) {
- return realm + REALM_CLIENTS_QUERY_SUFFIX;
- }
-
- static String getGroupsQueryCacheKey(String realm) {
- return realm + ".groups";
- }
-
- static String getTopGroupsQueryCacheKey(String realm) {
- return realm + ".top.groups";
- }
-
- static String getRolesCacheKey(String container) {
- return container + ROLES_QUERY_SUFFIX;
- }
- static String getRoleByNameCacheKey(String container, String name) {
- return container + "." + name + ROLES_QUERY_SUFFIX;
- }
-
- @Override
- public List<ClientModel> getClients(RealmModel realm) {
- String cacheKey = getRealmClientsQueryCacheKey(realm.getId());
- boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(realm.getId());
- if (queryDB) {
- return getClientDelegate().getClients(realm);
- }
-
- ClientListQuery query = cache.get(cacheKey, ClientListQuery.class);
- if (query != null) {
- logger.tracev("getClients cache hit: {0}", realm.getName());
- }
-
- if (query == null) {
- Long loaded = cache.getCurrentRevision(cacheKey);
- List<ClientModel> model = getClientDelegate().getClients(realm);
- if (model == null) return null;
- Set<String> ids = new HashSet<>();
- for (ClientModel client : model) ids.add(client.getId());
- query = new ClientListQuery(loaded, cacheKey, realm, ids);
- logger.tracev("adding realm clients cache miss: realm {0} key {1}", realm.getName(), cacheKey);
- cache.addRevisioned(query, startupRevision);
- return model;
- }
- List<ClientModel> list = new LinkedList<>();
- for (String id : query.getClients()) {
- ClientModel client = session.realms().getClientById(id, realm);
- if (client == null) {
- // TODO: Handle with cluster invalidations too
- invalidations.add(cacheKey);
- return getRealmDelegate().getClients(realm);
- }
- list.add(client);
- }
- return list;
- }
-
-
- @Override
- public boolean removeClient(String id, RealmModel realm) {
- ClientModel client = getClientById(id, realm);
- if (client == null) return false;
-
- invalidateClient(client.getId());
- // this is needed so that a client that hasn't been committed isn't cached in a query
- listInvalidations.add(realm.getId());
-
- invalidationEvents.add(ClientRemovedEvent.create(client));
- cache.clientRemoval(realm.getId(), id, client.getClientId(), invalidations);
-
- for (RoleModel role : client.getRoles()) {
- roleRemovalInvalidations(role.getId(), role.getName(), client.getId());
- }
- return getRealmDelegate().removeClient(id, realm);
- }
-
-
- @Override
- public void close() {
- if (realmDelegate != null) realmDelegate.close();
- if (clientDelegate != null) clientDelegate.close();
- }
-
- @Override
- public RoleModel addRealmRole(RealmModel realm, String name) {
- return addRealmRole(realm, KeycloakModelUtils.generateId(), name);
- }
-
- @Override
- public RoleModel addRealmRole(RealmModel realm, String id, String name) {
- RoleModel role = getRealmDelegate().addRealmRole(realm, id, name);
- addedRole(role.getId(), realm.getId());
- return role;
- }
-
- @Override
- public Set<RoleModel> getRealmRoles(RealmModel realm) {
- String cacheKey = getRolesCacheKey(realm.getId());
- boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(realm.getId());
- if (queryDB) {
- return getRealmDelegate().getRealmRoles(realm);
- }
-
- RoleListQuery query = cache.get(cacheKey, RoleListQuery.class);
- if (query != null) {
- logger.tracev("getRealmRoles cache hit: {0}", realm.getName());
- }
-
- if (query == null) {
- Long loaded = cache.getCurrentRevision(cacheKey);
- Set<RoleModel> model = getRealmDelegate().getRealmRoles(realm);
- if (model == null) return null;
- Set<String> ids = new HashSet<>();
- for (RoleModel role : model) ids.add(role.getId());
- query = new RoleListQuery(loaded, cacheKey, realm, ids);
- logger.tracev("adding realm roles cache miss: realm {0} key {1}", realm.getName(), cacheKey);
- cache.addRevisioned(query, startupRevision);
- return model;
- }
- Set<RoleModel> list = new HashSet<>();
- for (String id : query.getRoles()) {
- RoleModel role = session.realms().getRoleById(id, realm);
- if (role == null) {
- invalidations.add(cacheKey);
- return getRealmDelegate().getRealmRoles(realm);
- }
- list.add(role);
- }
- return list;
- }
-
- @Override
- public Set<RoleModel> getClientRoles(RealmModel realm, ClientModel client) {
- String cacheKey = getRolesCacheKey(client.getId());
- boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(client.getId());
- if (queryDB) {
- return getRealmDelegate().getClientRoles(realm, client);
- }
-
- RoleListQuery query = cache.get(cacheKey, RoleListQuery.class);
- if (query != null) {
- logger.tracev("getClientRoles cache hit: {0}", client.getClientId());
- }
-
- if (query == null) {
- Long loaded = cache.getCurrentRevision(cacheKey);
- Set<RoleModel> model = getRealmDelegate().getClientRoles(realm, client);
- if (model == null) return null;
- Set<String> ids = new HashSet<>();
- for (RoleModel role : model) ids.add(role.getId());
- query = new RoleListQuery(loaded, cacheKey, realm, ids, client.getClientId());
- logger.tracev("adding client roles cache miss: client {0} key {1}", client.getClientId(), cacheKey);
- cache.addRevisioned(query, startupRevision);
- return model;
- }
- Set<RoleModel> list = new HashSet<>();
- for (String id : query.getRoles()) {
- RoleModel role = session.realms().getRoleById(id, realm);
- if (role == null) {
- invalidations.add(cacheKey);
- return getRealmDelegate().getClientRoles(realm, client);
- }
- list.add(role);
- }
- return list;
- }
-
- @Override
- public RoleModel addClientRole(RealmModel realm, ClientModel client, String name) {
- return addClientRole(realm, client, KeycloakModelUtils.generateId(), name);
- }
-
- @Override
- public RoleModel addClientRole(RealmModel realm, ClientModel client, String id, String name) {
- RoleModel role = getRealmDelegate().addClientRole(realm, client, id, name);
- addedRole(role.getId(), client.getId());
- return role;
- }
-
- @Override
- public RoleModel getRealmRole(RealmModel realm, String name) {
- String cacheKey = getRoleByNameCacheKey(realm.getId(), name);
- boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(realm.getId());
- if (queryDB) {
- return getRealmDelegate().getRealmRole(realm, name);
- }
-
- RoleListQuery query = cache.get(cacheKey, RoleListQuery.class);
- if (query != null) {
- logger.tracev("getRealmRole cache hit: {0}.{1}", realm.getName(), name);
- }
-
- if (query == null) {
- Long loaded = cache.getCurrentRevision(cacheKey);
- RoleModel model = getRealmDelegate().getRealmRole(realm, name);
- if (model == null) return null;
- query = new RoleListQuery(loaded, cacheKey, realm, model.getId());
- logger.tracev("adding realm role cache miss: client {0} key {1}", realm.getName(), cacheKey);
- cache.addRevisioned(query, startupRevision);
- return model;
- }
- RoleModel role = getRoleById(query.getRoles().iterator().next(), realm);
- if (role == null) {
- invalidations.add(cacheKey);
- return getRealmDelegate().getRealmRole(realm, name);
- }
- return role;
- }
-
- @Override
- public RoleModel getClientRole(RealmModel realm, ClientModel client, String name) {
- String cacheKey = getRoleByNameCacheKey(client.getId(), name);
- boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(client.getId());
- if (queryDB) {
- return getRealmDelegate().getClientRole(realm, client, name);
- }
-
- RoleListQuery query = cache.get(cacheKey, RoleListQuery.class);
- if (query != null) {
- logger.tracev("getClientRole cache hit: {0}.{1}", client.getClientId(), name);
- }
-
- if (query == null) {
- Long loaded = cache.getCurrentRevision(cacheKey);
- RoleModel model = getRealmDelegate().getClientRole(realm, client, name);
- if (model == null) return null;
- query = new RoleListQuery(loaded, cacheKey, realm, model.getId(), client.getClientId());
- logger.tracev("adding client role cache miss: client {0} key {1}", client.getClientId(), cacheKey);
- cache.addRevisioned(query, startupRevision);
- return model;
- }
- RoleModel role = getRoleById(query.getRoles().iterator().next(), realm);
- if (role == null) {
- invalidations.add(cacheKey);
- return getRealmDelegate().getClientRole(realm, client, name);
- }
- return role;
- }
-
- @Override
- public boolean removeRole(RealmModel realm, RoleModel role) {
- listInvalidations.add(role.getContainer().getId());
-
- invalidateRole(role.getId());
- invalidationEvents.add(RoleRemovedEvent.create(role.getId(), role.getName(), role.getContainer().getId()));
- roleRemovalInvalidations(role.getId(), role.getName(), role.getContainer().getId());
-
- return getRealmDelegate().removeRole(realm, role);
- }
-
- @Override
- public RoleModel getRoleById(String id, RealmModel realm) {
- CachedRole cached = cache.get(id, CachedRole.class);
- if (cached != null && !cached.getRealm().equals(realm.getId())) {
- cached = null;
- }
-
- if (cached == null) {
- Long loaded = cache.getCurrentRevision(id);
- RoleModel model = getRealmDelegate().getRoleById(id, realm);
- if (model == null) return null;
- if (invalidations.contains(id)) return model;
- if (model.isClientRole()) {
- cached = new CachedClientRole(loaded, model.getContainerId(), model, realm);
- } else {
- cached = new CachedRealmRole(loaded, model, realm);
- }
- cache.addRevisioned(cached, startupRevision);
-
- } else if (invalidations.contains(id)) {
- return getRealmDelegate().getRoleById(id, realm);
- } else if (managedRoles.containsKey(id)) {
- return managedRoles.get(id);
- }
- RoleAdapter adapter = new RoleAdapter(cached,this, realm);
- managedRoles.put(id, adapter);
- return adapter;
- }
-
- @Override
- public GroupModel getGroupById(String id, RealmModel realm) {
- CachedGroup cached = cache.get(id, CachedGroup.class);
- if (cached != null && !cached.getRealm().equals(realm.getId())) {
- cached = null;
- }
-
- if (cached == null) {
- Long loaded = cache.getCurrentRevision(id);
- GroupModel model = getRealmDelegate().getGroupById(id, realm);
- if (model == null) return null;
- if (invalidations.contains(id)) return model;
- cached = new CachedGroup(loaded, realm, model);
- cache.addRevisioned(cached, startupRevision);
-
- } else if (invalidations.contains(id)) {
- return getRealmDelegate().getGroupById(id, realm);
- } else if (managedGroups.containsKey(id)) {
- return managedGroups.get(id);
- }
- GroupAdapter adapter = new GroupAdapter(cached, this, session, realm);
- managedGroups.put(id, adapter);
- return adapter;
- }
-
- @Override
- public void moveGroup(RealmModel realm, GroupModel group, GroupModel toParent) {
- invalidateGroup(group.getId(), realm.getId(), true);
- if (toParent != null) invalidateGroup(group.getId(), realm.getId(), false); // Queries already invalidated
- listInvalidations.add(realm.getId());
-
- invalidationEvents.add(GroupMovedEvent.create(group, toParent, realm.getId()));
- getRealmDelegate().moveGroup(realm, group, toParent);
- }
-
- @Override
- public List<GroupModel> getGroups(RealmModel realm) {
- String cacheKey = getGroupsQueryCacheKey(realm.getId());
- boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(realm.getId());
- if (queryDB) {
- return getRealmDelegate().getGroups(realm);
- }
-
- GroupListQuery query = cache.get(cacheKey, GroupListQuery.class);
- if (query != null) {
- logger.tracev("getGroups cache hit: {0}", realm.getName());
- }
-
- if (query == null) {
- Long loaded = cache.getCurrentRevision(cacheKey);
- List<GroupModel> model = getRealmDelegate().getGroups(realm);
- if (model == null) return null;
- Set<String> ids = new HashSet<>();
- for (GroupModel client : model) ids.add(client.getId());
- query = new GroupListQuery(loaded, cacheKey, realm, ids);
- logger.tracev("adding realm getGroups cache miss: realm {0} key {1}", realm.getName(), cacheKey);
- cache.addRevisioned(query, startupRevision);
- return model;
- }
- List<GroupModel> list = new LinkedList<>();
- for (String id : query.getGroups()) {
- GroupModel group = session.realms().getGroupById(id, realm);
- if (group == null) {
- invalidations.add(cacheKey);
- return getRealmDelegate().getGroups(realm);
- }
- list.add(group);
- }
-
- list.sort(Comparator.comparing(GroupModel::getName));
-
- return list;
- }
-
- @Override
- public Long getGroupsCount(RealmModel realm, Boolean onlyTopGroups) {
- return getRealmDelegate().getGroupsCount(realm, onlyTopGroups);
- }
-
- @Override
- public Long getGroupsCountByNameContaining(RealmModel realm, String search) {
- return getRealmDelegate().getGroupsCountByNameContaining(realm, search);
- }
-
- @Override
- public List<GroupModel> getTopLevelGroups(RealmModel realm) {
- String cacheKey = getTopGroupsQueryCacheKey(realm.getId());
- boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(realm.getId());
- if (queryDB) {
- return getRealmDelegate().getTopLevelGroups(realm);
- }
-
- GroupListQuery query = cache.get(cacheKey, GroupListQuery.class);
- if (query != null) {
- logger.tracev("getTopLevelGroups cache hit: {0}", realm.getName());
- }
-
- if (query == null) {
- Long loaded = cache.getCurrentRevision(cacheKey);
- List<GroupModel> model = getRealmDelegate().getTopLevelGroups(realm);
- if (model == null) return null;
- Set<String> ids = new HashSet<>();
- for (GroupModel client : model) ids.add(client.getId());
- query = new GroupListQuery(loaded, cacheKey, realm, ids);
- logger.tracev("adding realm getTopLevelGroups cache miss: realm {0} key {1}", realm.getName(), cacheKey);
- cache.addRevisioned(query, startupRevision);
- return model;
- }
- List<GroupModel> list = new LinkedList<>();
- for (String id : query.getGroups()) {
- GroupModel group = session.realms().getGroupById(id, realm);
- if (group == null) {
- invalidations.add(cacheKey);
- return getRealmDelegate().getTopLevelGroups(realm);
- }
- list.add(group);
- }
-
- list.sort(Comparator.comparing(GroupModel::getName));
-
- return list;
- }
-
- @Override
- public List<GroupModel> getTopLevelGroups(RealmModel realm, Integer first, Integer max) {
- String cacheKey = getTopGroupsQueryCacheKey(realm.getId() + first + max);
- boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(realm.getId() + first + max);
- if (queryDB) {
- return getRealmDelegate().getTopLevelGroups(realm, first, max);
- }
-
- GroupListQuery query = cache.get(cacheKey, GroupListQuery.class);
- if (Objects.nonNull(query)) {
- logger.tracev("getTopLevelGroups cache hit: {0}", realm.getName());
- }
-
- if (Objects.isNull(query)) {
- Long loaded = cache.getCurrentRevision(cacheKey);
- List<GroupModel> model = getRealmDelegate().getTopLevelGroups(realm, first, max);
- if (model == null) return null;
- Set<String> ids = new HashSet<>();
- for (GroupModel client : model) ids.add(client.getId());
- query = new GroupListQuery(loaded, cacheKey, realm, ids);
- logger.tracev("adding realm getTopLevelGroups cache miss: realm {0} key {1}", realm.getName(), cacheKey);
- cache.addRevisioned(query, startupRevision);
- return model;
- }
- List<GroupModel> list = new LinkedList<>();
- for (String id : query.getGroups()) {
- GroupModel group = session.realms().getGroupById(id, realm);
- if (Objects.isNull(group)) {
- invalidations.add(cacheKey);
- return getRealmDelegate().getTopLevelGroups(realm);
- }
- list.add(group);
- }
-
- list.sort(Comparator.comparing(GroupModel::getName));
-
- return list;
- }
-
- @Override
- public List<GroupModel> searchForGroupByName(RealmModel realm, String search, Integer first, Integer max) {
- return getRealmDelegate().searchForGroupByName(realm, search, first, max);
- }
-
- @Override
- public boolean removeGroup(RealmModel realm, GroupModel group) {
- invalidateGroup(group.getId(), realm.getId(), true);
- listInvalidations.add(realm.getId());
- cache.groupQueriesInvalidations(realm.getId(), invalidations);
- if (group.getParentId() != null) {
- invalidateGroup(group.getParentId(), realm.getId(), false); // Queries already invalidated
- }
-
- invalidationEvents.add(GroupRemovedEvent.create(group, realm.getId()));
-
- return getRealmDelegate().removeGroup(realm, group);
- }
-
- @Override
- public GroupModel createGroup(RealmModel realm, String name) {
- GroupModel group = getRealmDelegate().createGroup(realm, name);
- return groupAdded(realm, group);
- }
-
- private GroupModel groupAdded(RealmModel realm, GroupModel group) {
- listInvalidations.add(realm.getId());
- cache.groupQueriesInvalidations(realm.getId(), invalidations);
- invalidations.add(group.getId());
- invalidationEvents.add(GroupAddedEvent.create(group.getId(), realm.getId()));
- return group;
- }
-
- @Override
- public GroupModel createGroup(RealmModel realm, String id, String name) {
- GroupModel group = getRealmDelegate().createGroup(realm, id, name);
- return groupAdded(realm, group);
- }
-
- @Override
- public void addTopLevelGroup(RealmModel realm, GroupModel subGroup) {
- invalidateGroup(subGroup.getId(), realm.getId(), true);
- if (subGroup.getParentId() != null) {
- invalidateGroup(subGroup.getParentId(), realm.getId(), false); // Queries already invalidated
- }
-
- addGroupEventIfAbsent(GroupMovedEvent.create(subGroup, null, realm.getId()));
-
- getRealmDelegate().addTopLevelGroup(realm, subGroup);
-
- }
-
- private void addGroupEventIfAbsent(InvalidationEvent eventToAdd) {
- String groupId = eventToAdd.getId();
-
- // Check if we have existing event with bigger priority
- boolean eventAlreadyExists = invalidationEvents.stream()
- .anyMatch((InvalidationEvent event) -> (event.getId().equals(groupId)) &&
- (event instanceof GroupAddedEvent || event instanceof GroupMovedEvent || event instanceof GroupRemovedEvent));
-
- if (!eventAlreadyExists) {
- invalidationEvents.add(eventToAdd);
- }
- }
-
- @Override
- public ClientModel getClientById(String id, RealmModel realm) {
- CachedClient cached = cache.get(id, CachedClient.class);
- if (cached != null && !cached.getRealm().equals(realm.getId())) {
- cached = null;
- }
- if (cached != null) {
- logger.tracev("client by id cache hit: {0}", cached.getClientId());
- }
-
- if (cached == null) {
- Long loaded = cache.getCurrentRevision(id);
- ClientModel model = getClientDelegate().getClientById(id, realm);
- if (model == null) return null;
- ClientModel adapter = cacheClient(realm, model, loaded);
- managedApplications.put(id, adapter);
- return adapter;
- } else if (invalidations.contains(id)) {
- return getRealmDelegate().getClientById(id, realm);
- } else if (managedApplications.containsKey(id)) {
- return managedApplications.get(id);
- }
- ClientModel adapter = validateCache(realm, cached);
- managedApplications.put(id, adapter);
- return adapter;
- }
-
- protected ClientModel cacheClient(RealmModel realm, ClientModel delegate, Long revision) {
- if (invalidations.contains(delegate.getId())) return delegate;
- StorageId storageId = new StorageId(delegate.getId());
- CachedClient cached = null;
- ClientAdapter adapter = null;
-
- if (!storageId.isLocal()) {
- ComponentModel component = realm.getComponent(storageId.getProviderId());
- ClientStorageProviderModel model = new ClientStorageProviderModel(component);
- if (!model.isEnabled()) {
- return delegate;
- }
- ClientStorageProviderModel.CachePolicy policy = model.getCachePolicy();
- if (policy != null && policy == ClientStorageProviderModel.CachePolicy.NO_CACHE) {
- return delegate;
- }
-
- cached = new CachedClient(revision, realm, delegate);
- adapter = new ClientAdapter(realm, cached, this);
-
- long lifespan = model.getLifespan();
- if (lifespan > 0) {
- cache.addRevisioned(cached, startupRevision, lifespan);
- } else {
- cache.addRevisioned(cached, startupRevision);
- }
- } else {
- cached = new CachedClient(revision, realm, delegate);
- adapter = new ClientAdapter(realm, cached, this);
- cache.addRevisioned(cached, startupRevision);
- }
-
- return adapter;
- }
-
-
- protected ClientModel validateCache(RealmModel realm, CachedClient cached) {
- if (!realm.getId().equals(cached.getRealm())) {
- return null;
- }
-
- StorageId storageId = new StorageId(cached.getId());
- if (!storageId.isLocal()) {
- ComponentModel component = realm.getComponent(storageId.getProviderId());
- ClientStorageProviderModel model = new ClientStorageProviderModel(component);
-
- // although we do set a timeout, Infinispan has no guarantees when the user will be evicted
- // its also hard to test stuff
- if (model.shouldInvalidate(cached)) {
- registerClientInvalidation(cached.getId(), cached.getClientId(), realm.getId());
- return getClientDelegate().getClientById(cached.getId(), realm);
- }
- }
- ClientAdapter adapter = new ClientAdapter(realm, cached, this);
-
- return adapter;
- }
-
-
- @Override
- public ClientModel getClientByClientId(String clientId, RealmModel realm) {
- String cacheKey = getClientByClientIdCacheKey(clientId, realm.getId());
- ClientListQuery query = cache.get(cacheKey, ClientListQuery.class);
- String id = null;
-
- if (query != null) {
- logger.tracev("client by name cache hit: {0}", clientId);
- }
-
- if (query == null) {
- Long loaded = cache.getCurrentRevision(cacheKey);
- ClientModel model = getClientDelegate().getClientByClientId(clientId, realm);
- if (model == null) return null;
- if (invalidations.contains(model.getId())) return model;
- id = model.getId();
- query = new ClientListQuery(loaded, cacheKey, realm, id);
- logger.tracev("adding client by name cache miss: {0}", clientId);
- cache.addRevisioned(query, startupRevision);
- } else if (invalidations.contains(cacheKey)) {
- return getClientDelegate().getClientByClientId(clientId, realm);
- } else {
- id = query.getClients().iterator().next();
- if (invalidations.contains(id)) {
- return getClientDelegate().getClientByClientId(clientId, realm);
- }
- }
- return getClientById(id, realm);
- }
-
- static String getClientByClientIdCacheKey(String clientId, String realmId) {
- return realmId + ".client.query.by.clientId." + clientId;
- }
-
- @Override
- public ClientScopeModel getClientScopeById(String id, RealmModel realm) {
- CachedClientScope cached = cache.get(id, CachedClientScope.class);
- if (cached != null && !cached.getRealm().equals(realm.getId())) {
- cached = null;
- }
-
- if (cached == null) {
- Long loaded = cache.getCurrentRevision(id);
- ClientScopeModel model = getRealmDelegate().getClientScopeById(id, realm);
- if (model == null) return null;
- if (invalidations.contains(id)) return model;
- cached = new CachedClientScope(loaded, realm, model);
- cache.addRevisioned(cached, startupRevision);
- } else if (invalidations.contains(id)) {
- return getRealmDelegate().getClientScopeById(id, realm);
- } else if (managedClientScopes.containsKey(id)) {
- return managedClientScopes.get(id);
- }
- ClientScopeAdapter adapter = new ClientScopeAdapter(realm, cached, this);
- managedClientScopes.put(id, adapter);
- return adapter;
- }
-
- // Don't cache ClientInitialAccessModel for now
- @Override
- public ClientInitialAccessModel createClientInitialAccessModel(RealmModel realm, int expiration, int count) {
- return getRealmDelegate().createClientInitialAccessModel(realm, expiration, count);
- }
-
- @Override
- public ClientInitialAccessModel getClientInitialAccessModel(RealmModel realm, String id) {
- return getRealmDelegate().getClientInitialAccessModel(realm, id);
- }
-
- @Override
- public void removeClientInitialAccessModel(RealmModel realm, String id) {
- getRealmDelegate().removeClientInitialAccessModel(realm, id);
- }
-
- @Override
- public List<ClientInitialAccessModel> listClientInitialAccess(RealmModel realm) {
- return getRealmDelegate().listClientInitialAccess(realm);
- }
-
- @Override
- public void removeExpiredClientInitialAccess() {
- getRealmDelegate().removeExpiredClientInitialAccess();
- }
-
- @Override
- public void decreaseRemainingCount(RealmModel realm, ClientInitialAccessModel clientInitialAccess) {
- getRealmDelegate().decreaseRemainingCount(realm, clientInitialAccess);
- }
-}
+// @Override
+// public List<RealmModel> getRealmsWithProviderType(Class<?> type) {
+// // Retrieve realms from backend
+// List<RealmModel> backendRealms = getRealmDelegate().getRealmsWithProviderType(type);
+// return getRealms(backendRealms);
+// }
+
+// @Override
+// public List<RealmModel> getRealms() {
+// // Retrieve realms from backend
+// List<RealmModel> backendRealms = getRealmDelegate().getRealms();
+// return getRealms(backendRealms);
+// }
+
+// private List<RealmModel> getRealms(List<RealmModel> backendRealms) {
+// // Return cache delegates to ensure cache invalidated during write operations
+// List<RealmModel> cachedRealms = new LinkedList<RealmModel>();
+// for (RealmModel realm : backendRealms) {
+// RealmModel cached = getRealm(realm.getId());
+// cachedRealms.add(cached);
+// }
+// return cachedRealms;
+// }
+
+// @Override
+// public boolean removeRealm(String id) {
+// RealmModel realm = getRealm(id);
+// if (realm == null) return false;
+
+// evictRealmOnRemoval(realm);
+// return getRealmDelegate().removeRealm(id);
+// }
+
+// public void evictRealmOnRemoval(RealmModel realm) {
+// cache.invalidateObject(realm.getId());
+// invalidationEvents.add(RealmRemovedEvent.create(realm.getId(), realm.getName()));
+// cache.realmRemoval(realm.getId(), realm.getName(), invalidations);
+// }
+
+
+// @Override
+// public ClientModel addClient(RealmModel realm, String clientId) {
+// ClientModel client = getRealmDelegate().addClient(realm, clientId);
+// return addedClient(realm, client);
+// }
+
+// @Override
+// public ClientModel addClient(RealmModel realm, String id, String clientId) {
+// ClientModel client = getRealmDelegate().addClient(realm, id, clientId);
+// return addedClient(realm, client);
+// }
+
+// private ClientModel addedClient(RealmModel realm, ClientModel client) {
+// logger.trace("added Client.....");
+
+// // invalidateClient(client.getId());
+// // this is needed so that a client that hasn't been committed isn't cached in a query
+// listInvalidations.add(realm.getId());
+
+// invalidationEvents.add(ClientAddedEvent.create(client.getId(), client.getClientId(), realm.getId()));
+// cache.clientAdded(realm.getId(), client.getId(), client.getClientId(), invalidations);
+// return client;
+// }
+
+// static String getRealmClientsQueryCacheKey(String realm) {
+// return realm + REALM_CLIENTS_QUERY_SUFFIX;
+// }
+
+// static String getGroupsQueryCacheKey(String realm) {
+// return realm + ".groups";
+// }
+
+// static String getTopGroupsQueryCacheKey(String realm) {
+// return realm + ".top.groups";
+// }
+
+// static String getRolesCacheKey(String container) {
+// return container + ROLES_QUERY_SUFFIX;
+// }
+// static String getRoleByNameCacheKey(String container, String name) {
+// return container + "." + name + ROLES_QUERY_SUFFIX;
+// }
+
+// @Override
+// public List<ClientModel> getClients(RealmModel realm) {
+// String cacheKey = getRealmClientsQueryCacheKey(realm.getId());
+// boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(realm.getId());
+// if (queryDB) {
+// return getClientDelegate().getClients(realm);
+// }
+
+// ClientListQuery query = cache.get(cacheKey, ClientListQuery.class);
+// if (query != null) {
+// logger.tracev("getClients cache hit: {0}", realm.getName());
+// }
+
+// if (query == null) {
+// Long loaded = cache.getCurrentRevision(cacheKey);
+// List<ClientModel> model = getClientDelegate().getClients(realm);
+// if (model == null) return null;
+// Set<String> ids = new HashSet<>();
+// for (ClientModel client : model) ids.add(client.getId());
+// query = new ClientListQuery(loaded, cacheKey, realm, ids);
+// logger.tracev("adding realm clients cache miss: realm {0} key {1}", realm.getName(), cacheKey);
+// cache.addRevisioned(query, startupRevision);
+// return model;
+// }
+// List<ClientModel> list = new LinkedList<>();
+// for (String id : query.getClients()) {
+// ClientModel client = session.realms().getClientById(id, realm);
+// if (client == null) {
+// // TODO: Handle with cluster invalidations too
+// invalidations.add(cacheKey);
+// return getRealmDelegate().getClients(realm);
+// }
+// list.add(client);
+// }
+// return list;
+// }
+
+
+// @Override
+// public boolean removeClient(String id, RealmModel realm) {
+// ClientModel client = getClientById(id, realm);
+// if (client == null) return false;
+
+// // invalidateClient(client.getId());
+// // this is needed so that a client that hasn't been committed isn't cached in a query
+// listInvalidations.add(realm.getId());
+
+// invalidationEvents.add(ClientRemovedEvent.create(client));
+// cache.clientRemoval(realm.getId(), id, client.getClientId(), invalidations);
+
+// for (RoleModel role : client.getRoles()) {
+// roleRemovalInvalidations(role.getId(), role.getName(), client.getId());
+// }
+// return getRealmDelegate().removeClient(id, realm);
+// }
+
+
+// @Override
+// public void close() {
+// if (realmDelegate != null) realmDelegate.close();
+// if (clientDelegate != null) clientDelegate.close();
+// }
+
+// @Override
+// public RoleModel addRealmRole(RealmModel realm, String name) {
+// return addRealmRole(realm, KeycloakModelUtils.generateId(), name);
+// }
+
+// @Override
+// public RoleModel addRealmRole(RealmModel realm, String id, String name) {
+// RoleModel role = getRealmDelegate().addRealmRole(realm, id, name);
+// addedRole(role.getId(), realm.getId());
+// return role;
+// }
+
+// @Override
+// public Set<RoleModel> getRealmRoles(RealmModel realm) {
+// String cacheKey = getRolesCacheKey(realm.getId());
+// boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(realm.getId());
+// if (queryDB) {
+// return getRealmDelegate().getRealmRoles(realm);
+// }
+
+// RoleListQuery query = cache.get(cacheKey, RoleListQuery.class);
+// if (query != null) {
+// logger.tracev("getRealmRoles cache hit: {0}", realm.getName());
+// }
+
+// if (query == null) {
+// Long loaded = cache.getCurrentRevision(cacheKey);
+// Set<RoleModel> model = getRealmDelegate().getRealmRoles(realm);
+// if (model == null) return null;
+// Set<String> ids = new HashSet<>();
+// for (RoleModel role : model) ids.add(role.getId());
+// query = new RoleListQuery(loaded, cacheKey, realm, ids);
+// logger.tracev("adding realm roles cache miss: realm {0} key {1}", realm.getName(), cacheKey);
+// cache.addRevisioned(query, startupRevision);
+// return model;
+// }
+// Set<RoleModel> list = new HashSet<>();
+// for (String id : query.getRoles()) {
+// RoleModel role = session.realms().getRoleById(id, realm);
+// if (role == null) {
+// invalidations.add(cacheKey);
+// return getRealmDelegate().getRealmRoles(realm);
+// }
+// list.add(role);
+// }
+// return list;
+// }
+
+// @Override
+// public Set<RoleModel> getClientRoles(RealmModel realm, ClientModel client) {
+// String cacheKey = getRolesCacheKey(client.getId());
+// boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(client.getId());
+// if (queryDB) {
+// return getRealmDelegate().getClientRoles(realm, client);
+// }
+
+// RoleListQuery query = cache.get(cacheKey, RoleListQuery.class);
+// if (query != null) {
+// logger.tracev("getClientRoles cache hit: {0}", client.getClientId());
+// }
+
+// if (query == null) {
+// Long loaded = cache.getCurrentRevision(cacheKey);
+// Set<RoleModel> model = getRealmDelegate().getClientRoles(realm, client);
+// if (model == null) return null;
+// Set<String> ids = new HashSet<>();
+// for (RoleModel role : model) ids.add(role.getId());
+// query = new RoleListQuery(loaded, cacheKey, realm, ids, client.getClientId());
+// logger.tracev("adding client roles cache miss: client {0} key {1}", client.getClientId(), cacheKey);
+// cache.addRevisioned(query, startupRevision);
+// return model;
+// }
+// Set<RoleModel> list = new HashSet<>();
+// for (String id : query.getRoles()) {
+// RoleModel role = session.realms().getRoleById(id, realm);
+// if (role == null) {
+// invalidations.add(cacheKey);
+// return getRealmDelegate().getClientRoles(realm, client);
+// }
+// list.add(role);
+// }
+// return list;
+// }
+
+// @Override
+// public RoleModel addClientRole(RealmModel realm, ClientModel client, String name) {
+// return addClientRole(realm, client, KeycloakModelUtils.generateId(), name);
+// }
+
+// @Override
+// public RoleModel addClientRole(RealmModel realm, ClientModel client, String id, String name) {
+// RoleModel role = getRealmDelegate().addClientRole(realm, client, id, name);
+// addedRole(role.getId(), client.getId());
+// return role;
+// }
+
+// @Override
+// public RoleModel getRealmRole(RealmModel realm, String name) {
+// String cacheKey = getRoleByNameCacheKey(realm.getId(), name);
+// boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(realm.getId());
+// if (queryDB) {
+// return getRealmDelegate().getRealmRole(realm, name);
+// }
+
+// RoleListQuery query = cache.get(cacheKey, RoleListQuery.class);
+// if (query != null) {
+// logger.tracev("getRealmRole cache hit: {0}.{1}", realm.getName(), name);
+// }
+
+// if (query == null) {
+// Long loaded = cache.getCurrentRevision(cacheKey);
+// RoleModel model = getRealmDelegate().getRealmRole(realm, name);
+// if (model == null) return null;
+// query = new RoleListQuery(loaded, cacheKey, realm, model.getId());
+// logger.tracev("adding realm role cache miss: client {0} key {1}", realm.getName(), cacheKey);
+// cache.addRevisioned(query, startupRevision);
+// return model;
+// }
+// RoleModel role = getRoleById(query.getRoles().iterator().next(), realm);
+// if (role == null) {
+// invalidations.add(cacheKey);
+// return getRealmDelegate().getRealmRole(realm, name);
+// }
+// return role;
+// }
+
+// @Override
+// public RoleModel getClientRole(RealmModel realm, ClientModel client, String name) {
+// String cacheKey = getRoleByNameCacheKey(client.getId(), name);
+// boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(client.getId());
+// if (queryDB) {
+// return getRealmDelegate().getClientRole(realm, client, name);
+// }
+
+// RoleListQuery query = cache.get(cacheKey, RoleListQuery.class);
+// if (query != null) {
+// logger.tracev("getClientRole cache hit: {0}.{1}", client.getClientId(), name);
+// }
+
+// if (query == null) {
+// Long loaded = cache.getCurrentRevision(cacheKey);
+// RoleModel model = getRealmDelegate().getClientRole(realm, client, name);
+// if (model == null) return null;
+// query = new RoleListQuery(loaded, cacheKey, realm, model.getId(), client.getClientId());
+// logger.tracev("adding client role cache miss: client {0} key {1}", client.getClientId(), cacheKey);
+// cache.addRevisioned(query, startupRevision);
+// return model;
+// }
+// RoleModel role = getRoleById(query.getRoles().iterator().next(), realm);
+// if (role == null) {
+// invalidations.add(cacheKey);
+// return getRealmDelegate().getClientRole(realm, client, name);
+// }
+// return role;
+// }
+
+// @Override
+// public boolean removeRole(RealmModel realm, RoleModel role) {
+// listInvalidations.add(role.getContainer().getId());
+
+// invalidateRole(role.getId());
+// invalidationEvents.add(RoleRemovedEvent.create(role.getId(), role.getName(), role.getContainer().getId()));
+// roleRemovalInvalidations(role.getId(), role.getName(), role.getContainer().getId());
+
+// return getRealmDelegate().removeRole(realm, role);
+// }
+
+// @Override
+// public RoleModel getRoleById(String id, RealmModel realm) {
+// CachedRole cached = cache.get(id, CachedRole.class);
+// if (cached != null && !cached.getRealm().equals(realm.getId())) {
+// cached = null;
+// }
+
+// if (cached == null) {
+// Long loaded = cache.getCurrentRevision(id);
+// RoleModel model = getRealmDelegate().getRoleById(id, realm);
+// if (model == null) return null;
+// if (invalidations.contains(id)) return model;
+// if (model.isClientRole()) {
+// cached = new CachedClientRole(loaded, model.getContainerId(), model, realm);
+// } else {
+// cached = new CachedRealmRole(loaded, model, realm);
+// }
+// cache.addRevisioned(cached, startupRevision);
+
+// } else if (invalidations.contains(id)) {
+// return getRealmDelegate().getRoleById(id, realm);
+// } else if (managedRoles.containsKey(id)) {
+// return managedRoles.get(id);
+// }
+// RoleAdapter adapter = new RoleAdapter(cached,this, realm);
+// managedRoles.put(id, adapter);
+// return adapter;
+// }
+
+// @Override
+// public GroupModel getGroupById(String id, RealmModel realm) {
+// CachedGroup cached = cache.get(id, CachedGroup.class);
+// if (cached != null && !cached.getRealm().equals(realm.getId())) {
+// cached = null;
+// }
+
+// if (cached == null) {
+// Long loaded = cache.getCurrentRevision(id);
+// GroupModel model = getRealmDelegate().getGroupById(id, realm);
+// if (model == null) return null;
+// if (invalidations.contains(id)) return model;
+// cached = new CachedGroup(loaded, realm, model);
+// cache.addRevisioned(cached, startupRevision);
+
+// } else if (invalidations.contains(id)) {
+// return getRealmDelegate().getGroupById(id, realm);
+// } else if (managedGroups.containsKey(id)) {
+// return managedGroups.get(id);
+// }
+// GroupAdapter adapter = new GroupAdapter(cached, this, session, realm);
+// managedGroups.put(id, adapter);
+// return adapter;
+// }
+
+// @Override
+// public void moveGroup(RealmModel realm, GroupModel group, GroupModel toParent) {
+// invalidateGroup(group.getId(), realm.getId(), true);
+// if (toParent != null) invalidateGroup(group.getId(), realm.getId(), false); // Queries already invalidated
+// listInvalidations.add(realm.getId());
+
+// invalidationEvents.add(GroupMovedEvent.create(group, toParent, realm.getId()));
+// getRealmDelegate().moveGroup(realm, group, toParent);
+// }
+
+// @Override
+// public List<GroupModel> getGroups(RealmModel realm) {
+// String cacheKey = getGroupsQueryCacheKey(realm.getId());
+// boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(realm.getId());
+// if (queryDB) {
+// return getRealmDelegate().getGroups(realm);
+// }
+
+// GroupListQuery query = cache.get(cacheKey, GroupListQuery.class);
+// if (query != null) {
+// logger.tracev("getGroups cache hit: {0}", realm.getName());
+// }
+
+// if (query == null) {
+// Long loaded = cache.getCurrentRevision(cacheKey);
+// List<GroupModel> model = getRealmDelegate().getGroups(realm);
+// if (model == null) return null;
+// Set<String> ids = new HashSet<>();
+// for (GroupModel client : model) ids.add(client.getId());
+// query = new GroupListQuery(loaded, cacheKey, realm, ids);
+// logger.tracev("adding realm getGroups cache miss: realm {0} key {1}", realm.getName(), cacheKey);
+// cache.addRevisioned(query, startupRevision);
+// return model;
+// }
+// List<GroupModel> list = new LinkedList<>();
+// for (String id : query.getGroups()) {
+// GroupModel group = session.realms().getGroupById(id, realm);
+// if (group == null) {
+// invalidations.add(cacheKey);
+// return getRealmDelegate().getGroups(realm);
+// }
+// list.add(group);
+// }
+
+// list.sort(Comparator.comparing(GroupModel::getName));
+
+// return list;
+// }
+
+// @Override
+// public Long getGroupsCount(RealmModel realm, Boolean onlyTopGroups) {
+// return getRealmDelegate().getGroupsCount(realm, onlyTopGroups);
+// }
+
+// @Override
+// public Long getGroupsCountByNameContaining(RealmModel realm, String search) {
+// return getRealmDelegate().getGroupsCountByNameContaining(realm, search);
+// }
+
+// @Override
+// public List<GroupModel> getTopLevelGroups(RealmModel realm) {
+// String cacheKey = getTopGroupsQueryCacheKey(realm.getId());
+// boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(realm.getId());
+// if (queryDB) {
+// return getRealmDelegate().getTopLevelGroups(realm);
+// }
+
+// GroupListQuery query = cache.get(cacheKey, GroupListQuery.class);
+// if (query != null) {
+// logger.tracev("getTopLevelGroups cache hit: {0}", realm.getName());
+// }
+
+// if (query == null) {
+// Long loaded = cache.getCurrentRevision(cacheKey);
+// List<GroupModel> model = getRealmDelegate().getTopLevelGroups(realm);
+// if (model == null) return null;
+// Set<String> ids = new HashSet<>();
+// for (GroupModel client : model) ids.add(client.getId());
+// query = new GroupListQuery(loaded, cacheKey, realm, ids);
+// logger.tracev("adding realm getTopLevelGroups cache miss: realm {0} key {1}", realm.getName(), cacheKey);
+// cache.addRevisioned(query, startupRevision);
+// return model;
+// }
+// List<GroupModel> list = new LinkedList<>();
+// for (String id : query.getGroups()) {
+// GroupModel group = session.realms().getGroupById(id, realm);
+// if (group == null) {
+// invalidations.add(cacheKey);
+// return getRealmDelegate().getTopLevelGroups(realm);
+// }
+// list.add(group);
+// }
+
+// list.sort(Comparator.comparing(GroupModel::getName));
+
+// return list;
+// }
+
+// @Override
+// public List<GroupModel> getTopLevelGroups(RealmModel realm, Integer first, Integer max) {
+// String cacheKey = getTopGroupsQueryCacheKey(realm.getId() + first + max);
+// boolean queryDB = invalidations.contains(cacheKey) || listInvalidations.contains(realm.getId() + first + max);
+// if (queryDB) {
+// return getRealmDelegate().getTopLevelGroups(realm, first, max);
+// }
+
+// GroupListQuery query = cache.get(cacheKey, GroupListQuery.class);
+// if (Objects.nonNull(query)) {
+// logger.tracev("getTopLevelGroups cache hit: {0}", realm.getName());
+// }
+
+// if (Objects.isNull(query)) {
+// Long loaded = cache.getCurrentRevision(cacheKey);
+// List<GroupModel> model = getRealmDelegate().getTopLevelGroups(realm, first, max);
+// if (model == null) return null;
+// Set<String> ids = new HashSet<>();
+// for (GroupModel client : model) ids.add(client.getId());
+// query = new GroupListQuery(loaded, cacheKey, realm, ids);
+// logger.tracev("adding realm getTopLevelGroups cache miss: realm {0} key {1}", realm.getName(), cacheKey);
+// cache.addRevisioned(query, startupRevision);
+// return model;
+// }
+// List<GroupModel> list = new LinkedList<>();
+// for (String id : query.getGroups()) {
+// GroupModel group = session.realms().getGroupById(id, realm);
+// if (Objects.isNull(group)) {
+// invalidations.add(cacheKey);
+// return getRealmDelegate().getTopLevelGroups(realm);
+// }
+// list.add(group);
+// }
+
+// list.sort(Comparator.comparing(GroupModel::getName));
+
+// return list;
+// }
+
+// @Override
+// public List<GroupModel> searchForGroupByName(RealmModel realm, String search, Integer first, Integer max) {
+// return getRealmDelegate().searchForGroupByName(realm, search, first, max);
+// }
+
+// @Override
+// public boolean removeGroup(RealmModel realm, GroupModel group) {
+// invalidateGroup(group.getId(), realm.getId(), true);
+// listInvalidations.add(realm.getId());
+// cache.groupQueriesInvalidations(realm.getId(), invalidations);
+// if (group.getParentId() != null) {
+// invalidateGroup(group.getParentId(), realm.getId(), false); // Queries already invalidated
+// }
+
+// invalidationEvents.add(GroupRemovedEvent.create(group, realm.getId()));
+
+// return getRealmDelegate().removeGroup(realm, group);
+// }
+
+// @Override
+// public GroupModel createGroup(RealmModel realm, String name) {
+// GroupModel group = getRealmDelegate().createGroup(realm, name);
+// return groupAdded(realm, group);
+// }
+
+// private GroupModel groupAdded(RealmModel realm, GroupModel group) {
+// listInvalidations.add(realm.getId());
+// cache.groupQueriesInvalidations(realm.getId(), invalidations);
+// invalidations.add(group.getId());
+// invalidationEvents.add(GroupAddedEvent.create(group.getId(), realm.getId()));
+// return group;
+// }
+
+// @Override
+// public GroupModel createGroup(RealmModel realm, String id, String name) {
+// GroupModel group = getRealmDelegate().createGroup(realm, id, name);
+// return groupAdded(realm, group);
+// }
+
+// @Override
+// public void addTopLevelGroup(RealmModel realm, GroupModel subGroup) {
+// invalidateGroup(subGroup.getId(), realm.getId(), true);
+// if (subGroup.getParentId() != null) {
+// invalidateGroup(subGroup.getParentId(), realm.getId(), false); // Queries already invalidated
+// }
+
+// addGroupEventIfAbsent(GroupMovedEvent.create(subGroup, null, realm.getId()));
+
+// getRealmDelegate().addTopLevelGroup(realm, subGroup);
+
+// }
+
+// private void addGroupEventIfAbsent(InvalidationEvent eventToAdd) {
+// String groupId = eventToAdd.getId();
+
+// // Check if we have existing event with bigger priority
+// boolean eventAlreadyExists = invalidationEvents.stream()
+// .anyMatch((InvalidationEvent event) -> (event.getId().equals(groupId)) &&
+// (event instanceof GroupAddedEvent || event instanceof GroupMovedEvent || event instanceof GroupRemovedEvent));
+
+// if (!eventAlreadyExists) {
+// invalidationEvents.add(eventToAdd);
+// }
+// }
+
+// @Override
+// public ClientModel getClientById(String id, RealmModel realm) {
+// // CachedClient cached = cache.get(id, CachedClient.class);
+// // if (cached != null && !cached.getRealm().equals(realm.getId())) {
+// // cached = null;
+// // }
+// // if (cached != null) {
+// // logger.tracev("client by id cache hit: {0}", cached.getClientId());
+// // }
+
+// // if (cached == null) {
+// // Long loaded = cache.getCurrentRevision(id);
+// ClientModel model = getClientDelegate().getClientById(id, realm);
+// if (model == null) return null;
+// // ClientModel adapter = cacheClient(realm, model, loaded);
+// // managedApplications.put(id, adapter);
+// // return adapter;
+// return model; // ADDED BY MELOCA
+// // } else if (invalidations.contains(id)) {
+// // return getRealmDelegate().getClientById(id, realm);
+// // } else if (managedApplications.containsKey(id)) {
+// // return managedApplications.get(id);
+// // }
+// // ClientModel adapter = validateCache(realm, cached);
+// // managedApplications.put(id, adapter);
+// // return adapter;
+// }
+
+// // protected ClientModel cacheClient(RealmModel realm, ClientModel delegate, Long revision) {
+// // if (invalidations.contains(delegate.getId())) return delegate;
+// // StorageId storageId = new StorageId(delegate.getId());
+// // // CachedClient cached = null;
+// // ClientAdapter adapter = null;
+
+// // if (!storageId.isLocal()) {
+// // ComponentModel component = realm.getComponent(storageId.getProviderId());
+// // ClientStorageProviderModel model = new ClientStorageProviderModel(component);
+// // if (!model.isEnabled()) {
+// // return delegate;
+// // }
+// // ClientStorageProviderModel.CachePolicy policy = model.getCachePolicy();
+// // if (policy != null && policy == ClientStorageProviderModel.CachePolicy.NO_CACHE) {
+// // return delegate;
+// // }
+
+// // // cached = new CachedClient(revision, realm, delegate);
+// // // adapter = new ClientAdapter(realm, cached, this);
+
+// // // long lifespan = model.getLifespan();
+// // // if (lifespan > 0) {
+// // // cache.addRevisioned(cached, startupRevision, lifespan);
+// // // } else {
+// // // cache.addRevisioned(cached, startupRevision);
+// // // }
+// // // } else {
+// // // cached = new CachedClient(revision, realm, delegate);
+// // // adapter = new ClientAdapter(realm, cached, this);
+// // // cache.addRevisioned(cached, startupRevision);
+// // // }
+
+// // return adapter;
+// // }
+
+
+// // protected ClientModel validateCache(RealmModel realm, CachedClient cached) {
+// // if (!realm.getId().equals(cached.getRealm())) {
+// // return null;
+// // }
+
+// // StorageId storageId = new StorageId(cached.getId());
+// // if (!storageId.isLocal()) {
+// // ComponentModel component = realm.getComponent(storageId.getProviderId());
+// // ClientStorageProviderModel model = new ClientStorageProviderModel(component);
+
+// // // although we do set a timeout, Infinispan has no guarantees when the user will be evicted
+// // // its also hard to test stuff
+// // if (model.shouldInvalidate(cached)) {
+// // registerClientInvalidation(cached.getId(), cached.getClientId(), realm.getId());
+// // return getClientDelegate().getClientById(cached.getId(), realm);
+// // }
+// // }
+// // ClientAdapter adapter = new ClientAdapter(realm, cached, this);
+
+// // return adapter;
+// // }
+
+
+// @Override
+// public ClientModel getClientByClientId(String clientId, RealmModel realm) {
+// String cacheKey = getClientByClientIdCacheKey(clientId, realm.getId());
+// ClientListQuery query = cache.get(cacheKey, ClientListQuery.class);
+// String id = null;
+
+// if (query != null) {
+// logger.tracev("client by name cache hit: {0}", clientId);
+// }
+
+// if (query == null) {
+// Long loaded = cache.getCurrentRevision(cacheKey);
+// ClientModel model = getClientDelegate().getClientByClientId(clientId, realm);
+// if (model == null) return null;
+// if (invalidations.contains(model.getId())) return model;
+// id = model.getId();
+// query = new ClientListQuery(loaded, cacheKey, realm, id);
+// logger.tracev("adding client by name cache miss: {0}", clientId);
+// cache.addRevisioned(query, startupRevision);
+// } else if (invalidations.contains(cacheKey)) {
+// return getClientDelegate().getClientByClientId(clientId, realm);
+// } else {
+// id = query.getClients().iterator().next();
+// if (invalidations.contains(id)) {
+// return getClientDelegate().getClientByClientId(clientId, realm);
+// }
+// }
+// return getClientById(id, realm);
+// }
+
+// static String getClientByClientIdCacheKey(String clientId, String realmId) {
+// return realmId + ".client.query.by.clientId." + clientId;
+// }
+
+// @Override
+// public ClientScopeModel getClientScopeById(String id, RealmModel realm) {
+// CachedClientScope cached = cache.get(id, CachedClientScope.class);
+// if (cached != null && !cached.getRealm().equals(realm.getId())) {
+// cached = null;
+// }
+
+// if (cached == null) {
+// Long loaded = cache.getCurrentRevision(id);
+// ClientScopeModel model = getRealmDelegate().getClientScopeById(id, realm);
+// if (model == null) return null;
+// if (invalidations.contains(id)) return model;
+// cached = new CachedClientScope(loaded, realm, model);
+// cache.addRevisioned(cached, startupRevision);
+// } else if (invalidations.contains(id)) {
+// return getRealmDelegate().getClientScopeById(id, realm);
+// } else if (managedClientScopes.containsKey(id)) {
+// return managedClientScopes.get(id);
+// }
+// ClientScopeAdapter adapter = new ClientScopeAdapter(realm, cached, this);
+// managedClientScopes.put(id, adapter);
+// return adapter;
+// }
+
+// // Don't cache ClientInitialAccessModel for now
+// @Override
+// public ClientInitialAccessModel createClientInitialAccessModel(RealmModel realm, int expiration, int count) {
+// return getRealmDelegate().createClientInitialAccessModel(realm, expiration, count);
+// }
+
+// @Override
+// public ClientInitialAccessModel getClientInitialAccessModel(RealmModel realm, String id) {
+// return getRealmDelegate().getClientInitialAccessModel(realm, id);
+// }
+
+// @Override
+// public void removeClientInitialAccessModel(RealmModel realm, String id) {
+// getRealmDelegate().removeClientInitialAccessModel(realm, id);
+// }
+
+// @Override
+// public List<ClientInitialAccessModel> listClientInitialAccess(RealmModel realm) {
+// return getRealmDelegate().listClientInitialAccess(realm);
+// }
+
+// @Override
+// public void removeExpiredClientInitialAccess() {
+// getRealmDelegate().removeExpiredClientInitialAccess();
+// }
+
+// @Override
+// public void decreaseRemainingCount(RealmModel realm, ClientInitialAccessModel clientInitialAccess) {
+// getRealmDelegate().decreaseRemainingCount(realm, clientInitialAccess);
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RoleAdapter.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RoleAdapter.java
index 51620a1..30cd70f 100755
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RoleAdapter.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/RoleAdapter.java
@@ -1,243 +1,243 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan;
-
-import org.keycloak.models.RealmModel;
-import org.keycloak.models.RoleContainerModel;
-import org.keycloak.models.RoleModel;
-import org.keycloak.models.cache.infinispan.entities.CachedClientRole;
-import org.keycloak.models.cache.infinispan.entities.CachedRealmRole;
-import org.keycloak.models.cache.infinispan.entities.CachedRole;
-import org.keycloak.models.utils.KeycloakModelUtils;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.function.Supplier;
-
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class RoleAdapter implements RoleModel {
-
- protected RoleModel updated;
- protected CachedRole cached;
- protected RealmCacheSession cacheSession;
- protected RealmModel realm;
- protected Set<RoleModel> composites;
- private final Supplier<RoleModel> modelSupplier;
-
- public RoleAdapter(CachedRole cached, RealmCacheSession session, RealmModel realm) {
- this.cached = cached;
- this.cacheSession = session;
- this.realm = realm;
- this.modelSupplier = this::getRoleModel;
- }
-
- protected void getDelegateForUpdate() {
- if (updated == null) {
- cacheSession.registerRoleInvalidation(cached.getId(), cached.getName(), getContainerId());
- updated = modelSupplier.get();
- if (updated == null) throw new IllegalStateException("Not found in database");
- }
- }
-
- protected boolean invalidated;
-
- public void invalidate() {
- invalidated = true;
- }
-
- protected boolean isUpdated() {
- if (updated != null) return true;
- if (!invalidated) return false;
- updated = cacheSession.getRealmDelegate().getRoleById(cached.getId(), realm);
- if (updated == null) throw new IllegalStateException("Not found in database");
- return true;
- }
-
-
- @Override
- public String getName() {
- if (isUpdated()) return updated.getName();
- return cached.getName();
- }
-
- @Override
- public String getDescription() {
- if (isUpdated()) return updated.getDescription();
- return cached.getDescription();
- }
-
- @Override
- public void setDescription(String description) {
- getDelegateForUpdate();
- updated.setDescription(description);
- }
-
- @Override
- public String getId() {
- if (isUpdated()) return updated.getId();
- return cached.getId();
- }
-
- @Override
- public void setName(String name) {
- getDelegateForUpdate();
- updated.setName(name);
- }
-
- @Override
- public boolean isComposite() {
- if (isUpdated()) return updated.isComposite();
- return cached.isComposite();
- }
-
- @Override
- public void addCompositeRole(RoleModel role) {
- getDelegateForUpdate();
- updated.addCompositeRole(role);
- }
-
- @Override
- public void removeCompositeRole(RoleModel role) {
- getDelegateForUpdate();
- updated.removeCompositeRole(role);
- }
-
- @Override
- public Set<RoleModel> getComposites() {
- if (isUpdated()) return updated.getComposites();
-
- if (composites == null) {
- composites = new HashSet<RoleModel>();
- for (String id : cached.getComposites()) {
- RoleModel role = realm.getRoleById(id);
- if (role == null) {
- throw new IllegalStateException("Could not find composite in role " + getName() + ": " + id);
- }
- composites.add(role);
- }
- }
-
- return composites;
- }
-
- @Override
- public boolean isClientRole() {
- return cached instanceof CachedClientRole;
- }
-
- @Override
- public String getContainerId() {
- if (isClientRole()) {
- CachedClientRole appRole = (CachedClientRole) cached;
- return appRole.getClientId();
- } else {
- return realm.getId();
- }
- }
-
-
- @Override
- public RoleContainerModel getContainer() {
- if (cached instanceof CachedRealmRole) {
- return realm;
- } else {
- CachedClientRole appRole = (CachedClientRole) cached;
- return realm.getClientById(appRole.getClientId());
- }
- }
-
- @Override
- public boolean hasRole(RoleModel role) {
- return this.equals(role) || KeycloakModelUtils.searchFor(role, this, new HashSet<>());
- }
-
- @Override
- public void setSingleAttribute(String name, String value) {
- getDelegateForUpdate();
- updated.setSingleAttribute(name, value);
- }
-
- @Override
- public void setAttribute(String name, Collection<String> values) {
- getDelegateForUpdate();
- updated.setAttribute(name, values);
- }
-
- @Override
- public void removeAttribute(String name) {
- getDelegateForUpdate();
- updated.removeAttribute(name);
- }
-
- @Override
- public String getFirstAttribute(String name) {
- if (updated != null) {
- return updated.getFirstAttribute(name);
- }
-
- return cached.getAttributes(modelSupplier).getFirst(name);
- }
-
- @Override
- public List<String> getAttribute(String name) {
- if (updated != null) {
- return updated.getAttribute(name);
- }
-
- List<String> result = cached.getAttributes(modelSupplier).get(name);
- if (result == null) {
- result = Collections.emptyList();
- }
- return result;
- }
-
- @Override
- public Map<String, List<String>> getAttributes() {
- if (updated != null) {
- return updated.getAttributes();
- }
-
- return cached.getAttributes(modelSupplier);
- }
-
- private RoleModel getRoleModel() {
- return cacheSession.getRealmDelegate().getRoleById(cached.getId(), realm);
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || !(o instanceof RoleModel)) return false;
-
- RoleModel that = (RoleModel) o;
- return that.getId().equals(getId());
- }
-
- @Override
- public int hashCode() {
- return getId().hashCode();
- }
-
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan;
+
+// import org.keycloak.models.RealmModel;
+// import org.keycloak.models.RoleContainerModel;
+// import org.keycloak.models.RoleModel;
+// import org.keycloak.models.cache.infinispan.entities.CachedClientRole;
+// import org.keycloak.models.cache.infinispan.entities.CachedRealmRole;
+// import org.keycloak.models.cache.infinispan.entities.CachedRole;
+// import org.keycloak.models.utils.KeycloakModelUtils;
+
+// import java.util.Collection;
+// import java.util.Collections;
+// import java.util.HashSet;
+// import java.util.List;
+// import java.util.Map;
+// import java.util.Set;
+// import java.util.function.Supplier;
+
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public class RoleAdapter implements RoleModel {
+
+// protected RoleModel updated;
+// protected CachedRole cached;
+// protected RealmCacheSession cacheSession;
+// protected RealmModel realm;
+// protected Set<RoleModel> composites;
+// private final Supplier<RoleModel> modelSupplier;
+
+// public RoleAdapter(CachedRole cached, RealmCacheSession session, RealmModel realm) {
+// this.cached = cached;
+// this.cacheSession = session;
+// this.realm = realm;
+// this.modelSupplier = this::getRoleModel;
+// }
+
+// protected void getDelegateForUpdate() {
+// if (updated == null) {
+// cacheSession.registerRoleInvalidation(cached.getId(), cached.getName(), getContainerId());
+// updated = modelSupplier.get();
+// if (updated == null) throw new IllegalStateException("Not found in database");
+// }
+// }
+
+// protected boolean invalidated;
+
+// public void invalidate() {
+// invalidated = true;
+// }
+
+// protected boolean isUpdated() {
+// if (updated != null) return true;
+// if (!invalidated) return false;
+// updated = cacheSession.getRealmDelegate().getRoleById(cached.getId(), realm);
+// if (updated == null) throw new IllegalStateException("Not found in database");
+// return true;
+// }
+
+
+// @Override
+// public String getName() {
+// if (isUpdated()) return updated.getName();
+// return cached.getName();
+// }
+
+// @Override
+// public String getDescription() {
+// if (isUpdated()) return updated.getDescription();
+// return cached.getDescription();
+// }
+
+// @Override
+// public void setDescription(String description) {
+// getDelegateForUpdate();
+// updated.setDescription(description);
+// }
+
+// @Override
+// public String getId() {
+// if (isUpdated()) return updated.getId();
+// return cached.getId();
+// }
+
+// @Override
+// public void setName(String name) {
+// getDelegateForUpdate();
+// updated.setName(name);
+// }
+
+// @Override
+// public boolean isComposite() {
+// if (isUpdated()) return updated.isComposite();
+// return cached.isComposite();
+// }
+
+// @Override
+// public void addCompositeRole(RoleModel role) {
+// getDelegateForUpdate();
+// updated.addCompositeRole(role);
+// }
+
+// @Override
+// public void removeCompositeRole(RoleModel role) {
+// getDelegateForUpdate();
+// updated.removeCompositeRole(role);
+// }
+
+// @Override
+// public Set<RoleModel> getComposites() {
+// if (isUpdated()) return updated.getComposites();
+
+// if (composites == null) {
+// composites = new HashSet<RoleModel>();
+// for (String id : cached.getComposites()) {
+// RoleModel role = realm.getRoleById(id);
+// if (role == null) {
+// throw new IllegalStateException("Could not find composite in role " + getName() + ": " + id);
+// }
+// composites.add(role);
+// }
+// }
+
+// return composites;
+// }
+
+// @Override
+// public boolean isClientRole() {
+// return cached instanceof CachedClientRole;
+// }
+
+// @Override
+// public String getContainerId() {
+// if (isClientRole()) {
+// CachedClientRole appRole = (CachedClientRole) cached;
+// return appRole.getClientId();
+// } else {
+// return realm.getId();
+// }
+// }
+
+
+// @Override
+// public RoleContainerModel getContainer() {
+// if (cached instanceof CachedRealmRole) {
+// return realm;
+// } else {
+// CachedClientRole appRole = (CachedClientRole) cached;
+// return realm.getClientById(appRole.getClientId());
+// }
+// }
+
+// @Override
+// public boolean hasRole(RoleModel role) {
+// return this.equals(role) || KeycloakModelUtils.searchFor(role, this, new HashSet<>());
+// }
+
+// @Override
+// public void setSingleAttribute(String name, String value) {
+// getDelegateForUpdate();
+// updated.setSingleAttribute(name, value);
+// }
+
+// @Override
+// public void setAttribute(String name, Collection<String> values) {
+// getDelegateForUpdate();
+// updated.setAttribute(name, values);
+// }
+
+// @Override
+// public void removeAttribute(String name) {
+// getDelegateForUpdate();
+// updated.removeAttribute(name);
+// }
+
+// @Override
+// public String getFirstAttribute(String name) {
+// if (updated != null) {
+// return updated.getFirstAttribute(name);
+// }
+
+// return cached.getAttributes(modelSupplier).getFirst(name);
+// }
+
+// @Override
+// public List<String> getAttribute(String name) {
+// if (updated != null) {
+// return updated.getAttribute(name);
+// }
+
+// List<String> result = cached.getAttributes(modelSupplier).get(name);
+// if (result == null) {
+// result = Collections.emptyList();
+// }
+// return result;
+// }
+
+// @Override
+// public Map<String, List<String>> getAttributes() {
+// if (updated != null) {
+// return updated.getAttributes();
+// }
+
+// return cached.getAttributes(modelSupplier);
+// }
+
+// private RoleModel getRoleModel() {
+// return cacheSession.getRealmDelegate().getRoleById(cached.getId(), realm);
+// }
+
+// @Override
+// public boolean equals(Object o) {
+// if (this == o) return true;
+// if (o == null || !(o instanceof RoleModel)) return false;
+
+// RoleModel that = (RoleModel) o;
+// return that.getId().equals(getId());
+// }
+
+// @Override
+// public int hashCode() {
+// return getId().hashCode();
+// }
+
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/stream/HasRolePredicate.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/stream/HasRolePredicate.java
index 2523dc9..1a1f3c3 100755
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/stream/HasRolePredicate.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/stream/HasRolePredicate.java
@@ -1,6 +1,6 @@
package org.keycloak.models.cache.infinispan.stream;
-import org.keycloak.models.cache.infinispan.entities.CachedClient;
+// import org.keycloak.models.cache.infinispan.entities.CachedClient;
import org.keycloak.models.cache.infinispan.entities.CachedClientScope;
import org.keycloak.models.cache.infinispan.entities.CachedGroup;
import org.keycloak.models.cache.infinispan.entities.CachedRole;
@@ -50,11 +50,11 @@ public class HasRolePredicate implements Predicate<Map.Entry<String, Revisioned>
RoleQuery roleQuery = (RoleQuery)value;
if (roleQuery.getRoles().contains(role)) return true;
}
- if (value instanceof CachedClient) {
- CachedClient cachedClient = (CachedClient)value;
- if (cachedClient.getScope().contains(role)) return true;
+ // if (value instanceof CachedClient) {
+ // CachedClient cachedClient = (CachedClient)value;
+ // if (cachedClient.getScope().contains(role)) return true;
- }
+ // }
if (value instanceof CachedClientScope) {
CachedClientScope cachedClientScope = (CachedClientScope)value;
if (cachedClientScope.getScope().contains(role)) return true;
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserAdapter.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserAdapter.java
index 9ee1138..d2abf21 100755
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserAdapter.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserAdapter.java
@@ -1,402 +1,402 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan;
-
-import org.keycloak.models.ClientModel;
-import org.keycloak.models.GroupModel;
-import org.keycloak.models.KeycloakSession;
-import org.keycloak.models.RealmModel;
-import org.keycloak.models.RoleContainerModel;
-import org.keycloak.models.RoleModel;
-import org.keycloak.models.UserModel;
-import org.keycloak.models.cache.CachedUserModel;
-import org.keycloak.models.cache.infinispan.entities.CachedUser;
-import org.keycloak.models.utils.KeycloakModelUtils;
-import org.keycloak.models.utils.RoleUtils;
-
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.function.Supplier;
-
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class UserAdapter implements CachedUserModel {
-
- private final Supplier<UserModel> modelSupplier;
- protected final CachedUser cached;
- protected final UserCacheSession userProviderCache;
- protected final KeycloakSession keycloakSession;
- protected final RealmModel realm;
- protected volatile UserModel updated;
-
- public UserAdapter(CachedUser cached, UserCacheSession userProvider, KeycloakSession keycloakSession, RealmModel realm) {
- this.cached = cached;
- this.userProviderCache = userProvider;
- this.keycloakSession = keycloakSession;
- this.realm = realm;
- this.modelSupplier = this::getUserModel;
- }
-
- @Override
- public UserModel getDelegateForUpdate() {
- if (updated == null) {
- userProviderCache.registerUserInvalidation(realm, cached);
- updated = modelSupplier.get();
- if (updated == null) throw new IllegalStateException("Not found in database");
- }
- return updated;
- }
-
- @Override
- public boolean isMarkedForEviction() {
- return updated != null;
- }
-
- @Override
- public void invalidate() {
- getDelegateForUpdate();
- }
-
- @Override
- public long getCacheTimestamp() {
- return cached.getCacheTimestamp();
- }
-
- @Override
- public ConcurrentHashMap getCachedWith() {
- return cached.getCachedWith();
- }
-
- @Override
- public String getId() {
- if (updated != null) return updated.getId();
- return cached.getId();
- }
-
- @Override
- public String getUsername() {
- if (updated != null) return updated.getUsername();
- return cached.getUsername();
- }
-
- @Override
- public void setUsername(String username) {
- getDelegateForUpdate();
- username = KeycloakModelUtils.toLowerCaseSafe(username);
- updated.setUsername(username);
- }
-
- @Override
- public Long getCreatedTimestamp() {
- // get from cached always as it is immutable
- return cached.getCreatedTimestamp();
- }
-
- @Override
- public void setCreatedTimestamp(Long timestamp) {
- // nothing to do as this value is immutable
- }
-
- @Override
- public boolean isEnabled() {
- if (updated != null) return updated.isEnabled();
- return cached.isEnabled();
- }
-
- @Override
- public void setEnabled(boolean enabled) {
- getDelegateForUpdate();
- updated.setEnabled(enabled);
- }
-
- @Override
- public void setSingleAttribute(String name, String value) {
- getDelegateForUpdate();
- updated.setSingleAttribute(name, value);
- }
-
- @Override
- public void setAttribute(String name, List<String> values) {
- getDelegateForUpdate();
- updated.setAttribute(name, values);
- }
-
- @Override
- public void removeAttribute(String name) {
- getDelegateForUpdate();
- updated.removeAttribute(name);
- }
-
- @Override
- public String getFirstAttribute(String name) {
- if (updated != null) return updated.getFirstAttribute(name);
- return cached.getAttributes(modelSupplier).getFirst(name);
- }
-
- @Override
- public List<String> getAttribute(String name) {
- if (updated != null) return updated.getAttribute(name);
- List<String> result = cached.getAttributes(modelSupplier).get(name);
- return (result == null) ? Collections.<String>emptyList() : result;
- }
-
- @Override
- public Map<String, List<String>> getAttributes() {
- if (updated != null) return updated.getAttributes();
- return cached.getAttributes(modelSupplier);
- }
-
- @Override
- public Set<String> getRequiredActions() {
- if (updated != null) return updated.getRequiredActions();
- return cached.getRequiredActions(modelSupplier);
- }
-
- @Override
- public void addRequiredAction(RequiredAction action) {
- getDelegateForUpdate();
- updated.addRequiredAction(action);
- }
-
- @Override
- public void removeRequiredAction(RequiredAction action) {
- getDelegateForUpdate();
- updated.removeRequiredAction(action);
- }
-
- @Override
- public void addRequiredAction(String action) {
- getDelegateForUpdate();
- updated.addRequiredAction(action);
- }
-
- @Override
- public void removeRequiredAction(String action) {
- getDelegateForUpdate();
- updated.removeRequiredAction(action);
- }
-
- @Override
- public String getFirstName() {
- if (updated != null) return updated.getFirstName();
- return cached.getFirstName();
- }
-
- @Override
- public void setFirstName(String firstName) {
- getDelegateForUpdate();
- updated.setFirstName(firstName);
- }
-
- @Override
- public String getLastName() {
- if (updated != null) return updated.getLastName();
- return cached.getLastName();
- }
-
- @Override
- public void setLastName(String lastName) {
- getDelegateForUpdate();
- updated.setLastName(lastName);
- }
-
- @Override
- public String getEmail() {
- if (updated != null) return updated.getEmail();
- return cached.getEmail();
- }
-
- @Override
- public void setEmail(String email) {
- getDelegateForUpdate();
- email = KeycloakModelUtils.toLowerCaseSafe(email);
- updated.setEmail(email);
- }
-
- @Override
- public boolean isEmailVerified() {
- if (updated != null) return updated.isEmailVerified();
- return cached.isEmailVerified();
- }
-
- @Override
- public void setEmailVerified(boolean verified) {
- getDelegateForUpdate();
- updated.setEmailVerified(verified);
- }
-
- @Override
- public String getFederationLink() {
- if (updated != null) return updated.getFederationLink();
- return cached.getFederationLink();
- }
-
- @Override
- public void setFederationLink(String link) {
- getDelegateForUpdate();
- updated.setFederationLink(link);
- }
-
- @Override
- public String getServiceAccountClientLink() {
- if (updated != null) return updated.getServiceAccountClientLink();
- return cached.getServiceAccountClientLink();
- }
-
- @Override
- public void setServiceAccountClientLink(String clientInternalId) {
- getDelegateForUpdate();
- updated.setServiceAccountClientLink(clientInternalId);
- }
-
- @Override
- public Set<RoleModel> getRealmRoleMappings() {
- if (updated != null) return updated.getRealmRoleMappings();
- Set<RoleModel> roleMappings = getRoleMappings();
- Set<RoleModel> realmMappings = new HashSet<RoleModel>();
- for (RoleModel role : roleMappings) {
- RoleContainerModel container = role.getContainer();
- if (container instanceof RealmModel) {
- if (((RealmModel) container).getId().equals(realm.getId())) {
- realmMappings.add(role);
- }
- }
- }
- return realmMappings;
- }
-
- @Override
- public Set<RoleModel> getClientRoleMappings(ClientModel app) {
- if (updated != null) return updated.getClientRoleMappings(app);
- Set<RoleModel> roleMappings = getRoleMappings();
- Set<RoleModel> appMappings = new HashSet<RoleModel>();
- for (RoleModel role : roleMappings) {
- RoleContainerModel container = role.getContainer();
- if (container instanceof ClientModel) {
- if (((ClientModel) container).getId().equals(app.getId())) {
- appMappings.add(role);
- }
- }
- }
- return appMappings;
- }
-
- @Override
- public boolean hasRole(RoleModel role) {
- if (updated != null) return updated.hasRole(role);
- if (cached.getRoleMappings(modelSupplier).contains(role.getId())) return true;
-
- Set<RoleModel> mappings = getRoleMappings();
- for (RoleModel mapping: mappings) {
- if (mapping.hasRole(role)) return true;
- }
- return RoleUtils.hasRoleFromGroup(getGroups(), role, true);
- }
-
- @Override
- public void grantRole(RoleModel role) {
- getDelegateForUpdate();
- updated.grantRole(role);
- }
-
- @Override
- public Set<RoleModel> getRoleMappings() {
- if (updated != null) return updated.getRoleMappings();
- Set<RoleModel> roles = new HashSet<RoleModel>();
- for (String id : cached.getRoleMappings(modelSupplier)) {
- RoleModel roleById = keycloakSession.realms().getRoleById(id, realm);
- if (roleById == null) {
- // chance that role was removed, so just delete to persistence and get user invalidated
- getDelegateForUpdate();
- return updated.getRoleMappings();
- }
- roles.add(roleById);
-
- }
- return roles;
- }
-
- @Override
- public void deleteRoleMapping(RoleModel role) {
- getDelegateForUpdate();
- updated.deleteRoleMapping(role);
- }
-
- @Override
- public Set<GroupModel> getGroups() {
- if (updated != null) return updated.getGroups();
- Set<GroupModel> groups = new LinkedHashSet<>();
- for (String id : cached.getGroups(modelSupplier)) {
- GroupModel groupModel = keycloakSession.realms().getGroupById(id, realm);
- if (groupModel == null) {
- // chance that role was removed, so just delete to persistence and get user invalidated
- getDelegateForUpdate();
- return updated.getGroups();
- }
- groups.add(groupModel);
-
- }
- return groups;
- }
-
- @Override
- public void joinGroup(GroupModel group) {
- getDelegateForUpdate();
- updated.joinGroup(group);
-
- }
-
- @Override
- public void leaveGroup(GroupModel group) {
- getDelegateForUpdate();
- updated.leaveGroup(group);
- }
-
- @Override
- public boolean isMemberOf(GroupModel group) {
- if (updated != null) return updated.isMemberOf(group);
- if (cached.getGroups(modelSupplier).contains(group.getId())) return true;
- Set<GroupModel> roles = getGroups();
- return RoleUtils.isMember(roles, group);
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || !(o instanceof UserModel)) return false;
-
- UserModel that = (UserModel) o;
- return that.getId().equals(getId());
- }
-
- @Override
- public int hashCode() {
- return getId().hashCode();
- }
-
- private UserModel getUserModel() {
- return userProviderCache.getDelegate().getUserById(cached.getId(), realm);
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan;
+
+// import org.keycloak.models.ClientModel;
+// import org.keycloak.models.GroupModel;
+// import org.keycloak.models.KeycloakSession;
+// import org.keycloak.models.RealmModel;
+// import org.keycloak.models.RoleContainerModel;
+// import org.keycloak.models.RoleModel;
+// import org.keycloak.models.UserModel;
+// import org.keycloak.models.cache.CachedUserModel;
+// import org.keycloak.models.cache.infinispan.entities.CachedUser;
+// import org.keycloak.models.utils.KeycloakModelUtils;
+// import org.keycloak.models.utils.RoleUtils;
+
+// import java.util.Collections;
+// import java.util.HashSet;
+// import java.util.LinkedHashSet;
+// import java.util.List;
+// import java.util.Map;
+// import java.util.Set;
+// import java.util.concurrent.ConcurrentHashMap;
+// import java.util.function.Supplier;
+
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public class UserAdapter implements CachedUserModel {
+
+// private final Supplier<UserModel> modelSupplier;
+// protected final CachedUser cached;
+// protected final UserCacheSession userProviderCache;
+// protected final KeycloakSession keycloakSession;
+// protected final RealmModel realm;
+// protected volatile UserModel updated;
+
+// public UserAdapter(CachedUser cached, UserCacheSession userProvider, KeycloakSession keycloakSession, RealmModel realm) {
+// this.cached = cached;
+// this.userProviderCache = userProvider;
+// this.keycloakSession = keycloakSession;
+// this.realm = realm;
+// this.modelSupplier = this::getUserModel;
+// }
+
+// @Override
+// public UserModel getDelegateForUpdate() {
+// if (updated == null) {
+// userProviderCache.registerUserInvalidation(realm, cached);
+// updated = modelSupplier.get();
+// if (updated == null) throw new IllegalStateException("Not found in database");
+// }
+// return updated;
+// }
+
+// @Override
+// public boolean isMarkedForEviction() {
+// return updated != null;
+// }
+
+// @Override
+// public void invalidate() {
+// getDelegateForUpdate();
+// }
+
+// @Override
+// public long getCacheTimestamp() {
+// // return cached.getCacheTimestamp();
+// }
+
+// @Override
+// public ConcurrentHashMap getCachedWith() {
+// return cached.getCachedWith();
+// }
+
+// @Override
+// public String getId() {
+// if (updated != null) return updated.getId();
+// return cached.getId();
+// }
+
+// @Override
+// public String getUsername() {
+// if (updated != null) return updated.getUsername();
+// return cached.getUsername();
+// }
+
+// @Override
+// public void setUsername(String username) {
+// getDelegateForUpdate();
+// username = KeycloakModelUtils.toLowerCaseSafe(username);
+// updated.setUsername(username);
+// }
+
+// @Override
+// public Long getCreatedTimestamp() {
+// // get from cached always as it is immutable
+// return cached.getCreatedTimestamp();
+// }
+
+// @Override
+// public void setCreatedTimestamp(Long timestamp) {
+// // nothing to do as this value is immutable
+// }
+
+// @Override
+// public boolean isEnabled() {
+// if (updated != null) return updated.isEnabled();
+// return cached.isEnabled();
+// }
+
+// @Override
+// public void setEnabled(boolean enabled) {
+// getDelegateForUpdate();
+// updated.setEnabled(enabled);
+// }
+
+// @Override
+// public void setSingleAttribute(String name, String value) {
+// getDelegateForUpdate();
+// updated.setSingleAttribute(name, value);
+// }
+
+// @Override
+// public void setAttribute(String name, List<String> values) {
+// getDelegateForUpdate();
+// updated.setAttribute(name, values);
+// }
+
+// @Override
+// public void removeAttribute(String name) {
+// getDelegateForUpdate();
+// updated.removeAttribute(name);
+// }
+
+// @Override
+// public String getFirstAttribute(String name) {
+// if (updated != null) return updated.getFirstAttribute(name);
+// return cached.getAttributes(modelSupplier).getFirst(name);
+// }
+
+// @Override
+// public List<String> getAttribute(String name) {
+// if (updated != null) return updated.getAttribute(name);
+// List<String> result = cached.getAttributes(modelSupplier).get(name);
+// return (result == null) ? Collections.<String>emptyList() : result;
+// }
+
+// @Override
+// public Map<String, List<String>> getAttributes() {
+// if (updated != null) return updated.getAttributes();
+// return cached.getAttributes(modelSupplier);
+// }
+
+// @Override
+// public Set<String> getRequiredActions() {
+// if (updated != null) return updated.getRequiredActions();
+// return cached.getRequiredActions(modelSupplier);
+// }
+
+// @Override
+// public void addRequiredAction(RequiredAction action) {
+// getDelegateForUpdate();
+// updated.addRequiredAction(action);
+// }
+
+// @Override
+// public void removeRequiredAction(RequiredAction action) {
+// getDelegateForUpdate();
+// updated.removeRequiredAction(action);
+// }
+
+// @Override
+// public void addRequiredAction(String action) {
+// getDelegateForUpdate();
+// updated.addRequiredAction(action);
+// }
+
+// @Override
+// public void removeRequiredAction(String action) {
+// getDelegateForUpdate();
+// updated.removeRequiredAction(action);
+// }
+
+// @Override
+// public String getFirstName() {
+// if (updated != null) return updated.getFirstName();
+// return cached.getFirstName();
+// }
+
+// @Override
+// public void setFirstName(String firstName) {
+// getDelegateForUpdate();
+// updated.setFirstName(firstName);
+// }
+
+// @Override
+// public String getLastName() {
+// if (updated != null) return updated.getLastName();
+// return cached.getLastName();
+// }
+
+// @Override
+// public void setLastName(String lastName) {
+// getDelegateForUpdate();
+// updated.setLastName(lastName);
+// }
+
+// @Override
+// public String getEmail() {
+// if (updated != null) return updated.getEmail();
+// return cached.getEmail();
+// }
+
+// @Override
+// public void setEmail(String email) {
+// getDelegateForUpdate();
+// email = KeycloakModelUtils.toLowerCaseSafe(email);
+// updated.setEmail(email);
+// }
+
+// @Override
+// public boolean isEmailVerified() {
+// if (updated != null) return updated.isEmailVerified();
+// return cached.isEmailVerified();
+// }
+
+// @Override
+// public void setEmailVerified(boolean verified) {
+// getDelegateForUpdate();
+// updated.setEmailVerified(verified);
+// }
+
+// @Override
+// public String getFederationLink() {
+// if (updated != null) return updated.getFederationLink();
+// return cached.getFederationLink();
+// }
+
+// @Override
+// public void setFederationLink(String link) {
+// getDelegateForUpdate();
+// updated.setFederationLink(link);
+// }
+
+// @Override
+// public String getServiceAccountClientLink() {
+// if (updated != null) return updated.getServiceAccountClientLink();
+// return cached.getServiceAccountClientLink();
+// }
+
+// @Override
+// public void setServiceAccountClientLink(String clientInternalId) {
+// getDelegateForUpdate();
+// updated.setServiceAccountClientLink(clientInternalId);
+// }
+
+// @Override
+// public Set<RoleModel> getRealmRoleMappings() {
+// if (updated != null) return updated.getRealmRoleMappings();
+// Set<RoleModel> roleMappings = getRoleMappings();
+// Set<RoleModel> realmMappings = new HashSet<RoleModel>();
+// for (RoleModel role : roleMappings) {
+// RoleContainerModel container = role.getContainer();
+// if (container instanceof RealmModel) {
+// if (((RealmModel) container).getId().equals(realm.getId())) {
+// realmMappings.add(role);
+// }
+// }
+// }
+// return realmMappings;
+// }
+
+// @Override
+// public Set<RoleModel> getClientRoleMappings(ClientModel app) {
+// if (updated != null) return updated.getClientRoleMappings(app);
+// Set<RoleModel> roleMappings = getRoleMappings();
+// Set<RoleModel> appMappings = new HashSet<RoleModel>();
+// for (RoleModel role : roleMappings) {
+// RoleContainerModel container = role.getContainer();
+// if (container instanceof ClientModel) {
+// if (((ClientModel) container).getId().equals(app.getId())) {
+// appMappings.add(role);
+// }
+// }
+// }
+// return appMappings;
+// }
+
+// @Override
+// public boolean hasRole(RoleModel role) {
+// if (updated != null) return updated.hasRole(role);
+// if (cached.getRoleMappings(modelSupplier).contains(role.getId())) return true;
+
+// Set<RoleModel> mappings = getRoleMappings();
+// for (RoleModel mapping: mappings) {
+// if (mapping.hasRole(role)) return true;
+// }
+// return RoleUtils.hasRoleFromGroup(getGroups(), role, true);
+// }
+
+// @Override
+// public void grantRole(RoleModel role) {
+// getDelegateForUpdate();
+// updated.grantRole(role);
+// }
+
+// @Override
+// public Set<RoleModel> getRoleMappings() {
+// if (updated != null) return updated.getRoleMappings();
+// Set<RoleModel> roles = new HashSet<RoleModel>();
+// for (String id : cached.getRoleMappings(modelSupplier)) {
+// RoleModel roleById = keycloakSession.realms().getRoleById(id, realm);
+// if (roleById == null) {
+// // chance that role was removed, so just delete to persistence and get user invalidated
+// getDelegateForUpdate();
+// return updated.getRoleMappings();
+// }
+// roles.add(roleById);
+
+// }
+// return roles;
+// }
+
+// @Override
+// public void deleteRoleMapping(RoleModel role) {
+// getDelegateForUpdate();
+// updated.deleteRoleMapping(role);
+// }
+
+// @Override
+// public Set<GroupModel> getGroups() {
+// if (updated != null) return updated.getGroups();
+// Set<GroupModel> groups = new LinkedHashSet<>();
+// for (String id : cached.getGroups(modelSupplier)) {
+// GroupModel groupModel = keycloakSession.realms().getGroupById(id, realm);
+// if (groupModel == null) {
+// // chance that role was removed, so just delete to persistence and get user invalidated
+// getDelegateForUpdate();
+// return updated.getGroups();
+// }
+// groups.add(groupModel);
+
+// }
+// return groups;
+// }
+
+// @Override
+// public void joinGroup(GroupModel group) {
+// getDelegateForUpdate();
+// updated.joinGroup(group);
+
+// }
+
+// @Override
+// public void leaveGroup(GroupModel group) {
+// getDelegateForUpdate();
+// updated.leaveGroup(group);
+// }
+
+// @Override
+// public boolean isMemberOf(GroupModel group) {
+// if (updated != null) return updated.isMemberOf(group);
+// if (cached.getGroups(modelSupplier).contains(group.getId())) return true;
+// Set<GroupModel> roles = getGroups();
+// return RoleUtils.isMember(roles, group);
+// }
+
+// @Override
+// public boolean equals(Object o) {
+// if (this == o) return true;
+// if (o == null || !(o instanceof UserModel)) return false;
+
+// UserModel that = (UserModel) o;
+// return that.getId().equals(getId());
+// }
+
+// @Override
+// public int hashCode() {
+// return getId().hashCode();
+// }
+
+// private UserModel getUserModel() {
+// return userProviderCache.getDelegate().getUserById(cached.getId(), realm);
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserCacheManager.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserCacheManager.java
index 9126b2f..70b92d6 100755
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserCacheManager.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserCacheManager.java
@@ -1,109 +1,109 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan;
-
-import org.infinispan.Cache;
-import org.jboss.logging.Logger;
-import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
-import org.keycloak.models.cache.infinispan.entities.Revisioned;
-import org.keycloak.models.cache.infinispan.events.UserCacheInvalidationEvent;
-import org.keycloak.models.cache.infinispan.stream.InRealmPredicate;
-
-import java.util.Map;
-import java.util.Set;
-
-/**
- * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
- */
-public class UserCacheManager extends CacheManager {
-
- private static final Logger logger = Logger.getLogger(UserCacheManager.class);
-
- protected volatile boolean enabled = true;
-
- public UserCacheManager(Cache<String, Revisioned> cache, Cache<String, Long> revisions) {
- super(cache, revisions);
- }
-
- @Override
- protected Logger getLogger() {
- return logger;
- }
-
- @Override
- public void clear() {
- cache.clear();
- revisions.clear();
- }
-
-
- public void userUpdatedInvalidations(String userId, String username, String email, String realmId, Set<String> invalidations) {
- invalidations.add(userId);
- if (email != null) invalidations.add(UserCacheSession.getUserByEmailCacheKey(realmId, email));
- invalidations.add(UserCacheSession.getUserByUsernameCacheKey(realmId, username));
- }
-
- // Fully invalidate user including consents and federatedIdentity links.
- public void fullUserInvalidation(String userId, String username, String email, String realmId, boolean identityFederationEnabled, Map<String, String> federatedIdentities, Set<String> invalidations) {
- userUpdatedInvalidations(userId, username, email, realmId, invalidations);
-
- if (identityFederationEnabled) {
- // Invalidate all keys for lookup this user by any identityProvider link
- for (Map.Entry<String, String> socialLink : federatedIdentities.entrySet()) {
- String fedIdentityCacheKey = UserCacheSession.getUserByFederatedIdentityCacheKey(realmId, socialLink.getKey(), socialLink.getValue());
- invalidations.add(fedIdentityCacheKey);
- }
-
- // Invalidate federationLinks of user
- invalidations.add(UserCacheSession.getFederatedIdentityLinksCacheKey(userId));
- }
-
- // Consents
- invalidations.add(UserCacheSession.getConsentCacheKey(userId));
- }
-
- public void federatedIdentityLinkUpdatedInvalidation(String userId, Set<String> invalidations) {
- invalidations.add(UserCacheSession.getFederatedIdentityLinksCacheKey(userId));
- }
-
- public void federatedIdentityLinkRemovedInvalidation(String userId, String realmId, String identityProviderId, String socialUserId, Set<String> invalidations) {
- invalidations.add(UserCacheSession.getFederatedIdentityLinksCacheKey(userId));
- if (identityProviderId != null) {
- invalidations.add(UserCacheSession.getUserByFederatedIdentityCacheKey(realmId, identityProviderId, socialUserId));
- }
- }
-
- public void consentInvalidation(String userId, Set<String> invalidations) {
- invalidations.add(UserCacheSession.getConsentCacheKey(userId));
- }
-
-
- @Override
- protected void addInvalidationsFromEvent(InvalidationEvent event, Set<String> invalidations) {
- ((UserCacheInvalidationEvent) event).addInvalidations(this, invalidations);
- }
-
- public void invalidateRealmUsers(String realm, Set<String> invalidations) {
- InRealmPredicate inRealmPredicate = getInRealmPredicate(realm);
- addInvalidations(inRealmPredicate, invalidations);
- }
-
- private InRealmPredicate getInRealmPredicate(String realmId) {
- return InRealmPredicate.create().realm(realmId);
- }
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan;
+
+// import org.infinispan.Cache;
+// import org.jboss.logging.Logger;
+// import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
+// import org.keycloak.models.cache.infinispan.entities.Revisioned;
+// import org.keycloak.models.cache.infinispan.events.UserCacheInvalidationEvent;
+// import org.keycloak.models.cache.infinispan.stream.InRealmPredicate;
+
+// import java.util.Map;
+// import java.util.Set;
+
+// /**
+// * @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
+// */
+// public class UserCacheManager extends CacheManager {
+
+// private static final Logger logger = Logger.getLogger(UserCacheManager.class);
+
+// protected volatile boolean enabled = true;
+
+// public UserCacheManager(Cache<String, Revisioned> cache, Cache<String, Long> revisions) {
+// super(cache, revisions);
+// }
+
+// @Override
+// protected Logger getLogger() {
+// return logger;
+// }
+
+// @Override
+// public void clear() {
+// cache.clear();
+// revisions.clear();
+// }
+
+
+// public void userUpdatedInvalidations(String userId, String username, String email, String realmId, Set<String> invalidations) {
+// invalidations.add(userId);
+// if (email != null) invalidations.add(UserCacheSession.getUserByEmailCacheKey(realmId, email));
+// invalidations.add(UserCacheSession.getUserByUsernameCacheKey(realmId, username));
+// }
+
+// // Fully invalidate user including consents and federatedIdentity links.
+// public void fullUserInvalidation(String userId, String username, String email, String realmId, boolean identityFederationEnabled, Map<String, String> federatedIdentities, Set<String> invalidations) {
+// userUpdatedInvalidations(userId, username, email, realmId, invalidations);
+
+// if (identityFederationEnabled) {
+// // Invalidate all keys for lookup this user by any identityProvider link
+// for (Map.Entry<String, String> socialLink : federatedIdentities.entrySet()) {
+// String fedIdentityCacheKey = UserCacheSession.getUserByFederatedIdentityCacheKey(realmId, socialLink.getKey(), socialLink.getValue());
+// invalidations.add(fedIdentityCacheKey);
+// }
+
+// // Invalidate federationLinks of user
+// invalidations.add(UserCacheSession.getFederatedIdentityLinksCacheKey(userId));
+// }
+
+// // Consents
+// invalidations.add(UserCacheSession.getConsentCacheKey(userId));
+// }
+
+// public void federatedIdentityLinkUpdatedInvalidation(String userId, Set<String> invalidations) {
+// invalidations.add(UserCacheSession.getFederatedIdentityLinksCacheKey(userId));
+// }
+
+// public void federatedIdentityLinkRemovedInvalidation(String userId, String realmId, String identityProviderId, String socialUserId, Set<String> invalidations) {
+// invalidations.add(UserCacheSession.getFederatedIdentityLinksCacheKey(userId));
+// if (identityProviderId != null) {
+// invalidations.add(UserCacheSession.getUserByFederatedIdentityCacheKey(realmId, identityProviderId, socialUserId));
+// }
+// }
+
+// public void consentInvalidation(String userId, Set<String> invalidations) {
+// invalidations.add(UserCacheSession.getConsentCacheKey(userId));
+// }
+
+
+// @Override
+// protected void addInvalidationsFromEvent(InvalidationEvent event, Set<String> invalidations) {
+// ((UserCacheInvalidationEvent) event).addInvalidations(this, invalidations);
+// }
+
+// public void invalidateRealmUsers(String realm, Set<String> invalidations) {
+// InRealmPredicate inRealmPredicate = getInRealmPredicate(realm);
+// addInvalidations(inRealmPredicate, invalidations);
+// }
+
+// private InRealmPredicate getInRealmPredicate(String realmId) {
+// return InRealmPredicate.create().realm(realmId);
+// }
+// }
diff --git a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserCacheSession.java b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserCacheSession.java
index 7e4ddad..32b00df 100755
--- a/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserCacheSession.java
+++ b/model/infinispan/src/main/java/org/keycloak/models/cache/infinispan/UserCacheSession.java
@@ -1,889 +1,889 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.models.cache.infinispan;
-
-import org.jboss.logging.Logger;
-import org.keycloak.cluster.ClusterProvider;
-import org.keycloak.models.ClientScopeModel;
-import org.keycloak.models.cache.CachedObject;
-import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
-import org.keycloak.common.constants.ServiceAccountConstants;
-import org.keycloak.common.util.Time;
-import org.keycloak.component.ComponentModel;
-import org.keycloak.models.ClientModel;
-import org.keycloak.models.FederatedIdentityModel;
-import org.keycloak.models.GroupModel;
-import org.keycloak.models.KeycloakSession;
-import org.keycloak.models.KeycloakTransaction;
-import org.keycloak.models.ProtocolMapperModel;
-import org.keycloak.models.RealmModel;
-import org.keycloak.models.RoleModel;
-import org.keycloak.models.UserConsentModel;
-import org.keycloak.models.UserModel;
-import org.keycloak.models.UserProvider;
-import org.keycloak.models.cache.CachedUserModel;
-import org.keycloak.models.cache.OnUserCache;
-import org.keycloak.models.cache.UserCache;
-import org.keycloak.models.cache.infinispan.entities.CachedFederatedIdentityLinks;
-import org.keycloak.models.cache.infinispan.entities.CachedUser;
-import org.keycloak.models.cache.infinispan.entities.CachedUserConsent;
-import org.keycloak.models.cache.infinispan.entities.CachedUserConsents;
-import org.keycloak.models.cache.infinispan.entities.UserListQuery;
-import org.keycloak.models.cache.infinispan.events.UserCacheRealmInvalidationEvent;
-import org.keycloak.models.cache.infinispan.events.UserConsentsUpdatedEvent;
-import org.keycloak.models.cache.infinispan.events.UserFederationLinkRemovedEvent;
-import org.keycloak.models.cache.infinispan.events.UserFederationLinkUpdatedEvent;
-import org.keycloak.models.cache.infinispan.events.UserFullInvalidationEvent;
-import org.keycloak.models.cache.infinispan.events.UserUpdatedEvent;
-import org.keycloak.models.utils.KeycloakModelUtils;
-import org.keycloak.models.utils.ReadOnlyUserModelDelegate;
-import org.keycloak.storage.CacheableStorageProviderModel;
-import org.keycloak.storage.StorageId;
-import org.keycloak.storage.UserStorageProvider;
-import org.keycloak.storage.UserStorageProviderModel;
-import org.keycloak.storage.client.ClientStorageProvider;
-
-import java.util.Calendar;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class UserCacheSession implements UserCache {
- protected static final Logger logger = Logger.getLogger(UserCacheSession.class);
- protected UserCacheManager cache;
- protected KeycloakSession session;
- protected UserProvider delegate;
- protected boolean transactionActive;
- protected boolean setRollbackOnly;
- protected final long startupRevision;
-
-
- protected Set<String> invalidations = new HashSet<>();
- protected Set<String> realmInvalidations = new HashSet<>();
- protected Set<InvalidationEvent> invalidationEvents = new HashSet<>(); // Events to be sent across cluster
- protected Map<String, UserModel> managedUsers = new HashMap<>();
-
- public UserCacheSession(UserCacheManager cache, KeycloakSession session) {
- this.cache = cache;
- this.session = session;
- this.startupRevision = cache.getCurrentCounter();
- session.getTransactionManager().enlistAfterCompletion(getTransaction());
- }
-
- @Override
- public void clear() {
- cache.clear();
- ClusterProvider cluster = session.getProvider(ClusterProvider.class);
- cluster.notify(InfinispanUserCacheProviderFactory.USER_CLEAR_CACHE_EVENTS, new ClearCacheEvent(), true, ClusterProvider.DCNotify.ALL_DCS);
- }
-
- public UserProvider getDelegate() {
- if (!transactionActive) throw new IllegalStateException("Cannot access delegate without a transaction");
- if (delegate != null) return delegate;
- delegate = session.userStorageManager();
-
- return delegate;
- }
-
- public void registerUserInvalidation(RealmModel realm,CachedUser user) {
- cache.userUpdatedInvalidations(user.getId(), user.getUsername(), user.getEmail(), user.getRealm(), invalidations);
- invalidationEvents.add(UserUpdatedEvent.create(user.getId(), user.getUsername(), user.getEmail(), user.getRealm()));
- }
-
- @Override
- public void evict(RealmModel realm, UserModel user) {
- if (!transactionActive) throw new IllegalStateException("Cannot call evict() without a transaction");
- getDelegate(); // invalidations need delegate set
- if (user instanceof CachedUserModel) {
- ((CachedUserModel)user).invalidate();
- } else {
- cache.userUpdatedInvalidations(user.getId(), user.getUsername(), user.getEmail(), realm.getId(), invalidations);
- invalidationEvents.add(UserUpdatedEvent.create(user.getId(), user.getUsername(), user.getEmail(), realm.getId()));
- }
- }
-
- @Override
- public void evict(RealmModel realm) {
- addRealmInvalidation(realm.getId());
- }
-
- protected void runInvalidations() {
- for (String realmId : realmInvalidations) {
- cache.invalidateRealmUsers(realmId, invalidations);
- }
- for (String invalidation : invalidations) {
- cache.invalidateObject(invalidation);
- }
-
- cache.sendInvalidationEvents(session, invalidationEvents, InfinispanUserCacheProviderFactory.USER_INVALIDATION_EVENTS);
- }
-
- private KeycloakTransaction getTransaction() {
- return new KeycloakTransaction() {
- @Override
- public void begin() {
- transactionActive = true;
- }
-
- @Override
- public void commit() {
- runInvalidations();
- transactionActive = false;
- }
-
- @Override
- public void rollback() {
- setRollbackOnly = true;
- runInvalidations();
- transactionActive = false;
- }
-
- @Override
- public void setRollbackOnly() {
- setRollbackOnly = true;
- }
-
- @Override
- public boolean getRollbackOnly() {
- return setRollbackOnly;
- }
-
- @Override
- public boolean isActive() {
- return transactionActive;
- }
- };
- }
-
- private boolean isRegisteredForInvalidation(RealmModel realm, String userId) {
- return realmInvalidations.contains(realm.getId()) || invalidations.contains(userId);
- }
-
- @Override
- public UserModel getUserById(String id, RealmModel realm) {
- logger.tracev("getuserById {0}", id);
- if (isRegisteredForInvalidation(realm, id)) {
- logger.trace("registered for invalidation return delegate");
- return getDelegate().getUserById(id, realm);
- }
- if (managedUsers.containsKey(id)) {
- logger.trace("return managedusers");
- return managedUsers.get(id);
- }
-
- CachedUser cached = cache.get(id, CachedUser.class);
- UserModel adapter = null;
- if (cached == null) {
- logger.trace("not cached");
- Long loaded = cache.getCurrentRevision(id);
- UserModel delegate = getDelegate().getUserById(id, realm);
- if (delegate == null) {
- logger.trace("delegate returning null");
- return null;
- }
- adapter = cacheUser(realm, delegate, loaded);
- } else {
- adapter = validateCache(realm, cached);
- }
- managedUsers.put(id, adapter);
- return adapter;
- }
-
- static String getUserByUsernameCacheKey(String realmId, String username) {
- return realmId + ".username." + username;
- }
-
- static String getUserByEmailCacheKey(String realmId, String email) {
- return realmId + ".email." + email;
- }
-
- private static String getUserByFederatedIdentityCacheKey(String realmId, FederatedIdentityModel socialLink) {
- return getUserByFederatedIdentityCacheKey(realmId, socialLink.getIdentityProvider(), socialLink.getUserId());
- }
-
- static String getUserByFederatedIdentityCacheKey(String realmId, String identityProvider, String socialUserId) {
- return realmId + ".idp." + identityProvider + "." + socialUserId;
- }
-
- static String getFederatedIdentityLinksCacheKey(String userId) {
- return userId + ".idplinks";
- }
-
- @Override
- public UserModel getUserByUsername(String username, RealmModel realm) {
- logger.tracev("getUserByUsername: {0}", username);
- username = username.toLowerCase();
- if (realmInvalidations.contains(realm.getId())) {
- logger.tracev("realmInvalidations");
- return getDelegate().getUserByUsername(username, realm);
- }
- String cacheKey = getUserByUsernameCacheKey(realm.getId(), username);
- if (invalidations.contains(cacheKey)) {
- logger.tracev("invalidations");
- return getDelegate().getUserByUsername(username, realm);
- }
- UserListQuery query = cache.get(cacheKey, UserListQuery.class);
-
- String userId = null;
- if (query == null) {
- logger.tracev("query null");
- Long loaded = cache.getCurrentRevision(cacheKey);
- UserModel model = getDelegate().getUserByUsername(username, realm);
- if (model == null) {
- logger.tracev("model from delegate null");
- return null;
- }
- userId = model.getId();
- if (invalidations.contains(userId)) return model;
- if (managedUsers.containsKey(userId)) {
- logger.tracev("return managed user");
- return managedUsers.get(userId);
- }
-
- UserModel adapter = getUserAdapter(realm, userId, loaded, model);
- if (adapter instanceof UserAdapter) { // this was cached, so we can cache query too
- query = new UserListQuery(loaded, cacheKey, realm, model.getId());
- cache.addRevisioned(query, startupRevision);
- }
- managedUsers.put(userId, adapter);
- return adapter;
- } else {
- userId = query.getUsers().iterator().next();
- if (invalidations.contains(userId)) {
- logger.tracev("invalidated cache return delegate");
- return getDelegate().getUserByUsername(username, realm);
-
- }
- logger.trace("return getUserById");
- return getUserById(userId, realm);
- }
- }
-
- protected UserModel getUserAdapter(RealmModel realm, String userId, Long loaded, UserModel delegate) {
- CachedUser cached = cache.get(userId, CachedUser.class);
- if (cached == null) {
- return cacheUser(realm, delegate, loaded);
- } else {
- return validateCache(realm, cached);
- }
- }
-
- protected UserModel validateCache(RealmModel realm, CachedUser cached) {
- if (!realm.getId().equals(cached.getRealm())) {
- return null;
- }
-
- StorageId storageId = cached.getFederationLink() != null ?
- new StorageId(cached.getFederationLink(), cached.getId()) : new StorageId(cached.getId());
-
- if (!storageId.isLocal()) {
- ComponentModel component = realm.getComponent(storageId.getProviderId());
- CacheableStorageProviderModel model = new CacheableStorageProviderModel(component);
-
- // although we do set a timeout, Infinispan has no guarantees when the user will be evicted
- // its also hard to test stuff
- if (model.shouldInvalidate(cached)) {
- registerUserInvalidation(realm, cached);
- return getDelegate().getUserById(cached.getId(), realm);
- }
- }
- return new UserAdapter(cached, this, session, realm);
- }
-
- protected UserModel cacheUser(RealmModel realm, UserModel delegate, Long revision) {
- int notBefore = getDelegate().getNotBeforeOfUser(realm, delegate);
-
- StorageId storageId = delegate.getFederationLink() != null ?
- new StorageId(delegate.getFederationLink(), delegate.getId()) : new StorageId(delegate.getId());
- CachedUser cached = null;
- UserAdapter adapter = null;
-
- if (!storageId.isLocal()) {
- ComponentModel component = realm.getComponent(storageId.getProviderId());
- UserStorageProviderModel model = new UserStorageProviderModel(component);
- if (!model.isEnabled()) {
- return new ReadOnlyUserModelDelegate(delegate) {
- @Override
- public boolean isEnabled() {
- return false;
- }
- };
- }
- UserStorageProviderModel.CachePolicy policy = model.getCachePolicy();
- if (policy != null && policy == UserStorageProviderModel.CachePolicy.NO_CACHE) {
- return delegate;
- }
-
- cached = new CachedUser(revision, realm, delegate, notBefore);
- adapter = new UserAdapter(cached, this, session, realm);
- onCache(realm, adapter, delegate);
-
- long lifespan = model.getLifespan();
- if (lifespan > 0) {
- cache.addRevisioned(cached, startupRevision, lifespan);
- } else {
- cache.addRevisioned(cached, startupRevision);
- }
- } else {
- cached = new CachedUser(revision, realm, delegate, notBefore);
- adapter = new UserAdapter(cached, this, session, realm);
- onCache(realm, adapter, delegate);
- cache.addRevisioned(cached, startupRevision);
- }
-
- return adapter;
- }
-
- private void onCache(RealmModel realm, UserAdapter adapter, UserModel delegate) {
- ((OnUserCache)getDelegate()).onCache(realm, adapter, delegate);
- ((OnUserCache)session.userCredentialManager()).onCache(realm, adapter, delegate);
- }
-
- @Override
- public UserModel getUserByEmail(String email, RealmModel realm) {
- if (email == null) return null;
- email = email.toLowerCase();
- if (realmInvalidations.contains(realm.getId())) {
- return getDelegate().getUserByEmail(email, realm);
- }
- String cacheKey = getUserByEmailCacheKey(realm.getId(), email);
- if (invalidations.contains(cacheKey)) {
- return getDelegate().getUserByEmail(email, realm);
- }
- UserListQuery query = cache.get(cacheKey, UserListQuery.class);
-
- String userId = null;
- if (query == null) {
- Long loaded = cache.getCurrentRevision(cacheKey);
- UserModel model = getDelegate().getUserByEmail(email, realm);
- if (model == null) return null;
- userId = model.getId();
- if (invalidations.contains(userId)) return model;
- if (managedUsers.containsKey(userId)) return managedUsers.get(userId);
-
- UserModel adapter = getUserAdapter(realm, userId, loaded, model);
- if (adapter instanceof UserAdapter) {
- query = new UserListQuery(loaded, cacheKey, realm, model.getId());
- cache.addRevisioned(query, startupRevision);
- }
- managedUsers.put(userId, adapter);
- return adapter;
- } else {
- userId = query.getUsers().iterator().next();
- if (invalidations.contains(userId)) {
- return getDelegate().getUserByEmail(email, realm);
-
- }
- return getUserById(userId, realm);
- }
- }
-
- @Override
- public void close() {
- if (delegate != null) delegate.close();
- }
-
- @Override
- public UserModel getUserByFederatedIdentity(FederatedIdentityModel socialLink, RealmModel realm) {
- if (socialLink == null) return null;
- if (!realm.isIdentityFederationEnabled()) return null;
-
- if (realmInvalidations.contains(realm.getId())) {
- return getDelegate().getUserByFederatedIdentity(socialLink, realm);
- }
- String cacheKey = getUserByFederatedIdentityCacheKey(realm.getId(), socialLink);
- if (invalidations.contains(cacheKey)) {
- return getDelegate().getUserByFederatedIdentity(socialLink, realm);
- }
- UserListQuery query = cache.get(cacheKey, UserListQuery.class);
-
- String userId = null;
- if (query == null) {
- Long loaded = cache.getCurrentRevision(cacheKey);
- UserModel model = getDelegate().getUserByFederatedIdentity(socialLink, realm);
- if (model == null) return null;
- userId = model.getId();
- if (invalidations.contains(userId)) return model;
- if (managedUsers.containsKey(userId)) return managedUsers.get(userId);
-
- UserModel adapter = getUserAdapter(realm, userId, loaded, model);
- if (adapter instanceof UserAdapter) {
- query = new UserListQuery(loaded, cacheKey, realm, model.getId());
- cache.addRevisioned(query, startupRevision);
- }
-
- managedUsers.put(userId, adapter);
- return adapter;
- } else {
- userId = query.getUsers().iterator().next();
- if (invalidations.contains(userId)) {
- invalidations.add(cacheKey);
- return getDelegate().getUserByFederatedIdentity(socialLink, realm);
-
- }
- return getUserById(userId, realm);
- }
- }
-
- @Override
- public List<UserModel> getGroupMembers(RealmModel realm, GroupModel group, int firstResult, int maxResults) {
- return getDelegate().getGroupMembers(realm, group, firstResult, maxResults);
- }
-
- @Override
- public List<UserModel> getGroupMembers(RealmModel realm, GroupModel group) {
- return getDelegate().getGroupMembers(realm, group);
- }
-
- @Override
- public List<UserModel> getRoleMembers(RealmModel realm, RoleModel role, int firstResult, int maxResults) {
- return getDelegate().getRoleMembers(realm, role, firstResult, maxResults);
- }
-
- @Override
- public List<UserModel> getRoleMembers(RealmModel realm, RoleModel role) {
- return getDelegate().getRoleMembers(realm, role);
- }
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.models.cache.infinispan;
+
+// import org.jboss.logging.Logger;
+// import org.keycloak.cluster.ClusterProvider;
+// import org.keycloak.models.ClientScopeModel;
+// // import org.keycloak.models.cache.CachedObject;
+// import org.keycloak.models.cache.infinispan.events.InvalidationEvent;
+// import org.keycloak.common.constants.ServiceAccountConstants;
+// import org.keycloak.common.util.Time;
+// import org.keycloak.component.ComponentModel;
+// import org.keycloak.models.ClientModel;
+// import org.keycloak.models.FederatedIdentityModel;
+// import org.keycloak.models.GroupModel;
+// import org.keycloak.models.KeycloakSession;
+// import org.keycloak.models.KeycloakTransaction;
+// import org.keycloak.models.ProtocolMapperModel;
+// import org.keycloak.models.RealmModel;
+// import org.keycloak.models.RoleModel;
+// import org.keycloak.models.UserConsentModel;
+// import org.keycloak.models.UserModel;
+// import org.keycloak.models.UserProvider;
+// import org.keycloak.models.cache.CachedUserModel;
+// import org.keycloak.models.cache.OnUserCache;
+// import org.keycloak.models.cache.UserCache;
+// import org.keycloak.models.cache.infinispan.entities.CachedFederatedIdentityLinks;
+// import org.keycloak.models.cache.infinispan.entities.CachedUser;
+// import org.keycloak.models.cache.infinispan.entities.CachedUserConsent;
+// import org.keycloak.models.cache.infinispan.entities.CachedUserConsents;
+// import org.keycloak.models.cache.infinispan.entities.UserListQuery;
+// import org.keycloak.models.cache.infinispan.events.UserCacheRealmInvalidationEvent;
+// import org.keycloak.models.cache.infinispan.events.UserConsentsUpdatedEvent;
+// import org.keycloak.models.cache.infinispan.events.UserFederationLinkRemovedEvent;
+// import org.keycloak.models.cache.infinispan.events.UserFederationLinkUpdatedEvent;
+// import org.keycloak.models.cache.infinispan.events.UserFullInvalidationEvent;
+// import org.keycloak.models.cache.infinispan.events.UserUpdatedEvent;
+// import org.keycloak.models.utils.KeycloakModelUtils;
+// import org.keycloak.models.utils.ReadOnlyUserModelDelegate;
+// import org.keycloak.storage.CacheableStorageProviderModel;
+// import org.keycloak.storage.StorageId;
+// import org.keycloak.storage.UserStorageProvider;
+// import org.keycloak.storage.UserStorageProviderModel;
+// import org.keycloak.storage.client.ClientStorageProvider;
+
+// import java.util.Calendar;
+// import java.util.HashMap;
+// import java.util.HashSet;
+// import java.util.LinkedList;
+// import java.util.List;
+// import java.util.Map;
+// import java.util.Set;
+
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public class UserCacheSession implements UserCache {
+// protected static final Logger logger = Logger.getLogger(UserCacheSession.class);
+// protected UserCacheManager cache;
+// protected KeycloakSession session;
+// protected UserProvider delegate;
+// protected boolean transactionActive;
+// protected boolean setRollbackOnly;
+// protected final long startupRevision;
+
+
+// protected Set<String> invalidations = new HashSet<>();
+// protected Set<String> realmInvalidations = new HashSet<>();
+// protected Set<InvalidationEvent> invalidationEvents = new HashSet<>(); // Events to be sent across cluster
+// protected Map<String, UserModel> managedUsers = new HashMap<>();
+
+// public UserCacheSession(UserCacheManager cache, KeycloakSession session) {
+// this.cache = cache;
+// this.session = session;
+// this.startupRevision = cache.getCurrentCounter();
+// session.getTransactionManager().enlistAfterCompletion(getTransaction());
+// }
+
+// @Override
+// public void clear() {
+// cache.clear();
+// ClusterProvider cluster = session.getProvider(ClusterProvider.class);
+// cluster.notify(InfinispanUserCacheProviderFactory.USER_CLEAR_CACHE_EVENTS, new ClearCacheEvent(), true, ClusterProvider.DCNotify.ALL_DCS);
+// }
+
+// public UserProvider getDelegate() {
+// if (!transactionActive) throw new IllegalStateException("Cannot access delegate without a transaction");
+// if (delegate != null) return delegate;
+// delegate = session.userStorageManager();
+
+// return delegate;
+// }
+
+// public void registerUserInvalidation(RealmModel realm,CachedUser user) {
+// cache.userUpdatedInvalidations(user.getId(), user.getUsername(), user.getEmail(), user.getRealm(), invalidations);
+// invalidationEvents.add(UserUpdatedEvent.create(user.getId(), user.getUsername(), user.getEmail(), user.getRealm()));
+// }
+
+// @Override
+// public void evict(RealmModel realm, UserModel user) {
+// if (!transactionActive) throw new IllegalStateException("Cannot call evict() without a transaction");
+// getDelegate(); // invalidations need delegate set
+// if (user instanceof CachedUserModel) {
+// ((CachedUserModel)user).invalidate();
+// } else {
+// cache.userUpdatedInvalidations(user.getId(), user.getUsername(), user.getEmail(), realm.getId(), invalidations);
+// invalidationEvents.add(UserUpdatedEvent.create(user.getId(), user.getUsername(), user.getEmail(), realm.getId()));
+// }
+// }
+
+// @Override
+// public void evict(RealmModel realm) {
+// addRealmInvalidation(realm.getId());
+// }
+
+// protected void runInvalidations() {
+// for (String realmId : realmInvalidations) {
+// cache.invalidateRealmUsers(realmId, invalidations);
+// }
+// for (String invalidation : invalidations) {
+// cache.invalidateObject(invalidation);
+// }
+
+// cache.sendInvalidationEvents(session, invalidationEvents, InfinispanUserCacheProviderFactory.USER_INVALIDATION_EVENTS);
+// }
+
+// private KeycloakTransaction getTransaction() {
+// return new KeycloakTransaction() {
+// @Override
+// public void begin() {
+// transactionActive = true;
+// }
+
+// @Override
+// public void commit() {
+// runInvalidations();
+// transactionActive = false;
+// }
+
+// @Override
+// public void rollback() {
+// setRollbackOnly = true;
+// runInvalidations();
+// transactionActive = false;
+// }
+
+// @Override
+// public void setRollbackOnly() {
+// setRollbackOnly = true;
+// }
+
+// @Override
+// public boolean getRollbackOnly() {
+// return setRollbackOnly;
+// }
+
+// @Override
+// public boolean isActive() {
+// return transactionActive;
+// }
+// };
+// }
+
+// private boolean isRegisteredForInvalidation(RealmModel realm, String userId) {
+// return realmInvalidations.contains(realm.getId()) || invalidations.contains(userId);
+// }
+
+// @Override
+// public UserModel getUserById(String id, RealmModel realm) {
+// logger.tracev("getuserById {0}", id);
+// if (isRegisteredForInvalidation(realm, id)) {
+// logger.trace("registered for invalidation return delegate");
+// return getDelegate().getUserById(id, realm);
+// }
+// if (managedUsers.containsKey(id)) {
+// logger.trace("return managedusers");
+// return managedUsers.get(id);
+// }
+
+// CachedUser cached = cache.get(id, CachedUser.class);
+// UserModel adapter = null;
+// if (cached == null) {
+// logger.trace("not cached");
+// Long loaded = cache.getCurrentRevision(id);
+// UserModel delegate = getDelegate().getUserById(id, realm);
+// if (delegate == null) {
+// logger.trace("delegate returning null");
+// return null;
+// }
+// adapter = cacheUser(realm, delegate, loaded);
+// } else {
+// adapter = validateCache(realm, cached);
+// }
+// managedUsers.put(id, adapter);
+// return adapter;
+// }
+
+// static String getUserByUsernameCacheKey(String realmId, String username) {
+// return realmId + ".username." + username;
+// }
+
+// static String getUserByEmailCacheKey(String realmId, String email) {
+// return realmId + ".email." + email;
+// }
+
+// private static String getUserByFederatedIdentityCacheKey(String realmId, FederatedIdentityModel socialLink) {
+// return getUserByFederatedIdentityCacheKey(realmId, socialLink.getIdentityProvider(), socialLink.getUserId());
+// }
+
+// static String getUserByFederatedIdentityCacheKey(String realmId, String identityProvider, String socialUserId) {
+// return realmId + ".idp." + identityProvider + "." + socialUserId;
+// }
+
+// static String getFederatedIdentityLinksCacheKey(String userId) {
+// return userId + ".idplinks";
+// }
+
+// @Override
+// public UserModel getUserByUsername(String username, RealmModel realm) {
+// logger.tracev("getUserByUsername: {0}", username);
+// username = username.toLowerCase();
+// if (realmInvalidations.contains(realm.getId())) {
+// logger.tracev("realmInvalidations");
+// return getDelegate().getUserByUsername(username, realm);
+// }
+// String cacheKey = getUserByUsernameCacheKey(realm.getId(), username);
+// if (invalidations.contains(cacheKey)) {
+// logger.tracev("invalidations");
+// return getDelegate().getUserByUsername(username, realm);
+// }
+// UserListQuery query = cache.get(cacheKey, UserListQuery.class);
+
+// String userId = null;
+// if (query == null) {
+// logger.tracev("query null");
+// Long loaded = cache.getCurrentRevision(cacheKey);
+// UserModel model = getDelegate().getUserByUsername(username, realm);
+// if (model == null) {
+// logger.tracev("model from delegate null");
+// return null;
+// }
+// userId = model.getId();
+// if (invalidations.contains(userId)) return model;
+// if (managedUsers.containsKey(userId)) {
+// logger.tracev("return managed user");
+// return managedUsers.get(userId);
+// }
+
+// UserModel adapter = getUserAdapter(realm, userId, loaded, model);
+// if (adapter instanceof UserAdapter) { // this was cached, so we can cache query too
+// query = new UserListQuery(loaded, cacheKey, realm, model.getId());
+// cache.addRevisioned(query, startupRevision);
+// }
+// managedUsers.put(userId, adapter);
+// return adapter;
+// } else {
+// userId = query.getUsers().iterator().next();
+// if (invalidations.contains(userId)) {
+// logger.tracev("invalidated cache return delegate");
+// return getDelegate().getUserByUsername(username, realm);
+
+// }
+// logger.trace("return getUserById");
+// return getUserById(userId, realm);
+// }
+// }
+
+// // protected UserModel getUserAdapter(RealmModel realm, String userId, Long loaded, UserModel delegate) {
+// // CachedUser cached = cache.get(userId, CachedUser.class);
+// // if (cached == null) {
+// // return cacheUser(realm, delegate, loaded);
+// // } else {
+// // return validateCache(realm, cached);
+// // }
+// // }
+
+// // protected UserModel validateCache(RealmModel realm, CachedUser cached) {
+// // if (!realm.getId().equals(cached.getRealm())) {
+// // return null;
+// // }
+
+// // StorageId storageId = cached.getFederationLink() != null ?
+// // new StorageId(cached.getFederationLink(), cached.getId()) : new StorageId(cached.getId());
+
+// // if (!storageId.isLocal()) {
+// // ComponentModel component = realm.getComponent(storageId.getProviderId());
+// // CacheableStorageProviderModel model = new CacheableStorageProviderModel(component);
+
+// // // although we do set a timeout, Infinispan has no guarantees when the user will be evicted
+// // // its also hard to test stuff
+// // if (model.shouldInvalidate(cached)) {
+// // registerUserInvalidation(realm, cached);
+// // return getDelegate().getUserById(cached.getId(), realm);
+// // }
+// // }
+// // return new UserAdapter(cached, this, session, realm);
+// // }
+
+// protected UserModel cacheUser(RealmModel realm, UserModel delegate, Long revision) {
+// int notBefore = getDelegate().getNotBeforeOfUser(realm, delegate);
+
+// StorageId storageId = delegate.getFederationLink() != null ?
+// new StorageId(delegate.getFederationLink(), delegate.getId()) : new StorageId(delegate.getId());
+// CachedUser cached = null;
+// UserAdapter adapter = null;
+
+// if (!storageId.isLocal()) {
+// ComponentModel component = realm.getComponent(storageId.getProviderId());
+// UserStorageProviderModel model = new UserStorageProviderModel(component);
+// if (!model.isEnabled()) {
+// return new ReadOnlyUserModelDelegate(delegate) {
+// @Override
+// public boolean isEnabled() {
+// return false;
+// }
+// };
+// }
+// UserStorageProviderModel.CachePolicy policy = model.getCachePolicy();
+// if (policy != null && policy == UserStorageProviderModel.CachePolicy.NO_CACHE) {
+// return delegate;
+// }
+
+// cached = new CachedUser(revision, realm, delegate, notBefore);
+// adapter = new UserAdapter(cached, this, session, realm);
+// onCache(realm, adapter, delegate);
+
+// long lifespan = model.getLifespan();
+// if (lifespan > 0) {
+// cache.addRevisioned(cached, startupRevision, lifespan);
+// } else {
+// cache.addRevisioned(cached, startupRevision);
+// }
+// } else {
+// cached = new CachedUser(revision, realm, delegate, notBefore);
+// adapter = new UserAdapter(cached, this, session, realm);
+// onCache(realm, adapter, delegate);
+// cache.addRevisioned(cached, startupRevision);
+// }
+
+// return adapter;
+// }
+
+// private void onCache(RealmModel realm, UserAdapter adapter, UserModel delegate) {
+// ((OnUserCache)getDelegate()).onCache(realm, adapter, delegate);
+// ((OnUserCache)session.userCredentialManager()).onCache(realm, adapter, delegate);
+// }
+
+// @Override
+// public UserModel getUserByEmail(String email, RealmModel realm) {
+// if (email == null) return null;
+// email = email.toLowerCase();
+// if (realmInvalidations.contains(realm.getId())) {
+// return getDelegate().getUserByEmail(email, realm);
+// }
+// String cacheKey = getUserByEmailCacheKey(realm.getId(), email);
+// if (invalidations.contains(cacheKey)) {
+// return getDelegate().getUserByEmail(email, realm);
+// }
+// UserListQuery query = cache.get(cacheKey, UserListQuery.class);
+
+// String userId = null;
+// if (query == null) {
+// Long loaded = cache.getCurrentRevision(cacheKey);
+// UserModel model = getDelegate().getUserByEmail(email, realm);
+// if (model == null) return null;
+// userId = model.getId();
+// if (invalidations.contains(userId)) return model;
+// if (managedUsers.containsKey(userId)) return managedUsers.get(userId);
+
+// UserModel adapter = getUserAdapter(realm, userId, loaded, model);
+// if (adapter instanceof UserAdapter) {
+// query = new UserListQuery(loaded, cacheKey, realm, model.getId());
+// cache.addRevisioned(query, startupRevision);
+// }
+// managedUsers.put(userId, adapter);
+// return adapter;
+// } else {
+// userId = query.getUsers().iterator().next();
+// if (invalidations.contains(userId)) {
+// return getDelegate().getUserByEmail(email, realm);
+
+// }
+// return getUserById(userId, realm);
+// }
+// }
+
+// @Override
+// public void close() {
+// if (delegate != null) delegate.close();
+// }
+
+// @Override
+// public UserModel getUserByFederatedIdentity(FederatedIdentityModel socialLink, RealmModel realm) {
+// if (socialLink == null) return null;
+// if (!realm.isIdentityFederationEnabled()) return null;
+
+// if (realmInvalidations.contains(realm.getId())) {
+// return getDelegate().getUserByFederatedIdentity(socialLink, realm);
+// }
+// String cacheKey = getUserByFederatedIdentityCacheKey(realm.getId(), socialLink);
+// if (invalidations.contains(cacheKey)) {
+// return getDelegate().getUserByFederatedIdentity(socialLink, realm);
+// }
+// UserListQuery query = cache.get(cacheKey, UserListQuery.class);
+
+// String userId = null;
+// if (query == null) {
+// Long loaded = cache.getCurrentRevision(cacheKey);
+// UserModel model = getDelegate().getUserByFederatedIdentity(socialLink, realm);
+// if (model == null) return null;
+// userId = model.getId();
+// if (invalidations.contains(userId)) return model;
+// if (managedUsers.containsKey(userId)) return managedUsers.get(userId);
+
+// UserModel adapter = getUserAdapter(realm, userId, loaded, model);
+// if (adapter instanceof UserAdapter) {
+// query = new UserListQuery(loaded, cacheKey, realm, model.getId());
+// cache.addRevisioned(query, startupRevision);
+// }
+
+// managedUsers.put(userId, adapter);
+// return adapter;
+// } else {
+// userId = query.getUsers().iterator().next();
+// if (invalidations.contains(userId)) {
+// invalidations.add(cacheKey);
+// return getDelegate().getUserByFederatedIdentity(socialLink, realm);
+
+// }
+// return getUserById(userId, realm);
+// }
+// }
+
+// @Override
+// public List<UserModel> getGroupMembers(RealmModel realm, GroupModel group, int firstResult, int maxResults) {
+// return getDelegate().getGroupMembers(realm, group, firstResult, maxResults);
+// }
+
+// @Override
+// public List<UserModel> getGroupMembers(RealmModel realm, GroupModel group) {
+// return getDelegate().getGroupMembers(realm, group);
+// }
+
+// @Override
+// public List<UserModel> getRoleMembers(RealmModel realm, RoleModel role, int firstResult, int maxResults) {
+// return getDelegate().getRoleMembers(realm, role, firstResult, maxResults);
+// }
+
+// @Override
+// public List<UserModel> getRoleMembers(RealmModel realm, RoleModel role) {
+// return getDelegate().getRoleMembers(realm, role);
+// }
- @Override
- public UserModel getServiceAccount(ClientModel client) {
- // Just an attempt to find the user from cache by default serviceAccount username
- UserModel user = findServiceAccount(client);
- if (user != null && user.getServiceAccountClientLink() != null && user.getServiceAccountClientLink().equals(client.getId())) {
- return user;
- }
-
- return getDelegate().getServiceAccount(client);
- }
-
- public UserModel findServiceAccount(ClientModel client) {
- String username = ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + client.getClientId();
- logger.tracev("getServiceAccount: {0}", username);
- username = username.toLowerCase();
- RealmModel realm = client.getRealm();
- if (realmInvalidations.contains(realm.getId())) {
- logger.tracev("realmInvalidations");
- return getDelegate().getServiceAccount(client);
- }
- String cacheKey = getUserByUsernameCacheKey(realm.getId(), username);
- if (invalidations.contains(cacheKey)) {
- logger.tracev("invalidations");
- return getDelegate().getServiceAccount(client);
- }
- UserListQuery query = cache.get(cacheKey, UserListQuery.class);
-
- String userId = null;
- if (query == null) {
- logger.tracev("query null");
- Long loaded = cache.getCurrentRevision(cacheKey);
- UserModel model = getDelegate().getServiceAccount(client);
- if (model == null) {
- logger.tracev("model from delegate null");
- return null;
- }
- userId = model.getId();
- if (invalidations.contains(userId)) return model;
- if (managedUsers.containsKey(userId)) {
- logger.tracev("return managed user");
- return managedUsers.get(userId);
- }
-
- UserModel adapter = getUserAdapter(realm, userId, loaded, model);
- if (adapter instanceof UserAdapter) { // this was cached, so we can cache query too
- query = new UserListQuery(loaded, cacheKey, realm, model.getId());
- cache.addRevisioned(query, startupRevision);
- }
- managedUsers.put(userId, adapter);
- return adapter;
- } else {
- userId = query.getUsers().iterator().next();
- if (invalidations.contains(userId)) {
- logger.tracev("invalidated cache return delegate");
- return getDelegate().getUserByUsername(username, realm);
-
- }
- logger.trace("return getUserById");
- return getUserById(userId, realm);
- }
- }
-
-
-
-
- @Override
- public List<UserModel> getUsers(RealmModel realm, boolean includeServiceAccounts) {
- return getDelegate().getUsers(realm, includeServiceAccounts);
- }
-
- @Override
- public int getUsersCount(RealmModel realm, boolean includeServiceAccount) {
- return getDelegate().getUsersCount(realm, includeServiceAccount);
- }
-
- @Override
- public int getUsersCount(RealmModel realm) {
- return getUsersCount(realm, false);
- }
-
- @Override
- public List<UserModel> getUsers(RealmModel realm, int firstResult, int maxResults, boolean includeServiceAccounts) {
- return getDelegate().getUsers(realm, firstResult, maxResults, includeServiceAccounts);
- }
-
- @Override
- public List<UserModel> getUsers(RealmModel realm) {
- return getUsers(realm, false);
- }
-
- @Override
- public List<UserModel> getUsers(RealmModel realm, int firstResult, int maxResults) {
- return getUsers(realm, firstResult, maxResults, false);
- }
-
- @Override
- public List<UserModel> searchForUser(String search, RealmModel realm) {
- return getDelegate().searchForUser(search, realm);
- }
-
- @Override
- public List<UserModel> searchForUser(String search, RealmModel realm, int firstResult, int maxResults) {
- return getDelegate().searchForUser(search, realm, firstResult, maxResults);
- }
-
- @Override
- public List<UserModel> searchForUser(Map<String, String> attributes, RealmModel realm) {
- return getDelegate().searchForUser(attributes, realm);
- }
-
- @Override
- public List<UserModel> searchForUser(Map<String, String> attributes, RealmModel realm, int firstResult, int maxResults) {
- return getDelegate().searchForUser(attributes, realm, firstResult, maxResults);
- }
-
- @Override
- public List<UserModel> searchForUserByUserAttribute(String attrName, String attrValue, RealmModel realm) {
- return getDelegate().searchForUserByUserAttribute(attrName, attrValue, realm);
- }
-
- @Override
- public Set<FederatedIdentityModel> getFederatedIdentities(UserModel user, RealmModel realm) {
- logger.tracev("getFederatedIdentities: {0}", user.getUsername());
-
- String cacheKey = getFederatedIdentityLinksCacheKey(user.getId());
- if (realmInvalidations.contains(realm.getId()) || invalidations.contains(user.getId()) || invalidations.contains(cacheKey)) {
- return getDelegate().getFederatedIdentities(user, realm);
- }
-
- CachedFederatedIdentityLinks cachedLinks = cache.get(cacheKey, CachedFederatedIdentityLinks.class);
-
- if (cachedLinks == null) {
- Long loaded = cache.getCurrentRevision(cacheKey);
- Set<FederatedIdentityModel> federatedIdentities = getDelegate().getFederatedIdentities(user, realm);
- cachedLinks = new CachedFederatedIdentityLinks(loaded, cacheKey, realm, federatedIdentities);
- cache.addRevisioned(cachedLinks, startupRevision);
- return federatedIdentities;
- } else {
- return new HashSet<>(cachedLinks.getFederatedIdentities());
- }
- }
-
- @Override
- public FederatedIdentityModel getFederatedIdentity(UserModel user, String socialProvider, RealmModel realm) {
- logger.tracev("getFederatedIdentity: {0} {1}", user.getUsername(), socialProvider);
-
- String cacheKey = getFederatedIdentityLinksCacheKey(user.getId());
- if (realmInvalidations.contains(realm.getId()) || invalidations.contains(user.getId()) || invalidations.contains(cacheKey)) {
- return getDelegate().getFederatedIdentity(user, socialProvider, realm);
- }
-
- Set<FederatedIdentityModel> federatedIdentities = getFederatedIdentities(user, realm);
- for (FederatedIdentityModel socialLink : federatedIdentities) {
- if (socialLink.getIdentityProvider().equals(socialProvider)) {
- return socialLink;
- }
- }
- return null;
- }
-
- @Override
- public void updateConsent(RealmModel realm, String userId, UserConsentModel consent) {
- invalidateConsent(userId);
- getDelegate().updateConsent(realm, userId, consent);
- }
-
- @Override
- public boolean revokeConsentForClient(RealmModel realm, String userId, String clientInternalId) {
- invalidateConsent(userId);
- return getDelegate().revokeConsentForClient(realm, userId, clientInternalId);
- }
-
- static String getConsentCacheKey(String userId) {
- return userId + ".consents";
- }
-
-
- @Override
- public void addConsent(RealmModel realm, String userId, UserConsentModel consent) {
- invalidateConsent(userId);
- getDelegate().addConsent(realm, userId, consent);
- }
-
- private void invalidateConsent(String userId) {
- cache.consentInvalidation(userId, invalidations);
- invalidationEvents.add(UserConsentsUpdatedEvent.create(userId));
- }
-
- @Override
- public UserConsentModel getConsentByClient(RealmModel realm, String userId, String clientId) {
- logger.tracev("getConsentByClient: {0}", userId);
-
- String cacheKey = getConsentCacheKey(userId);
- if (realmInvalidations.contains(realm.getId()) || invalidations.contains(userId) || invalidations.contains(cacheKey)) {
- return getDelegate().getConsentByClient(realm, userId, clientId);
- }
-
- CachedUserConsents cached = cache.get(cacheKey, CachedUserConsents.class);
-
- if (cached == null) {
- Long loaded = cache.getCurrentRevision(cacheKey);
- List<UserConsentModel> consents = getDelegate().getConsents(realm, userId);
- cached = new CachedUserConsents(loaded, cacheKey, realm, consents);
- cache.addRevisioned(cached, startupRevision);
- }
- CachedUserConsent cachedConsent = cached.getConsents().get(clientId);
- if (cachedConsent == null) return null;
- return toConsentModel(realm, cachedConsent);
- }
-
- @Override
- public List<UserConsentModel> getConsents(RealmModel realm, String userId) {
- logger.tracev("getConsents: {0}", userId);
-
- String cacheKey = getConsentCacheKey(userId);
- if (realmInvalidations.contains(realm.getId()) || invalidations.contains(userId) || invalidations.contains(cacheKey)) {
- return getDelegate().getConsents(realm, userId);
- }
-
- CachedUserConsents cached = cache.get(cacheKey, CachedUserConsents.class);
-
- if (cached == null) {
- Long loaded = cache.getCurrentRevision(cacheKey);
- List<UserConsentModel> consents = getDelegate().getConsents(realm, userId);
- cached = new CachedUserConsents(loaded, cacheKey, realm, consents);
- cache.addRevisioned(cached, startupRevision);
- return consents;
- } else {
- List<UserConsentModel> result = new LinkedList<>();
- for (CachedUserConsent cachedConsent : cached.getConsents().values()) {
- UserConsentModel consent = toConsentModel(realm, cachedConsent);
- if (consent != null) {
- result.add(consent);
- }
- }
- return result;
- }
- }
-
- private UserConsentModel toConsentModel(RealmModel realm, CachedUserConsent cachedConsent) {
- ClientModel client = session.realms().getClientById(cachedConsent.getClientDbId(), realm);
- if (client == null) {
- return null;
- }
-
- UserConsentModel consentModel = new UserConsentModel(client);
- consentModel.setCreatedDate(cachedConsent.getCreatedDate());
- consentModel.setLastUpdatedDate(cachedConsent.getLastUpdatedDate());
-
- for (String clientScopeId : cachedConsent.getClientScopeIds()) {
- ClientScopeModel clientScope = KeycloakModelUtils.findClientScopeById(realm, client, clientScopeId);
- if (clientScope != null) {
- consentModel.addGrantedClientScope(clientScope);
- }
- }
-
- return consentModel;
- }
-
- @Override
- public void setNotBeforeForUser(RealmModel realm, UserModel user, int notBefore) {
- if (!isRegisteredForInvalidation(realm, user.getId())) {
- UserModel foundUser = getUserById(user.getId(), realm);
- if (foundUser instanceof UserAdapter) {
- ((UserAdapter) foundUser).invalidate();
- }
- }
-
- getDelegate().setNotBeforeForUser(realm, user, notBefore);
-
- }
-
- @Override
- public int getNotBeforeOfUser(RealmModel realm, UserModel user) {
- if (isRegisteredForInvalidation(realm, user.getId())) {
- return getDelegate().getNotBeforeOfUser(realm, user);
- }
-
- UserModel foundUser = getUserById(user.getId(), realm);
- if (foundUser instanceof UserAdapter) {
- return ((UserAdapter) foundUser).cached.getNotBefore();
- } else {
- return getDelegate().getNotBeforeOfUser(realm, user);
- }
- }
-
- @Override
- public UserModel addUser(RealmModel realm, String id, String username, boolean addDefaultRoles, boolean addDefaultRequiredActions) {
- UserModel user = getDelegate().addUser(realm, id, username, addDefaultRoles, addDefaultRoles);
- // just in case the transaction is rolled back you need to invalidate the user and all cache queries for that user
- fullyInvalidateUser(realm, user);
- managedUsers.put(user.getId(), user);
- return user;
- }
-
- @Override
- public UserModel addUser(RealmModel realm, String username) {
- UserModel user = getDelegate().addUser(realm, username);
- // just in case the transaction is rolled back you need to invalidate the user and all cache queries for that user
- fullyInvalidateUser(realm, user);
- managedUsers.put(user.getId(), user);
- return user;
- }
-
- // just in case the transaction is rolled back you need to invalidate the user and all cache queries for that user
- protected void fullyInvalidateUser(RealmModel realm, UserModel user) {
- Set<FederatedIdentityModel> federatedIdentities = realm.isIdentityFederationEnabled() ? getFederatedIdentities(user, realm) : null;
-
- UserFullInvalidationEvent event = UserFullInvalidationEvent.create(user.getId(), user.getUsername(), user.getEmail(), realm.getId(), realm.isIdentityFederationEnabled(), federatedIdentities);
-
- cache.fullUserInvalidation(user.getId(), user.getUsername(), user.getEmail(), realm.getId(), realm.isIdentityFederationEnabled(), event.getFederatedIdentities(), invalidations);
- invalidationEvents.add(event);
- }
-
- @Override
- public boolean removeUser(RealmModel realm, UserModel user) {
- fullyInvalidateUser(realm, user);
- return getDelegate().removeUser(realm, user);
- }
-
- @Override
- public void addFederatedIdentity(RealmModel realm, UserModel user, FederatedIdentityModel socialLink) {
- invalidateFederationLink(user.getId());
- getDelegate().addFederatedIdentity(realm, user, socialLink);
- }
-
- @Override
- public void updateFederatedIdentity(RealmModel realm, UserModel federatedUser, FederatedIdentityModel federatedIdentityModel) {
- invalidateFederationLink(federatedUser.getId());
- getDelegate().updateFederatedIdentity(realm, federatedUser, federatedIdentityModel);
- }
-
- private void invalidateFederationLink(String userId) {
- cache.federatedIdentityLinkUpdatedInvalidation(userId, invalidations);
- invalidationEvents.add(UserFederationLinkUpdatedEvent.create(userId));
- }
-
- @Override
- public boolean removeFederatedIdentity(RealmModel realm, UserModel user, String socialProvider) {
- // Needs to invalidate both directions
- FederatedIdentityModel socialLink = getFederatedIdentity(user, socialProvider, realm);
-
- UserFederationLinkRemovedEvent event = UserFederationLinkRemovedEvent.create(user.getId(), realm.getId(), socialLink);
- cache.federatedIdentityLinkRemovedInvalidation(user.getId(), realm.getId(), event.getIdentityProviderId(), event.getSocialUserId(), invalidations);
- invalidationEvents.add(event);
-
- return getDelegate().removeFederatedIdentity(realm, user, socialProvider);
- }
-
- @Override
- public void grantToAllUsers(RealmModel realm, RoleModel role) {
- addRealmInvalidation(realm.getId()); // easier to just invalidate whole realm
- getDelegate().grantToAllUsers(realm, role);
- }
-
- @Override
- public void preRemove(RealmModel realm) {
- addRealmInvalidation(realm.getId());
- getDelegate().preRemove(realm);
- }
-
- @Override
- public void preRemove(RealmModel realm, RoleModel role) {
- addRealmInvalidation(realm.getId()); // easier to just invalidate whole realm
- getDelegate().preRemove(realm, role);
- }
- @Override
- public void preRemove(RealmModel realm, GroupModel group) {
- addRealmInvalidation(realm.getId()); // easier to just invalidate whole realm
- getDelegate().preRemove(realm, group);
- }
-
-
- @Override
- public void preRemove(RealmModel realm, ClientModel client) {
- addRealmInvalidation(realm.getId()); // easier to just invalidate whole realm
- getDelegate().preRemove(realm, client);
- }
-
- @Override
- public void preRemove(ProtocolMapperModel protocolMapper) {
- getDelegate().preRemove(protocolMapper);
- }
-
- @Override
- public void preRemove(ClientScopeModel clientScope) {
- // Not needed to invalidate realm probably. Just consents are affected ATM and they are checked if they exists
- getDelegate().preRemove(clientScope);
- }
-
- @Override
- public void preRemove(RealmModel realm, ComponentModel component) {
- if (!component.getProviderType().equals(UserStorageProvider.class.getName()) && !component.getProviderType().equals(ClientStorageProvider.class.getName())) return;
- addRealmInvalidation(realm.getId()); // easier to just invalidate whole realm
- getDelegate().preRemove(realm, component);
-
- }
-
- @Override
- public void removeImportedUsers(RealmModel realm, String storageProviderId) {
- getDelegate().removeImportedUsers(realm, storageProviderId);
- clear();
- addRealmInvalidation(realm.getId()); // easier to just invalidate whole realm
- }
-
- @Override
- public void unlinkUsers(RealmModel realm, String storageProviderId) {
- getDelegate().unlinkUsers(realm, storageProviderId);
- clear();
- addRealmInvalidation(realm.getId()); // easier to just invalidate whole realm
-
- }
-
- private void addRealmInvalidation(String realmId) {
- realmInvalidations.add(realmId);
- invalidationEvents.add(UserCacheRealmInvalidationEvent.create(realmId));
- }
-
-}
+// @Override
+// public UserModel getServiceAccount(ClientModel client) {
+// // Just an attempt to find the user from cache by default serviceAccount username
+// UserModel user = findServiceAccount(client);
+// if (user != null && user.getServiceAccountClientLink() != null && user.getServiceAccountClientLink().equals(client.getId())) {
+// return user;
+// }
+
+// return getDelegate().getServiceAccount(client);
+// }
+
+// public UserModel findServiceAccount(ClientModel client) {
+// String username = ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + client.getClientId();
+// logger.tracev("getServiceAccount: {0}", username);
+// username = username.toLowerCase();
+// RealmModel realm = client.getRealm();
+// if (realmInvalidations.contains(realm.getId())) {
+// logger.tracev("realmInvalidations");
+// return getDelegate().getServiceAccount(client);
+// }
+// String cacheKey = getUserByUsernameCacheKey(realm.getId(), username);
+// if (invalidations.contains(cacheKey)) {
+// logger.tracev("invalidations");
+// return getDelegate().getServiceAccount(client);
+// }
+// UserListQuery query = cache.get(cacheKey, UserListQuery.class);
+
+// String userId = null;
+// if (query == null) {
+// logger.tracev("query null");
+// Long loaded = cache.getCurrentRevision(cacheKey);
+// UserModel model = getDelegate().getServiceAccount(client);
+// if (model == null) {
+// logger.tracev("model from delegate null");
+// return null;
+// }
+// userId = model.getId();
+// if (invalidations.contains(userId)) return model;
+// if (managedUsers.containsKey(userId)) {
+// logger.tracev("return managed user");
+// return managedUsers.get(userId);
+// }
+
+// UserModel adapter = getUserAdapter(realm, userId, loaded, model);
+// if (adapter instanceof UserAdapter) { // this was cached, so we can cache query too
+// query = new UserListQuery(loaded, cacheKey, realm, model.getId());
+// cache.addRevisioned(query, startupRevision);
+// }
+// managedUsers.put(userId, adapter);
+// return adapter;
+// } else {
+// userId = query.getUsers().iterator().next();
+// if (invalidations.contains(userId)) {
+// logger.tracev("invalidated cache return delegate");
+// return getDelegate().getUserByUsername(username, realm);
+
+// }
+// logger.trace("return getUserById");
+// return getUserById(userId, realm);
+// }
+// }
+
+
+
+
+// @Override
+// public List<UserModel> getUsers(RealmModel realm, boolean includeServiceAccounts) {
+// return getDelegate().getUsers(realm, includeServiceAccounts);
+// }
+
+// @Override
+// public int getUsersCount(RealmModel realm, boolean includeServiceAccount) {
+// return getDelegate().getUsersCount(realm, includeServiceAccount);
+// }
+
+// @Override
+// public int getUsersCount(RealmModel realm) {
+// return getUsersCount(realm, false);
+// }
+
+// @Override
+// public List<UserModel> getUsers(RealmModel realm, int firstResult, int maxResults, boolean includeServiceAccounts) {
+// return getDelegate().getUsers(realm, firstResult, maxResults, includeServiceAccounts);
+// }
+
+// @Override
+// public List<UserModel> getUsers(RealmModel realm) {
+// return getUsers(realm, false);
+// }
+
+// @Override
+// public List<UserModel> getUsers(RealmModel realm, int firstResult, int maxResults) {
+// return getUsers(realm, firstResult, maxResults, false);
+// }
+
+// @Override
+// public List<UserModel> searchForUser(String search, RealmModel realm) {
+// return getDelegate().searchForUser(search, realm);
+// }
+
+// @Override
+// public List<UserModel> searchForUser(String search, RealmModel realm, int firstResult, int maxResults) {
+// return getDelegate().searchForUser(search, realm, firstResult, maxResults);
+// }
+
+// @Override
+// public List<UserModel> searchForUser(Map<String, String> attributes, RealmModel realm) {
+// return getDelegate().searchForUser(attributes, realm);
+// }
+
+// @Override
+// public List<UserModel> searchForUser(Map<String, String> attributes, RealmModel realm, int firstResult, int maxResults) {
+// return getDelegate().searchForUser(attributes, realm, firstResult, maxResults);
+// }
+
+// @Override
+// public List<UserModel> searchForUserByUserAttribute(String attrName, String attrValue, RealmModel realm) {
+// return getDelegate().searchForUserByUserAttribute(attrName, attrValue, realm);
+// }
+
+// @Override
+// public Set<FederatedIdentityModel> getFederatedIdentities(UserModel user, RealmModel realm) {
+// logger.tracev("getFederatedIdentities: {0}", user.getUsername());
+
+// String cacheKey = getFederatedIdentityLinksCacheKey(user.getId());
+// if (realmInvalidations.contains(realm.getId()) || invalidations.contains(user.getId()) || invalidations.contains(cacheKey)) {
+// return getDelegate().getFederatedIdentities(user, realm);
+// }
+
+// CachedFederatedIdentityLinks cachedLinks = cache.get(cacheKey, CachedFederatedIdentityLinks.class);
+
+// if (cachedLinks == null) {
+// Long loaded = cache.getCurrentRevision(cacheKey);
+// Set<FederatedIdentityModel> federatedIdentities = getDelegate().getFederatedIdentities(user, realm);
+// cachedLinks = new CachedFederatedIdentityLinks(loaded, cacheKey, realm, federatedIdentities);
+// cache.addRevisioned(cachedLinks, startupRevision);
+// return federatedIdentities;
+// } else {
+// return new HashSet<>(cachedLinks.getFederatedIdentities());
+// }
+// }
+
+// @Override
+// public FederatedIdentityModel getFederatedIdentity(UserModel user, String socialProvider, RealmModel realm) {
+// logger.tracev("getFederatedIdentity: {0} {1}", user.getUsername(), socialProvider);
+
+// String cacheKey = getFederatedIdentityLinksCacheKey(user.getId());
+// if (realmInvalidations.contains(realm.getId()) || invalidations.contains(user.getId()) || invalidations.contains(cacheKey)) {
+// return getDelegate().getFederatedIdentity(user, socialProvider, realm);
+// }
+
+// Set<FederatedIdentityModel> federatedIdentities = getFederatedIdentities(user, realm);
+// for (FederatedIdentityModel socialLink : federatedIdentities) {
+// if (socialLink.getIdentityProvider().equals(socialProvider)) {
+// return socialLink;
+// }
+// }
+// return null;
+// }
+
+// @Override
+// public void updateConsent(RealmModel realm, String userId, UserConsentModel consent) {
+// invalidateConsent(userId);
+// getDelegate().updateConsent(realm, userId, consent);
+// }
+
+// @Override
+// public boolean revokeConsentForClient(RealmModel realm, String userId, String clientInternalId) {
+// invalidateConsent(userId);
+// return getDelegate().revokeConsentForClient(realm, userId, clientInternalId);
+// }
+
+// static String getConsentCacheKey(String userId) {
+// return userId + ".consents";
+// }
+
+
+// @Override
+// public void addConsent(RealmModel realm, String userId, UserConsentModel consent) {
+// invalidateConsent(userId);
+// getDelegate().addConsent(realm, userId, consent);
+// }
+
+// private void invalidateConsent(String userId) {
+// cache.consentInvalidation(userId, invalidations);
+// invalidationEvents.add(UserConsentsUpdatedEvent.create(userId));
+// }
+
+// @Override
+// public UserConsentModel getConsentByClient(RealmModel realm, String userId, String clientId) {
+// logger.tracev("getConsentByClient: {0}", userId);
+
+// String cacheKey = getConsentCacheKey(userId);
+// if (realmInvalidations.contains(realm.getId()) || invalidations.contains(userId) || invalidations.contains(cacheKey)) {
+// return getDelegate().getConsentByClient(realm, userId, clientId);
+// }
+
+// CachedUserConsents cached = cache.get(cacheKey, CachedUserConsents.class);
+
+// if (cached == null) {
+// Long loaded = cache.getCurrentRevision(cacheKey);
+// List<UserConsentModel> consents = getDelegate().getConsents(realm, userId);
+// cached = new CachedUserConsents(loaded, cacheKey, realm, consents);
+// cache.addRevisioned(cached, startupRevision);
+// }
+// CachedUserConsent cachedConsent = cached.getConsents().get(clientId);
+// if (cachedConsent == null) return null;
+// return toConsentModel(realm, cachedConsent);
+// }
+
+// @Override
+// public List<UserConsentModel> getConsents(RealmModel realm, String userId) {
+// logger.tracev("getConsents: {0}", userId);
+
+// String cacheKey = getConsentCacheKey(userId);
+// if (realmInvalidations.contains(realm.getId()) || invalidations.contains(userId) || invalidations.contains(cacheKey)) {
+// return getDelegate().getConsents(realm, userId);
+// }
+
+// CachedUserConsents cached = cache.get(cacheKey, CachedUserConsents.class);
+
+// if (cached == null) {
+// Long loaded = cache.getCurrentRevision(cacheKey);
+// List<UserConsentModel> consents = getDelegate().getConsents(realm, userId);
+// cached = new CachedUserConsents(loaded, cacheKey, realm, consents);
+// cache.addRevisioned(cached, startupRevision);
+// return consents;
+// } else {
+// List<UserConsentModel> result = new LinkedList<>();
+// for (CachedUserConsent cachedConsent : cached.getConsents().values()) {
+// UserConsentModel consent = toConsentModel(realm, cachedConsent);
+// if (consent != null) {
+// result.add(consent);
+// }
+// }
+// return result;
+// }
+// }
+
+// private UserConsentModel toConsentModel(RealmModel realm, CachedUserConsent cachedConsent) {
+// ClientModel client = session.realms().getClientById(cachedConsent.getClientDbId(), realm);
+// if (client == null) {
+// return null;
+// }
+
+// UserConsentModel consentModel = new UserConsentModel(client);
+// consentModel.setCreatedDate(cachedConsent.getCreatedDate());
+// consentModel.setLastUpdatedDate(cachedConsent.getLastUpdatedDate());
+
+// for (String clientScopeId : cachedConsent.getClientScopeIds()) {
+// ClientScopeModel clientScope = KeycloakModelUtils.findClientScopeById(realm, client, clientScopeId);
+// if (clientScope != null) {
+// consentModel.addGrantedClientScope(clientScope);
+// }
+// }
+
+// return consentModel;
+// }
+
+// @Override
+// public void setNotBeforeForUser(RealmModel realm, UserModel user, int notBefore) {
+// if (!isRegisteredForInvalidation(realm, user.getId())) {
+// UserModel foundUser = getUserById(user.getId(), realm);
+// if (foundUser instanceof UserAdapter) {
+// ((UserAdapter) foundUser).invalidate();
+// }
+// }
+
+// getDelegate().setNotBeforeForUser(realm, user, notBefore);
+
+// }
+
+// @Override
+// public int getNotBeforeOfUser(RealmModel realm, UserModel user) {
+// if (isRegisteredForInvalidation(realm, user.getId())) {
+// return getDelegate().getNotBeforeOfUser(realm, user);
+// }
+
+// UserModel foundUser = getUserById(user.getId(), realm);
+// if (foundUser instanceof UserAdapter) {
+// return ((UserAdapter) foundUser).cached.getNotBefore();
+// } else {
+// return getDelegate().getNotBeforeOfUser(realm, user);
+// }
+// }
+
+// @Override
+// public UserModel addUser(RealmModel realm, String id, String username, boolean addDefaultRoles, boolean addDefaultRequiredActions) {
+// UserModel user = getDelegate().addUser(realm, id, username, addDefaultRoles, addDefaultRoles);
+// // just in case the transaction is rolled back you need to invalidate the user and all cache queries for that user
+// fullyInvalidateUser(realm, user);
+// managedUsers.put(user.getId(), user);
+// return user;
+// }
+
+// @Override
+// public UserModel addUser(RealmModel realm, String username) {
+// UserModel user = getDelegate().addUser(realm, username);
+// // just in case the transaction is rolled back you need to invalidate the user and all cache queries for that user
+// fullyInvalidateUser(realm, user);
+// managedUsers.put(user.getId(), user);
+// return user;
+// }
+
+// // just in case the transaction is rolled back you need to invalidate the user and all cache queries for that user
+// protected void fullyInvalidateUser(RealmModel realm, UserModel user) {
+// Set<FederatedIdentityModel> federatedIdentities = realm.isIdentityFederationEnabled() ? getFederatedIdentities(user, realm) : null;
+
+// UserFullInvalidationEvent event = UserFullInvalidationEvent.create(user.getId(), user.getUsername(), user.getEmail(), realm.getId(), realm.isIdentityFederationEnabled(), federatedIdentities);
+
+// cache.fullUserInvalidation(user.getId(), user.getUsername(), user.getEmail(), realm.getId(), realm.isIdentityFederationEnabled(), event.getFederatedIdentities(), invalidations);
+// invalidationEvents.add(event);
+// }
+
+// @Override
+// public boolean removeUser(RealmModel realm, UserModel user) {
+// fullyInvalidateUser(realm, user);
+// return getDelegate().removeUser(realm, user);
+// }
+
+// @Override
+// public void addFederatedIdentity(RealmModel realm, UserModel user, FederatedIdentityModel socialLink) {
+// invalidateFederationLink(user.getId());
+// getDelegate().addFederatedIdentity(realm, user, socialLink);
+// }
+
+// @Override
+// public void updateFederatedIdentity(RealmModel realm, UserModel federatedUser, FederatedIdentityModel federatedIdentityModel) {
+// invalidateFederationLink(federatedUser.getId());
+// getDelegate().updateFederatedIdentity(realm, federatedUser, federatedIdentityModel);
+// }
+
+// private void invalidateFederationLink(String userId) {
+// cache.federatedIdentityLinkUpdatedInvalidation(userId, invalidations);
+// invalidationEvents.add(UserFederationLinkUpdatedEvent.create(userId));
+// }
+
+// @Override
+// public boolean removeFederatedIdentity(RealmModel realm, UserModel user, String socialProvider) {
+// // Needs to invalidate both directions
+// FederatedIdentityModel socialLink = getFederatedIdentity(user, socialProvider, realm);
+
+// UserFederationLinkRemovedEvent event = UserFederationLinkRemovedEvent.create(user.getId(), realm.getId(), socialLink);
+// cache.federatedIdentityLinkRemovedInvalidation(user.getId(), realm.getId(), event.getIdentityProviderId(), event.getSocialUserId(), invalidations);
+// invalidationEvents.add(event);
+
+// return getDelegate().removeFederatedIdentity(realm, user, socialProvider);
+// }
+
+// @Override
+// public void grantToAllUsers(RealmModel realm, RoleModel role) {
+// addRealmInvalidation(realm.getId()); // easier to just invalidate whole realm
+// getDelegate().grantToAllUsers(realm, role);
+// }
+
+// @Override
+// public void preRemove(RealmModel realm) {
+// addRealmInvalidation(realm.getId());
+// getDelegate().preRemove(realm);
+// }
+
+// @Override
+// public void preRemove(RealmModel realm, RoleModel role) {
+// addRealmInvalidation(realm.getId()); // easier to just invalidate whole realm
+// getDelegate().preRemove(realm, role);
+// }
+// @Override
+// public void preRemove(RealmModel realm, GroupModel group) {
+// addRealmInvalidation(realm.getId()); // easier to just invalidate whole realm
+// getDelegate().preRemove(realm, group);
+// }
+
+
+// @Override
+// public void preRemove(RealmModel realm, ClientModel client) {
+// addRealmInvalidation(realm.getId()); // easier to just invalidate whole realm
+// getDelegate().preRemove(realm, client);
+// }
+
+// @Override
+// public void preRemove(ProtocolMapperModel protocolMapper) {
+// getDelegate().preRemove(protocolMapper);
+// }
+
+// @Override
+// public void preRemove(ClientScopeModel clientScope) {
+// // Not needed to invalidate realm probably. Just consents are affected ATM and they are checked if they exists
+// getDelegate().preRemove(clientScope);
+// }
+
+// @Override
+// public void preRemove(RealmModel realm, ComponentModel component) {
+// if (!component.getProviderType().equals(UserStorageProvider.class.getName()) && !component.getProviderType().equals(ClientStorageProvider.class.getName())) return;
+// addRealmInvalidation(realm.getId()); // easier to just invalidate whole realm
+// getDelegate().preRemove(realm, component);
+
+// }
+
+// @Override
+// public void removeImportedUsers(RealmModel realm, String storageProviderId) {
+// getDelegate().removeImportedUsers(realm, storageProviderId);
+// clear();
+// addRealmInvalidation(realm.getId()); // easier to just invalidate whole realm
+// }
+
+// @Override
+// public void unlinkUsers(RealmModel realm, String storageProviderId) {
+// getDelegate().unlinkUsers(realm, storageProviderId);
+// clear();
+// addRealmInvalidation(realm.getId()); // easier to just invalidate whole realm
+
+// }
+
+// private void addRealmInvalidation(String realmId) {
+// realmInvalidations.add(realmId);
+// invalidationEvents.add(UserCacheRealmInvalidationEvent.create(realmId));
+// }
+
+// }
diff --git a/model/infinispan/src/main/resources/META-INF/services/org.keycloak.models.cache.authorization.CachedStoreProviderFactory b/model/infinispan/src/main/resources/META-INF/services/org.keycloak.models.cache.authorization.CachedStoreProviderFactory
index d9bed49..4a8b3fd 100644
--- a/model/infinispan/src/main/resources/META-INF/services/org.keycloak.models.cache.authorization.CachedStoreProviderFactory
+++ b/model/infinispan/src/main/resources/META-INF/services/org.keycloak.models.cache.authorization.CachedStoreProviderFactory
@@ -16,4 +16,4 @@
# limitations under the License.
#
-org.keycloak.models.cache.infinispan.authorization.InfinispanCacheStoreFactoryProviderFactory
\ No newline at end of file
+# org.keycloak.models.cache.infinispan.authorization.InfinispanCacheStoreFactoryProviderFactory
\ No newline at end of file
diff --git a/model/infinispan/src/main/resources/META-INF/services/org.keycloak.models.cache.CacheRealmProviderFactory b/model/infinispan/src/main/resources/META-INF/services/org.keycloak.models.cache.CacheRealmProviderFactory
index a2b04e7..47a1cba 100755
--- a/model/infinispan/src/main/resources/META-INF/services/org.keycloak.models.cache.CacheRealmProviderFactory
+++ b/model/infinispan/src/main/resources/META-INF/services/org.keycloak.models.cache.CacheRealmProviderFactory
@@ -15,4 +15,4 @@
# limitations under the License.
#
-org.keycloak.models.cache.infinispan.InfinispanCacheRealmProviderFactory
+# org.keycloak.models.cache.infinispan.InfinispanCacheRealmProviderFactory
diff --git a/model/infinispan/src/main/resources/META-INF/services/org.keycloak.models.cache.UserCacheProviderFactory b/model/infinispan/src/main/resources/META-INF/services/org.keycloak.models.cache.UserCacheProviderFactory
index e558cf2..9dcba19 100755
--- a/model/infinispan/src/main/resources/META-INF/services/org.keycloak.models.cache.UserCacheProviderFactory
+++ b/model/infinispan/src/main/resources/META-INF/services/org.keycloak.models.cache.UserCacheProviderFactory
@@ -15,4 +15,4 @@
# limitations under the License.
#
-org.keycloak.models.cache.infinispan.InfinispanUserCacheProviderFactory
\ No newline at end of file
+# org.keycloak.models.cache.infinispan.InfinispanUserCacheProviderFactory
\ No newline at end of file
diff --git a/server-spi/src/main/java/org/keycloak/models/cache/CachedObject.java b/server-spi/src/main/java/org/keycloak/models/cache/CachedObject.java
index f252db5..0d1be77 100644
--- a/server-spi/src/main/java/org/keycloak/models/cache/CachedObject.java
+++ b/server-spi/src/main/java/org/keycloak/models/cache/CachedObject.java
@@ -14,12 +14,12 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.keycloak.models.cache;
+// package org.keycloak.models.cache;
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public interface CachedObject {
- long getCacheTimestamp();
-}
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public interface CachedObject {
+// long getCacheTimestamp();
+// }
diff --git a/server-spi/src/main/java/org/keycloak/models/cache/CachedUserModel.java b/server-spi/src/main/java/org/keycloak/models/cache/CachedUserModel.java
index 1d3f59f..9adb126 100644
--- a/server-spi/src/main/java/org/keycloak/models/cache/CachedUserModel.java
+++ b/server-spi/src/main/java/org/keycloak/models/cache/CachedUserModel.java
@@ -1,59 +1,59 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.keycloak.models.cache;
-
-import org.keycloak.models.UserModel;
-
-import java.util.concurrent.ConcurrentMap;
-
-/**
- * Cached users will implement this interface
- *
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public interface CachedUserModel extends UserModel {
-
- /**
- * Invalidates the cache for this user and returns a delegate that represents the actual data provider
- *
- * @return
- */
- UserModel getDelegateForUpdate();
-
- boolean isMarkedForEviction();
-
- /**
- * Invalidate the cache for this model
- *
- */
- void invalidate();
-
- /**
- * When was the model was loaded from database.
- *
- * @return
- */
- long getCacheTimestamp();
-
- /**
- * Returns a map that contains custom things that are cached along with this model. You can write to this map.
- *
- * @return
- */
- ConcurrentMap getCachedWith();
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+// package org.keycloak.models.cache;
+
+// import org.keycloak.models.UserModel;
+
+// import java.util.concurrent.ConcurrentMap;
+
+// /**
+// * Cached users will implement this interface
+// *
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public interface CachedUserModel extends UserModel {
+
+// /**
+// * Invalidates the cache for this user and returns a delegate that represents the actual data provider
+// *
+// * @return
+// */
+// UserModel getDelegateForUpdate();
+
+// boolean isMarkedForEviction();
+
+// /**
+// * Invalidate the cache for this model
+// *
+// */
+// void invalidate();
+
+// /**
+// * When was the model was loaded from database.
+// *
+// * @return
+// */
+// long getCacheTimestamp();
+
+// /**
+// * Returns a map that contains custom things that are cached along with this model. You can write to this map.
+// *
+// * @return
+// */
+// ConcurrentMap getCachedWith();
+// }
diff --git a/server-spi/src/main/java/org/keycloak/models/cache/OnUserCache.java b/server-spi/src/main/java/org/keycloak/models/cache/OnUserCache.java
index 319b5c5..2dc1989 100644
--- a/server-spi/src/main/java/org/keycloak/models/cache/OnUserCache.java
+++ b/server-spi/src/main/java/org/keycloak/models/cache/OnUserCache.java
@@ -14,15 +14,15 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.keycloak.models.cache;
+// package org.keycloak.models.cache;
-import org.keycloak.models.RealmModel;
-import org.keycloak.models.UserModel;
+// import org.keycloak.models.RealmModel;
+// import org.keycloak.models.UserModel;
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public interface OnUserCache {
- void onCache(RealmModel realm, CachedUserModel user, UserModel delegate);
-}
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public interface OnUserCache {
+// void onCache(RealmModel realm, CachedUserModel user, UserModel delegate);
+// }
diff --git a/server-spi/src/main/java/org/keycloak/models/cache/UserCache.java b/server-spi/src/main/java/org/keycloak/models/cache/UserCache.java
index ab70808..21bb55b 100755
--- a/server-spi/src/main/java/org/keycloak/models/cache/UserCache.java
+++ b/server-spi/src/main/java/org/keycloak/models/cache/UserCache.java
@@ -1,50 +1,50 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
-package org.keycloak.models.cache;
+// package org.keycloak.models.cache;
-import org.keycloak.models.RealmModel;
-import org.keycloak.models.UserModel;
-import org.keycloak.models.UserProvider;
+// import org.keycloak.models.RealmModel;
+// import org.keycloak.models.UserModel;
+// import org.keycloak.models.UserProvider;
-/**
- * All these methods effect an entire cluster of Keycloak instances.
- *
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public interface UserCache extends UserProvider {
- /**
- * Evict user from cache.
- *
- * @param user
- */
- void evict(RealmModel realm, UserModel user);
+// /**
+// * All these methods effect an entire cluster of Keycloak instances.
+// *
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public interface UserCache extends UserProvider {
+// /**
+// * Evict user from cache.
+// *
+// * @param user
+// */
+// void evict(RealmModel realm, UserModel user);
- /**
- * Evict users of a specific realm
- *
- * @param realm
- */
- void evict(RealmModel realm);
+// /**
+// * Evict users of a specific realm
+// *
+// * @param realm
+// */
+// void evict(RealmModel realm);
- /**
- * Clear cache entirely.
- *
- */
- void clear();
-}
+// /**
+// * Clear cache entirely.
+// *
+// */
+// void clear();
+// }
diff --git a/server-spi/src/main/java/org/keycloak/models/KeycloakSession.java b/server-spi/src/main/java/org/keycloak/models/KeycloakSession.java
index 19773dc..97d0cd4 100755
--- a/server-spi/src/main/java/org/keycloak/models/KeycloakSession.java
+++ b/server-spi/src/main/java/org/keycloak/models/KeycloakSession.java
@@ -18,7 +18,7 @@
package org.keycloak.models;
import org.keycloak.component.ComponentModel;
-import org.keycloak.models.cache.UserCache;
+// import org.keycloak.models.cache.UserCache;
import org.keycloak.provider.Provider;
import org.keycloak.sessions.AuthenticationSessionProvider;
import org.keycloak.storage.federated.UserFederatedStorageProvider;
@@ -125,7 +125,7 @@ public interface KeycloakSession {
*
* @return may be null if cache is disabled
*/
- UserCache userCache();
+ // UserCache userCache();
/**
* A cached view of all users in system including users loaded by UserStorageProviders
diff --git a/server-spi/src/main/java/org/keycloak/storage/CacheableStorageProviderModel.java b/server-spi/src/main/java/org/keycloak/storage/CacheableStorageProviderModel.java
index 3fb8384..27068a4 100644
--- a/server-spi/src/main/java/org/keycloak/storage/CacheableStorageProviderModel.java
+++ b/server-spi/src/main/java/org/keycloak/storage/CacheableStorageProviderModel.java
@@ -19,7 +19,7 @@ package org.keycloak.storage;
import org.keycloak.common.util.Time;
import org.keycloak.component.ComponentModel;
import org.keycloak.component.PrioritizedComponentModel;
-import org.keycloak.models.cache.CachedObject;
+// import org.keycloak.models.cache.CachedObject;
import java.util.Calendar;
@@ -180,41 +180,41 @@ public class CacheableStorageProviderModel extends PrioritizedComponentModel {
return lifespan;
}
- public boolean shouldInvalidate(CachedObject cached) {
- boolean invalidate = false;
- if (!isEnabled()) {
- invalidate = true;
- } else {
- CacheableStorageProviderModel.CachePolicy policy = getCachePolicy();
- if (policy != null) {
- //String currentTime = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date(Time.currentTimeMillis()));
- if (policy == CacheableStorageProviderModel.CachePolicy.NO_CACHE) {
- invalidate = true;
- } else if (cached.getCacheTimestamp() < getCacheInvalidBefore()) {
- invalidate = true;
- } else if (policy == CacheableStorageProviderModel.CachePolicy.MAX_LIFESPAN) {
- if (cached.getCacheTimestamp() + getMaxLifespan() < Time.currentTimeMillis()) {
- invalidate = true;
- }
- } else if (policy == CacheableStorageProviderModel.CachePolicy.EVICT_DAILY) {
- long dailyBoundary = dailyEvictionBoundary(getEvictionHour(), getEvictionMinute());
- if (cached.getCacheTimestamp() <= dailyBoundary) {
- invalidate = true;
- }
- } else if (policy == CacheableStorageProviderModel.CachePolicy.EVICT_WEEKLY) {
- int oneWeek = 7 * 24 * 60 * 60 * 1000;
- long weeklyTimeout = weeklyTimeout(getEvictionDay(), getEvictionHour(), getEvictionMinute());
- long lastTimeout = weeklyTimeout - oneWeek;
- //String timeout = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date(weeklyTimeout));
- //String stamp = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date(cached.getCacheTimestamp()));
- if (cached.getCacheTimestamp() <= lastTimeout) {
- invalidate = true;
- }
- }
- }
- }
- return invalidate;
- }
+ // public boolean shouldInvalidate(CachedObject cached) {
+ // boolean invalidate = false;
+ // if (!isEnabled()) {
+ // invalidate = true;
+ // } else {
+ // CacheableStorageProviderModel.CachePolicy policy = getCachePolicy();
+ // if (policy != null) {
+ // //String currentTime = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date(Time.currentTimeMillis()));
+ // if (policy == CacheableStorageProviderModel.CachePolicy.NO_CACHE) {
+ // invalidate = true;
+ // } else if (cached.getCacheTimestamp() < getCacheInvalidBefore()) {
+ // invalidate = true;
+ // } else if (policy == CacheableStorageProviderModel.CachePolicy.MAX_LIFESPAN) {
+ // if (cached.getCacheTimestamp() + getMaxLifespan() < Time.currentTimeMillis()) {
+ // invalidate = true;
+ // }
+ // } else if (policy == CacheableStorageProviderModel.CachePolicy.EVICT_DAILY) {
+ // long dailyBoundary = dailyEvictionBoundary(getEvictionHour(), getEvictionMinute());
+ // if (cached.getCacheTimestamp() <= dailyBoundary) {
+ // invalidate = true;
+ // }
+ // } else if (policy == CacheableStorageProviderModel.CachePolicy.EVICT_WEEKLY) {
+ // int oneWeek = 7 * 24 * 60 * 60 * 1000;
+ // long weeklyTimeout = weeklyTimeout(getEvictionDay(), getEvictionHour(), getEvictionMinute());
+ // long lastTimeout = weeklyTimeout - oneWeek;
+ // //String timeout = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date(weeklyTimeout));
+ // //String stamp = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL).format(new Date(cached.getCacheTimestamp()));
+ // if (cached.getCacheTimestamp() <= lastTimeout) {
+ // invalidate = true;
+ // }
+ // }
+ // }
+ // }
+ // return invalidate;
+ // }
public static long dailyTimeout(int hour, int minute) {
diff --git a/server-spi-private/src/main/java/org/keycloak/authorization/AuthorizationProvider.java b/server-spi-private/src/main/java/org/keycloak/authorization/AuthorizationProvider.java
index bd1d88d..3d713e4 100644
--- a/server-spi-private/src/main/java/org/keycloak/authorization/AuthorizationProvider.java
+++ b/server-spi-private/src/main/java/org/keycloak/authorization/AuthorizationProvider.java
@@ -108,7 +108,7 @@ public final class AuthorizationProvider implements Provider {
*/
public StoreFactory getStoreFactory() {
if (storeFactory != null) return storeFactory;
- storeFactory = keycloakSession.getProvider(CachedStoreFactoryProvider.class);
+ // storeFactory = keycloakSession.getProvider(CachedStoreFactoryProvider.class);
if (storeFactory == null) storeFactory = getLocalStoreFactory();
storeFactory = createStoreFactory(storeFactory);
return storeFactory;
diff --git a/server-spi-private/src/main/java/org/keycloak/authorization/model/CachedModel.java b/server-spi-private/src/main/java/org/keycloak/authorization/model/CachedModel.java
index d908a84..20ace85 100644
--- a/server-spi-private/src/main/java/org/keycloak/authorization/model/CachedModel.java
+++ b/server-spi-private/src/main/java/org/keycloak/authorization/model/CachedModel.java
@@ -14,32 +14,32 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.keycloak.authorization.model;
+// package org.keycloak.authorization.model;
-/**
- * Cached authorization model classes will implement this interface.
- *
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public interface CachedModel<Model> {
- /**
- * Invalidates the cache for this model and returns a delegate that represents the actual data provider
- *
- * @return
- */
- Model getDelegateForUpdate();
+// /**
+// * Cached authorization model classes will implement this interface.
+// *
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public interface CachedModel<Model> {
+// /**
+// * Invalidates the cache for this model and returns a delegate that represents the actual data provider
+// *
+// * @return
+// */
+// Model getDelegateForUpdate();
- /**
- * Invalidate the cache for this model
- *
- */
- void invalidate();
+// /**
+// * Invalidate the cache for this model
+// *
+// */
+// void invalidate();
- /**
- * When was the model was loaded from database.
- *
- * @return
- */
- long getCacheTimestamp();
-}
+// /**
+// * When was the model was loaded from database.
+// *
+// * @return
+// */
+// long getCacheTimestamp();
+// }
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 792a151..cfd6689 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
@@ -24,7 +24,7 @@ import org.keycloak.models.KeycloakSession;
import org.keycloak.models.LDAPConstants;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
-import org.keycloak.models.cache.UserCache;
+// import org.keycloak.models.cache.UserCache;
import org.keycloak.models.utils.DefaultAuthenticationFlows;
import org.keycloak.models.utils.DefaultRequiredActions;
import org.keycloak.models.utils.KeycloakModelUtils;
@@ -93,10 +93,10 @@ public class MigrateTo1_4_0 implements Migration {
email = KeycloakModelUtils.toLowerCaseSafe(email);
if (email != null && !email.equals(user.getEmail())) {
user.setEmail(email);
- UserCache userCache = session.userCache();
- if (userCache != null) {
- userCache.evict(realm, user);
- }
+ // UserCache userCache = session.userCache();
+ // if (userCache != null) {
+ // userCache.evict(realm, user);
+ // }
}
}
}
diff --git a/server-spi-private/src/main/java/org/keycloak/models/cache/CachedRealmModel.java b/server-spi-private/src/main/java/org/keycloak/models/cache/CachedRealmModel.java
index 09111cc..a130ec4 100644
--- a/server-spi-private/src/main/java/org/keycloak/models/cache/CachedRealmModel.java
+++ b/server-spi-private/src/main/java/org/keycloak/models/cache/CachedRealmModel.java
@@ -1,64 +1,64 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.keycloak.models.cache;
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+// package org.keycloak.models.cache;
-import org.keycloak.models.KeycloakSession;
-import org.keycloak.models.RealmModel;
-import org.keycloak.provider.ProviderEvent;
+// import org.keycloak.models.KeycloakSession;
+// import org.keycloak.models.RealmModel;
+// import org.keycloak.provider.ProviderEvent;
-import java.util.concurrent.ConcurrentHashMap;
+// import java.util.concurrent.ConcurrentHashMap;
-/**
- * Cached realms will implement this interface
- *
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public interface CachedRealmModel extends RealmModel {
+// /**
+// * Cached realms will implement this interface
+// *
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public interface CachedRealmModel extends RealmModel {
- interface RealmCachedEvent extends ProviderEvent {
- CachedRealmModel getRealm();
- KeycloakSession getKeycloakSession();
- }
+// interface RealmCachedEvent extends ProviderEvent {
+// CachedRealmModel getRealm();
+// KeycloakSession getKeycloakSession();
+// }
- /**
- * Invalidates the cache for this model and returns a delegate that represents the actual data provider
- *
- * @return
- */
- RealmModel getDelegateForUpdate();
+// /**
+// * Invalidates the cache for this model and returns a delegate that represents the actual data provider
+// *
+// * @return
+// */
+// RealmModel getDelegateForUpdate();
- /**
- * Invalidate the cache for this model
- *
- */
- void invalidate();
+// /**
+// * Invalidate the cache for this model
+// *
+// */
+// void invalidate();
- /**
- * When was the model was loaded from database.
- *
- * @return
- */
- long getCacheTimestamp();
+// /**
+// * When was the model was loaded from database.
+// *
+// * @return
+// */
+// long getCacheTimestamp();
- /**
- * Returns a map that contains custom things that are cached along with this model. You can write to this map.
- *
- * @return
- */
- ConcurrentHashMap getCachedWith();
-}
+// /**
+// * Returns a map that contains custom things that are cached along with this model. You can write to this map.
+// *
+// * @return
+// */
+// ConcurrentHashMap getCachedWith();
+// }
diff --git a/server-spi-private/src/main/java/org/keycloak/models/cache/CacheUserProviderSpi.java b/server-spi-private/src/main/java/org/keycloak/models/cache/CacheUserProviderSpi.java
index a0efa39..0352083 100755
--- a/server-spi-private/src/main/java/org/keycloak/models/cache/CacheUserProviderSpi.java
+++ b/server-spi-private/src/main/java/org/keycloak/models/cache/CacheUserProviderSpi.java
@@ -1,49 +1,49 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
-package org.keycloak.models.cache;
+// package org.keycloak.models.cache;
-import org.keycloak.provider.Provider;
-import org.keycloak.provider.ProviderFactory;
-import org.keycloak.provider.Spi;
+// import org.keycloak.provider.Provider;
+// import org.keycloak.provider.ProviderFactory;
+// import org.keycloak.provider.Spi;
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class CacheUserProviderSpi implements Spi {
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public class CacheUserProviderSpi implements Spi {
- @Override
- public boolean isInternal() {
- return true;
- }
+// @Override
+// public boolean isInternal() {
+// return true;
+// }
- @Override
- public String getName() {
- return "userCache";
- }
+// @Override
+// public String getName() {
+// return "userCache";
+// }
- @Override
- public Class<? extends Provider> getProviderClass() {
- return UserCache.class;
- }
+// @Override
+// public Class<? extends Provider> getProviderClass() {
+// return UserCache.class;
+// }
- @Override
- public Class<? extends ProviderFactory> getProviderFactoryClass() {
- return UserCacheProviderFactory.class;
- }
-}
+// @Override
+// public Class<? extends ProviderFactory> getProviderFactoryClass() {
+// return UserCacheProviderFactory.class;
+// }
+// }
diff --git a/server-spi-private/src/main/java/org/keycloak/models/cache/UserCacheProviderFactory.java b/server-spi-private/src/main/java/org/keycloak/models/cache/UserCacheProviderFactory.java
index fdf4fd8..0aaf572 100755
--- a/server-spi-private/src/main/java/org/keycloak/models/cache/UserCacheProviderFactory.java
+++ b/server-spi-private/src/main/java/org/keycloak/models/cache/UserCacheProviderFactory.java
@@ -15,14 +15,14 @@
* limitations under the License.
*/
-package org.keycloak.models.cache;
+// package org.keycloak.models.cache;
-import org.keycloak.provider.ProviderFactory;
+// import org.keycloak.provider.ProviderFactory;
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public interface UserCacheProviderFactory extends ProviderFactory<UserCache> {
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public interface UserCacheProviderFactory extends ProviderFactory<UserCache> {
-}
+// }
diff --git a/server-spi-private/src/main/resources/META-INF/services/org.keycloak.provider.Spi b/server-spi-private/src/main/resources/META-INF/services/org.keycloak.provider.Spi
index bb4c6c3..8c8dff1 100755
--- a/server-spi-private/src/main/resources/META-INF/services/org.keycloak.provider.Spi
+++ b/server-spi-private/src/main/resources/META-INF/services/org.keycloak.provider.Spi
@@ -52,7 +52,7 @@ org.keycloak.theme.ThemeSpi
org.keycloak.truststore.TruststoreSpi
org.keycloak.connections.httpclient.HttpClientSpi
org.keycloak.models.cache.CacheRealmProviderSpi
-org.keycloak.models.cache.CacheUserProviderSpi
+# org.keycloak.models.cache.CacheUserProviderSpi
org.keycloak.authentication.AuthenticatorSpi
org.keycloak.authentication.ClientAuthenticatorSpi
org.keycloak.authentication.RequiredActionSpi
diff --git a/services/src/main/java/org/keycloak/credential/OTPCredentialProvider.java b/services/src/main/java/org/keycloak/credential/OTPCredentialProvider.java
index e25de88..f3f1ce7 100644
--- a/services/src/main/java/org/keycloak/credential/OTPCredentialProvider.java
+++ b/services/src/main/java/org/keycloak/credential/OTPCredentialProvider.java
@@ -23,9 +23,9 @@ import org.keycloak.models.OTPPolicy;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel;
-import org.keycloak.models.cache.CachedUserModel;
-import org.keycloak.models.cache.OnUserCache;
-import org.keycloak.models.cache.UserCache;
+// import org.keycloak.models.cache.CachedUserModel;
+// import org.keycloak.models.cache.OnUserCache;
+// import org.keycloak.models.cache.UserCache;
import org.keycloak.models.utils.HmacOTP;
import org.keycloak.models.utils.TimeBasedOTP;
@@ -38,30 +38,30 @@ import java.util.Set;
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
-public class OTPCredentialProvider implements CredentialProvider, CredentialInputValidator, CredentialInputUpdater, OnUserCache {
+public class OTPCredentialProvider implements CredentialProvider, CredentialInputValidator, CredentialInputUpdater{//, OnUserCache {
private static final Logger logger = Logger.getLogger(OTPCredentialProvider.class);
protected KeycloakSession session;
- protected List<CredentialModel> getCachedCredentials(UserModel user, String type) {
- if (!(user instanceof CachedUserModel)) return null;
- CachedUserModel cached = (CachedUserModel)user;
- if (cached.isMarkedForEviction()) return null;
- List<CredentialModel> rtn = (List<CredentialModel>)cached.getCachedWith().get(OTPCredentialProvider.class.getName() + "." + type);
- if (rtn == null) return Collections.EMPTY_LIST;
- return rtn;
- }
+ // protected List<CredentialModel> getCachedCredentials(UserModel user, String type) {
+ // if (!(user instanceof CachedUserModel)) return null;
+ // CachedUserModel cached = (CachedUserModel)user;
+ // if (cached.isMarkedForEviction()) return null;
+ // List<CredentialModel> rtn = (List<CredentialModel>)cached.getCachedWith().get(OTPCredentialProvider.class.getName() + "." + type);
+ // if (rtn == null) return Collections.EMPTY_LIST;
+ // return rtn;
+ // }
protected UserCredentialStore getCredentialStore() {
return session.userCredentialManager();
}
- @Override
- public void onCache(RealmModel realm, CachedUserModel user, UserModel delegate) {
- List<CredentialModel> creds = getCredentialStore().getStoredCredentialsByType(realm, user, CredentialModel.TOTP);
- user.getCachedWith().put(OTPCredentialProvider.class.getName() + "." + CredentialModel.TOTP, creds);
+ // @Override
+ // public void onCache(RealmModel realm, CachedUserModel user, UserModel delegate) {
+ // List<CredentialModel> creds = getCredentialStore().getStoredCredentialsByType(realm, user, CredentialModel.TOTP);
+ // user.getCachedWith().put(OTPCredentialProvider.class.getName() + "." + CredentialModel.TOTP, creds);
- }
+ // }
public OTPCredentialProvider(KeycloakSession session) {
this.session = session;
@@ -103,10 +103,10 @@ public class OTPCredentialProvider implements CredentialProvider, CredentialInpu
} else {
getCredentialStore().updateCredential(realm, user, model);
}
- UserCache userCache = session.userCache();
- if (userCache != null) {
- userCache.evict(realm, user);
- }
+ // UserCache userCache = session.userCache();
+ // if (userCache != null) {
+ // userCache.evict(realm, user);
+ // }
return true;
@@ -142,10 +142,10 @@ public class OTPCredentialProvider implements CredentialProvider, CredentialInpu
}
if (disableTOTP || disableHOTP) {
- UserCache userCache = session.userCache();
- if (userCache != null) {
- userCache.evict(realm, user);
- }
+ // UserCache userCache = session.userCache();
+ // if (userCache != null) {
+ // userCache.evict(realm, user);
+ // }
}
}
@@ -194,9 +194,10 @@ public class OTPCredentialProvider implements CredentialProvider, CredentialInpu
}
protected boolean configuredForTOTP(RealmModel realm, UserModel user) {
- List<CredentialModel> cachedCredentials = getCachedCredentials(user, CredentialModel.TOTP);
- if (cachedCredentials == null) return !getCredentialStore().getStoredCredentialsByType(realm, user, CredentialModel.TOTP).isEmpty();
- return !cachedCredentials.isEmpty();
+ // List<CredentialModel> cachedCredentials = getCachedCredentials(user, CredentialModel.TOTP);
+ // if (cachedCredentials == null)
+ return !getCredentialStore().getStoredCredentialsByType(realm, user, CredentialModel.TOTP).isEmpty();
+ // return !cachedCredentials.isEmpty();
}
public static boolean validOTP(RealmModel realm, String token, String secret) {
@@ -236,12 +237,12 @@ public class OTPCredentialProvider implements CredentialProvider, CredentialInpu
}
} else {
TimeBasedOTP validator = new TimeBasedOTP(policy.getAlgorithm(), policy.getDigits(), policy.getPeriod(), policy.getLookAheadWindow());
- List<CredentialModel> creds = getCachedCredentials(user, CredentialModel.TOTP);
- if (creds == null) {
+ List<CredentialModel> creds;// = getCachedCredentials(user, CredentialModel.TOTP);
+ // if (creds == null) {
creds = getCredentialStore().getStoredCredentialsByType(realm, user, CredentialModel.TOTP);
- } else {
- logger.debugv("Cache hit for TOTP for user {0}", user.getUsername());
- }
+ // } else {
+ // logger.debugv("Cache hit for TOTP for user {0}", user.getUsername());
+ // }
for (CredentialModel cred : creds) {
if (validator.validateTOTP(token, cred.getValue().getBytes())) {
return true;
diff --git a/services/src/main/java/org/keycloak/credential/PasswordCredentialProvider.java b/services/src/main/java/org/keycloak/credential/PasswordCredentialProvider.java
index 98fd928..795472c 100644
--- a/services/src/main/java/org/keycloak/credential/PasswordCredentialProvider.java
+++ b/services/src/main/java/org/keycloak/credential/PasswordCredentialProvider.java
@@ -25,9 +25,9 @@ import org.keycloak.models.PasswordPolicy;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserCredentialModel;
import org.keycloak.models.UserModel;
-import org.keycloak.models.cache.CachedUserModel;
-import org.keycloak.models.cache.OnUserCache;
-import org.keycloak.models.cache.UserCache;
+// import org.keycloak.models.cache.CachedUserModel;
+// import org.keycloak.models.cache.OnUserCache;
+// import org.keycloak.models.cache.UserCache;
import org.keycloak.policy.PasswordPolicyManagerProvider;
import org.keycloak.policy.PolicyError;
@@ -40,7 +40,7 @@ import java.util.Set;
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
-public class PasswordCredentialProvider implements CredentialProvider, CredentialInputValidator, CredentialInputUpdater, OnUserCache {
+public class PasswordCredentialProvider implements CredentialProvider, CredentialInputValidator, CredentialInputUpdater{//, OnUserCache {
public static final String PASSWORD_CACHE_KEY = PasswordCredentialProvider.class.getName() + "." + CredentialModel.PASSWORD;
private static final Logger logger = Logger.getLogger(PasswordCredentialProvider.class);
@@ -57,15 +57,15 @@ public class PasswordCredentialProvider implements CredentialProvider, Credentia
public CredentialModel getPassword(RealmModel realm, UserModel user) {
List<CredentialModel> passwords = null;
- if (user instanceof CachedUserModel && !((CachedUserModel)user).isMarkedForEviction()) {
- CachedUserModel cached = (CachedUserModel)user;
- passwords = (List<CredentialModel>)cached.getCachedWith().get(PASSWORD_CACHE_KEY);
+ // if (user instanceof CachedUserModel && !((CachedUserModel)user).isMarkedForEviction()) {
+ // CachedUserModel cached = (CachedUserModel)user;
+ // passwords = (List<CredentialModel>)cached.getCachedWith().get(PASSWORD_CACHE_KEY);
- }
+ // }
// if the model was marked for eviction while passwords were initialized, override it from credentialStore
- if (! (user instanceof CachedUserModel) || ((CachedUserModel) user).isMarkedForEviction()) {
+ // if (! (user instanceof CachedUserModel) || ((CachedUserModel) user).isMarkedForEviction()) {
passwords = getCredentialStore().getStoredCredentialsByType(realm, user, CredentialModel.PASSWORD);
- }
+ // }
if (passwords == null || passwords.isEmpty()) return null;
return passwords.get(0);
}
@@ -99,10 +99,10 @@ public class PasswordCredentialProvider implements CredentialProvider, Credentia
newPassword.setCreatedDate(createdDate);
hash.encode(cred.getValue(), policy.getHashIterations(), newPassword);
getCredentialStore().createCredential(realm, user, newPassword);
- UserCache userCache = session.userCache();
- if (userCache != null) {
- userCache.evict(realm, user);
- }
+ // UserCache userCache = session.userCache();
+ // if (userCache != null) {
+ // userCache.evict(realm, user);
+ // }
return true;
}
@@ -214,20 +214,20 @@ public class PasswordCredentialProvider implements CredentialProvider, Credentia
hash.encode(cred.getValue(), policy.getHashIterations(), newPassword);
getCredentialStore().updateCredential(realm, user, newPassword);
- UserCache userCache = session.userCache();
- if (userCache != null) {
- userCache.evict(realm, user);
- }
+ // UserCache userCache = session.userCache();
+ // if (userCache != null) {
+ // userCache.evict(realm, user);
+ // }
return true;
}
- @Override
- public void onCache(RealmModel realm, CachedUserModel user, UserModel delegate) {
- List<CredentialModel> passwords = getCredentialStore().getStoredCredentialsByType(realm, user, CredentialModel.PASSWORD);
- if (passwords != null) {
- user.getCachedWith().put(PASSWORD_CACHE_KEY, passwords);
- }
+ // @Override
+ // public void onCache(RealmModel realm, CachedUserModel user, UserModel delegate) {
+ // List<CredentialModel> passwords = getCredentialStore().getStoredCredentialsByType(realm, user, CredentialModel.PASSWORD);
+ // if (passwords != null) {
+ // user.getCachedWith().put(PASSWORD_CACHE_KEY, passwords);
+ // }
- }
+ // }
}
diff --git a/services/src/main/java/org/keycloak/credential/UserCredentialStoreManager.java b/services/src/main/java/org/keycloak/credential/UserCredentialStoreManager.java
index 16f789b..3086fd6 100644
--- a/services/src/main/java/org/keycloak/credential/UserCredentialStoreManager.java
+++ b/services/src/main/java/org/keycloak/credential/UserCredentialStoreManager.java
@@ -22,8 +22,8 @@ import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserCredentialManager;
import org.keycloak.models.UserModel;
-import org.keycloak.models.cache.CachedUserModel;
-import org.keycloak.models.cache.OnUserCache;
+// import org.keycloak.models.cache.CachedUserModel;
+// import org.keycloak.models.cache.OnUserCache;
import org.keycloak.provider.ProviderFactory;
import org.keycloak.storage.StorageId;
import org.keycloak.storage.UserStorageManager;
@@ -41,7 +41,7 @@ import java.util.Set;
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
-public class UserCredentialStoreManager implements UserCredentialManager, OnUserCache {
+public class UserCredentialStoreManager implements UserCredentialManager{//, OnUserCache {
protected KeycloakSession session;
public UserCredentialStoreManager(KeycloakSession session) {
@@ -309,13 +309,13 @@ public class UserCredentialStoreManager implements UserCredentialManager, OnUser
return null;
}
- @Override
- public void onCache(RealmModel realm, CachedUserModel user, UserModel delegate) {
- List<OnUserCache> credentialProviders = getCredentialProviders(session, realm, OnUserCache.class);
- for (OnUserCache validator : credentialProviders) {
- validator.onCache(realm, user, delegate);
- }
- }
+ // @Override
+ // public void onCache(RealmModel realm, CachedUserModel user, UserModel delegate) {
+ // List<OnUserCache> credentialProviders = getCredentialProviders(session, realm, OnUserCache.class);
+ // for (OnUserCache validator : credentialProviders) {
+ // validator.onCache(realm, user, delegate);
+ // }
+ // }
@Override
public void close() {
diff --git a/services/src/main/java/org/keycloak/services/DefaultKeycloakSession.java b/services/src/main/java/org/keycloak/services/DefaultKeycloakSession.java
index f280ea7..5aa33cd 100644
--- a/services/src/main/java/org/keycloak/services/DefaultKeycloakSession.java
+++ b/services/src/main/java/org/keycloak/services/DefaultKeycloakSession.java
@@ -34,7 +34,7 @@ import org.keycloak.models.UserCredentialManager;
import org.keycloak.models.UserProvider;
import org.keycloak.models.UserSessionProvider;
import org.keycloak.models.cache.CacheRealmProvider;
-import org.keycloak.models.cache.UserCache;
+// import org.keycloak.models.cache.UserCache;
import org.keycloak.provider.Provider;
import org.keycloak.provider.ProviderFactory;
import org.keycloak.sessions.AuthenticationSessionProvider;
@@ -92,11 +92,11 @@ public class DefaultKeycloakSession implements KeycloakSession {
}
}
- @Override
- public UserCache userCache() {
- return getProvider(UserCache.class);
+ // @Override
+ // public UserCache userCache() {
+ // return getProvider(UserCache.class);
- }
+ // }
@Override
public void enlistForClose(Provider provider) {
@@ -172,12 +172,12 @@ public class DefaultKeycloakSession implements KeycloakSession {
@Override
public UserProvider users() {
- UserCache cache = getProvider(UserCache.class);
- if (cache != null) {
- return cache;
- } else {
+ // UserCache cache = getProvider(UserCache.class);
+ // if (cache != null) {
+ // return cache;
+ // } else {
return userStorageManager();
- }
+ // }
}
@Override
diff --git a/services/src/main/java/org/keycloak/services/resources/admin/RealmAdminResource.java b/services/src/main/java/org/keycloak/services/resources/admin/RealmAdminResource.java
index d35ccaf..98e76c0 100644
--- a/services/src/main/java/org/keycloak/services/resources/admin/RealmAdminResource.java
+++ b/services/src/main/java/org/keycloak/services/resources/admin/RealmAdminResource.java
@@ -53,7 +53,7 @@ import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.models.cache.CacheRealmProvider;
-import org.keycloak.models.cache.UserCache;
+// import org.keycloak.models.cache.UserCache;
import org.keycloak.models.utils.KeycloakModelUtils;
import org.keycloak.models.utils.ModelToRepresentation;
import org.keycloak.models.utils.RepresentationToModel;
@@ -426,10 +426,10 @@ public class RealmAdminResource {
adminEvent.operation(OperationType.UPDATE).representation(StripSecretsUtils.strip(rep)).success();
- if (rep.isDuplicateEmailsAllowed() != null && rep.isDuplicateEmailsAllowed() != wasDuplicateEmailsAllowed) {
- UserCache cache = session.getProvider(UserCache.class);
- if (cache != null) cache.clear();
- }
+ // if (rep.isDuplicateEmailsAllowed() != null && rep.isDuplicateEmailsAllowed() != wasDuplicateEmailsAllowed) {
+ // UserCache cache = session.getProvider(UserCache.class);
+ // if (cache != null) cache.clear();
+ // }
return Response.noContent().build();
} catch (ModelDuplicateException e) {
@@ -1120,10 +1120,10 @@ public class RealmAdminResource {
public void clearUserCache() {
auth.realm().requireManageRealm();
- UserCache cache = session.getProvider(UserCache.class);
- if (cache != null) {
- cache.clear();
- }
+ // UserCache cache = session.getProvider(UserCache.class);
+ // if (cache != null) {
+ // cache.clear();
+ // }
adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).success();
}
diff --git a/services/src/main/java/org/keycloak/storage/UserStorageManager.java b/services/src/main/java/org/keycloak/storage/UserStorageManager.java
index 93b7f72..accb258 100755
--- a/services/src/main/java/org/keycloak/storage/UserStorageManager.java
+++ b/services/src/main/java/org/keycloak/storage/UserStorageManager.java
@@ -35,9 +35,9 @@ import org.keycloak.models.UserConsentModel;
import org.keycloak.models.UserManager;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserProvider;
-import org.keycloak.models.cache.CachedUserModel;
-import org.keycloak.models.cache.OnUserCache;
-import org.keycloak.models.cache.UserCache;
+// import org.keycloak.models.cache.CachedUserModel;
+// import org.keycloak.models.cache.OnUserCache;
+// import org.keycloak.models.cache.UserCache;
import org.keycloak.models.utils.ComponentUtil;
import org.keycloak.models.utils.ReadOnlyUserModelDelegate;
import org.keycloak.services.managers.UserStorageSyncManager;
@@ -63,7 +63,9 @@ import static org.keycloak.models.utils.KeycloakModelUtils.runJobInTransaction;
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
*/
-public class UserStorageManager implements UserProvider, OnUserCache, OnCreateComponent, OnUpdateComponent {
+public class UserStorageManager implements UserProvider
+// , OnUserCache
+, OnCreateComponent, OnUpdateComponent {
private static final Logger logger = Logger.getLogger(UserStorageManager.class);
@@ -333,10 +335,10 @@ public class UserStorageManager implements UserProvider, OnUserCache, OnCreateCo
protected void deleteInvalidUser(final RealmModel realm, final UserModel user) {
String userId = user.getId();
String userName = user.getUsername();
- UserCache userCache = session.userCache();
- if (userCache != null) {
- userCache.evict(realm, user);
- }
+ // UserCache userCache = session.userCache();
+ // if (userCache != null) {
+ // userCache.evict(realm, user);
+ // }
runJobInTransaction(session.getKeycloakSessionFactory(), new KeycloakSessionTask() {
@Override
@@ -726,19 +728,19 @@ public class UserStorageManager implements UserProvider, OnUserCache, OnCreateCo
localStorage().unlinkUsers(realm, storageProviderId);
}
- @Override
- public void onCache(RealmModel realm, CachedUserModel user, UserModel delegate) {
- if (StorageId.isLocalStorage(user)) {
- if (session.userLocalStorage() instanceof OnUserCache) {
- ((OnUserCache)session.userLocalStorage()).onCache(realm, user, delegate);
- }
- } else {
- Object provider = getStorageProvider(session, realm, StorageId.resolveProviderId(user));
- if (provider != null && provider instanceof OnUserCache) {
- ((OnUserCache)provider).onCache(realm, user, delegate);
- }
- }
- }
+ // @Override
+ // public void onCache(RealmModel realm, CachedUserModel user, UserModel delegate) {
+ // if (StorageId.isLocalStorage(user)) {
+ // if (session.userLocalStorage() instanceof OnUserCache) {
+ // ((OnUserCache)session.userLocalStorage()).onCache(realm, user, delegate);
+ // }
+ // } else {
+ // Object provider = getStorageProvider(session, realm, StorageId.resolveProviderId(user));
+ // if (provider != null && provider instanceof OnUserCache) {
+ // ((OnUserCache)provider).onCache(realm, user, delegate);
+ // }
+ // }
+ // }
@Override
public void close() {
diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMultipleAttributesTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMultipleAttributesTest.java
index a465799..1a15178 100755
--- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMultipleAttributesTest.java
+++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPMultipleAttributesTest.java
@@ -1,247 +1,247 @@
-/*
- * Copyright 2017 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.testsuite.federation.ldap;
-
-import org.jboss.arquillian.container.test.api.Deployment;
-import org.jboss.arquillian.container.test.api.TargetsContainer;
-import org.jboss.shrinkwrap.api.spec.WebArchive;
-import org.junit.Assert;
-import org.junit.ClassRule;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.runners.MethodSorters;
-import org.keycloak.admin.client.resource.UserResource;
-import org.keycloak.models.ClientModel;
-import org.keycloak.models.LDAPConstants;
-import org.keycloak.models.RealmModel;
-import org.keycloak.models.UserModel;
-import org.keycloak.models.utils.KeycloakModelUtils;
-import org.keycloak.protocol.oidc.OIDCLoginProtocol;
-import org.keycloak.protocol.oidc.mappers.UserAttributeMapper;
-import org.keycloak.representations.IDToken;
-import org.keycloak.storage.ldap.LDAPStorageProvider;
-import org.keycloak.storage.ldap.idm.model.LDAPObject;
-import org.keycloak.testsuite.runonserver.RunOnServerDeployment;
-import org.keycloak.testsuite.util.LDAPRule;
-import org.keycloak.testsuite.util.LDAPTestConfiguration;
-import org.keycloak.testsuite.util.LDAPTestUtils;
-import org.keycloak.testsuite.util.OAuthClient;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.LinkedHashSet;
-import java.util.LinkedList;
-import java.util.List;
-
-import static org.keycloak.testsuite.arquillian.DeploymentTargetModifier.AUTH_SERVER_CURRENT;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class LDAPMultipleAttributesTest extends AbstractLDAPTest {
-
-
- // Skip this test on MSAD due to lack of supported user multivalued attributes
- @ClassRule
- public static LDAPRule ldapRule = new LDAPRule()
- .assumeTrue((LDAPTestConfiguration ldapConfig) -> {
-
- String vendor = ldapConfig.getLDAPConfig().get(LDAPConstants.VENDOR);
- return !LDAPConstants.VENDOR_ACTIVE_DIRECTORY.equals(vendor);
-
- });
-
-
- @Deployment
- @TargetsContainer(AUTH_SERVER_CURRENT)
- public static WebArchive deploy() {
- return RunOnServerDeployment.create(UserResource.class, AbstractLDAPTest.class)
- .addPackages(true,
- "org.keycloak.testsuite",
- "org.keycloak.testsuite.federation.ldap");
- }
-
- @Override
- protected LDAPRule getLDAPRule() {
- return ldapRule;
- }
-
-
- @Override
- protected void afterImportTestRealm() {
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- LDAPTestUtils.addZipCodeLDAPMapper(appRealm, ctx.getLdapModel());
- LDAPTestUtils.addUserAttributeMapper(appRealm, ctx.getLdapModel(), "streetMapper", "street", LDAPConstants.STREET);
-
- // Remove current users and add default users
- LDAPStorageProvider ldapFedProvider = LDAPTestUtils.getLdapProvider(session, ctx.getLdapModel());
- LDAPTestUtils.removeAllLDAPUsers(ldapFedProvider, appRealm);
-
- LDAPObject james = LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "jbrown", "James", "Brown", "jbrown@keycloak.org", null, "88441");
- LDAPTestUtils.updateLDAPPassword(ldapFedProvider, james, "Password1");
-
- // User for testing duplicating surname and postalCode
- LDAPObject bruce = LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "bwilson", "Bruce", "Wilson", "bwilson@keycloak.org", "Elm 5", "88441", "77332");
- bruce.setAttribute("sn", new LinkedHashSet<>(Arrays.asList("Wilson", "Schneider")));
- ldapFedProvider.getLdapIdentityStore().update(bruce);
- LDAPTestUtils.updateLDAPPassword(ldapFedProvider, bruce, "Password1");
-
- // Create ldap-portal client
- ClientModel ldapClient = KeycloakModelUtils.createClient(appRealm, "ldap-portal");
- ldapClient.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
- ldapClient.addRedirectUri("/ldap-portal");
- ldapClient.addRedirectUri("/ldap-portal/*");
- ldapClient.setManagementUrl("/ldap-portal");
- ldapClient.addProtocolMapper(UserAttributeMapper.createClaimMapper("postalCode", "postal_code", "postal_code", "String", true, true, true));
- ldapClient.addProtocolMapper(UserAttributeMapper.createClaimMapper("street", "street", "street", "String", true, true, false));
- ldapClient.addScopeMapping(appRealm.getRole("user"));
- ldapClient.setSecret("password");
- });
- }
-
-
- @Test
- public void testUserImport() {
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- session.userCache().clear();
- RealmModel appRealm = ctx.getRealm();
-
- // Test user imported in local storage now
- UserModel user = session.users().getUserByUsername("jbrown", appRealm);
- Assert.assertNotNull(session.userLocalStorage().getUserById(user.getId(), appRealm));
- LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "jbrown", "James", "Brown", "jbrown@keycloak.org", "88441");
- });
- }
-
-
- @Test
- public void testModel() {
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- session.userCache().clear();
- RealmModel appRealm = ctx.getRealm();
-
- UserModel user = session.users().getUserByUsername("bwilson", appRealm);
- Assert.assertEquals("bwilson@keycloak.org", user.getEmail());
- Assert.assertEquals("Bruce", user.getFirstName());
-
- // There are 2 lastnames in ldif
- Assert.assertTrue("Wilson".equals(user.getLastName()) || "Schneider".equals(user.getLastName()));
-
- // Actually there are 2 postalCodes
- List<String> postalCodes = user.getAttribute("postal_code");
- assertPostalCodes(postalCodes, "88441", "77332");
- List<String> tmp = new LinkedList<>();
- tmp.addAll(postalCodes);
- postalCodes = tmp;
- postalCodes.remove("77332");
- user.setAttribute("postal_code", postalCodes);
-
- });
-
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- UserModel user = session.users().getUserByUsername("bwilson", appRealm);
- List<String> postalCodes = user.getAttribute("postal_code");
- assertPostalCodes(postalCodes, "88441");
- List<String> tmp = new LinkedList<>();
- tmp.addAll(postalCodes);
- postalCodes = tmp;
- postalCodes.add("77332");
- user.setAttribute("postal_code", postalCodes);
- });
-
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- UserModel user = session.users().getUserByUsername("bwilson", appRealm);
- assertPostalCodes(user.getAttribute("postal_code"), "88441", "77332");
- });
- }
-
- private static void assertPostalCodes(List<String> postalCodes, String... expectedPostalCodes) {
- if (expectedPostalCodes == null && postalCodes.isEmpty()) {
- return;
- }
-
-
- Assert.assertEquals(expectedPostalCodes.length, postalCodes.size());
- for (String expected : expectedPostalCodes) {
- if (!postalCodes.contains(expected)) {
- Assert.fail("postalCode '" + expected + "' not in postalCodes: " + postalCodes);
- }
- }
- }
-
- @Test
- public void ldapPortalEndToEndTest() {
- // Login as bwilson
- oauth.clientId("ldap-portal");
- oauth.redirectUri("/ldap-portal");
-
- loginPage.open();
- loginPage.login("bwilson", "Password1");
-
- String code = new OAuthClient.AuthorizationEndpointResponse(oauth).getCode();
- OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
-
- Assert.assertEquals(200, response.getStatusCode());
- IDToken idToken = oauth.verifyIDToken(response.getIdToken());
-
- Assert.assertEquals("Bruce Wilson", idToken.getName());
- Assert.assertEquals("Elm 5", idToken.getOtherClaims().get("street"));
- Collection postalCodes = (Collection) idToken.getOtherClaims().get("postal_code");
- Assert.assertEquals(2, postalCodes.size());
- Assert.assertTrue(postalCodes.contains("88441"));
- Assert.assertTrue(postalCodes.contains("77332"));
-
- oauth.doLogout(response.getRefreshToken(), "password");
-
- // Login as jbrown
- loginPage.open();
- loginPage.login("jbrown", "Password1");
-
- code = new OAuthClient.AuthorizationEndpointResponse(oauth).getCode();
- response = oauth.doAccessTokenRequest(code, "password");
-
- org.keycloak.testsuite.Assert.assertEquals(200, response.getStatusCode());
- idToken = oauth.verifyIDToken(response.getIdToken());
-
- Assert.assertEquals("James Brown", idToken.getName());
- Assert.assertNull(idToken.getOtherClaims().get("street"));
- postalCodes = (Collection) idToken.getOtherClaims().get("postal_code");
- Assert.assertEquals(1, postalCodes.size());
- Assert.assertTrue(postalCodes.contains("88441"));
- Assert.assertFalse(postalCodes.contains("77332"));
-
- oauth.doLogout(response.getRefreshToken(), "password");
- }
-
+// /*
+// * Copyright 2017 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.testsuite.federation.ldap;
+
+// import org.jboss.arquillian.container.test.api.Deployment;
+// import org.jboss.arquillian.container.test.api.TargetsContainer;
+// import org.jboss.shrinkwrap.api.spec.WebArchive;
+// import org.junit.Assert;
+// import org.junit.ClassRule;
+// import org.junit.FixMethodOrder;
+// import org.junit.Test;
+// import org.junit.runners.MethodSorters;
+// import org.keycloak.admin.client.resource.UserResource;
+// import org.keycloak.models.ClientModel;
+// import org.keycloak.models.LDAPConstants;
+// import org.keycloak.models.RealmModel;
+// import org.keycloak.models.UserModel;
+// import org.keycloak.models.utils.KeycloakModelUtils;
+// import org.keycloak.protocol.oidc.OIDCLoginProtocol;
+// import org.keycloak.protocol.oidc.mappers.UserAttributeMapper;
+// import org.keycloak.representations.IDToken;
+// import org.keycloak.storage.ldap.LDAPStorageProvider;
+// import org.keycloak.storage.ldap.idm.model.LDAPObject;
+// import org.keycloak.testsuite.runonserver.RunOnServerDeployment;
+// import org.keycloak.testsuite.util.LDAPRule;
+// import org.keycloak.testsuite.util.LDAPTestConfiguration;
+// import org.keycloak.testsuite.util.LDAPTestUtils;
+// import org.keycloak.testsuite.util.OAuthClient;
+
+// import java.util.Arrays;
+// import java.util.Collection;
+// import java.util.LinkedHashSet;
+// import java.util.LinkedList;
+// import java.util.List;
+
+// import static org.keycloak.testsuite.arquillian.DeploymentTargetModifier.AUTH_SERVER_CURRENT;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @FixMethodOrder(MethodSorters.NAME_ASCENDING)
+// public class LDAPMultipleAttributesTest extends AbstractLDAPTest {
+
+
+// // Skip this test on MSAD due to lack of supported user multivalued attributes
+// @ClassRule
+// public static LDAPRule ldapRule = new LDAPRule()
+// .assumeTrue((LDAPTestConfiguration ldapConfig) -> {
+
+// String vendor = ldapConfig.getLDAPConfig().get(LDAPConstants.VENDOR);
+// return !LDAPConstants.VENDOR_ACTIVE_DIRECTORY.equals(vendor);
+
+// });
+
+
+// @Deployment
+// @TargetsContainer(AUTH_SERVER_CURRENT)
+// public static WebArchive deploy() {
+// return RunOnServerDeployment.create(UserResource.class, AbstractLDAPTest.class)
+// .addPackages(true,
+// "org.keycloak.testsuite",
+// "org.keycloak.testsuite.federation.ldap");
+// }
+
+// @Override
+// protected LDAPRule getLDAPRule() {
+// return ldapRule;
+// }
+
+
+// @Override
+// protected void afterImportTestRealm() {
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// LDAPTestUtils.addZipCodeLDAPMapper(appRealm, ctx.getLdapModel());
+// LDAPTestUtils.addUserAttributeMapper(appRealm, ctx.getLdapModel(), "streetMapper", "street", LDAPConstants.STREET);
+
+// // Remove current users and add default users
+// LDAPStorageProvider ldapFedProvider = LDAPTestUtils.getLdapProvider(session, ctx.getLdapModel());
+// LDAPTestUtils.removeAllLDAPUsers(ldapFedProvider, appRealm);
+
+// LDAPObject james = LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "jbrown", "James", "Brown", "jbrown@keycloak.org", null, "88441");
+// LDAPTestUtils.updateLDAPPassword(ldapFedProvider, james, "Password1");
+
+// // User for testing duplicating surname and postalCode
+// LDAPObject bruce = LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "bwilson", "Bruce", "Wilson", "bwilson@keycloak.org", "Elm 5", "88441", "77332");
+// bruce.setAttribute("sn", new LinkedHashSet<>(Arrays.asList("Wilson", "Schneider")));
+// ldapFedProvider.getLdapIdentityStore().update(bruce);
+// LDAPTestUtils.updateLDAPPassword(ldapFedProvider, bruce, "Password1");
+
+// // Create ldap-portal client
+// ClientModel ldapClient = KeycloakModelUtils.createClient(appRealm, "ldap-portal");
+// ldapClient.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
+// ldapClient.addRedirectUri("/ldap-portal");
+// ldapClient.addRedirectUri("/ldap-portal/*");
+// ldapClient.setManagementUrl("/ldap-portal");
+// ldapClient.addProtocolMapper(UserAttributeMapper.createClaimMapper("postalCode", "postal_code", "postal_code", "String", true, true, true));
+// ldapClient.addProtocolMapper(UserAttributeMapper.createClaimMapper("street", "street", "street", "String", true, true, false));
+// ldapClient.addScopeMapping(appRealm.getRole("user"));
+// ldapClient.setSecret("password");
+// });
+// }
+
+
+// @Test
+// public void testUserImport() {
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// session.userCache().clear();
+// RealmModel appRealm = ctx.getRealm();
+
+// // Test user imported in local storage now
+// UserModel user = session.users().getUserByUsername("jbrown", appRealm);
+// Assert.assertNotNull(session.userLocalStorage().getUserById(user.getId(), appRealm));
+// LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "jbrown", "James", "Brown", "jbrown@keycloak.org", "88441");
+// });
+// }
+
+
+// @Test
+// public void testModel() {
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// session.userCache().clear();
+// RealmModel appRealm = ctx.getRealm();
+
+// UserModel user = session.users().getUserByUsername("bwilson", appRealm);
+// Assert.assertEquals("bwilson@keycloak.org", user.getEmail());
+// Assert.assertEquals("Bruce", user.getFirstName());
+
+// // There are 2 lastnames in ldif
+// Assert.assertTrue("Wilson".equals(user.getLastName()) || "Schneider".equals(user.getLastName()));
+
+// // Actually there are 2 postalCodes
+// List<String> postalCodes = user.getAttribute("postal_code");
+// assertPostalCodes(postalCodes, "88441", "77332");
+// List<String> tmp = new LinkedList<>();
+// tmp.addAll(postalCodes);
+// postalCodes = tmp;
+// postalCodes.remove("77332");
+// user.setAttribute("postal_code", postalCodes);
+
+// });
+
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// UserModel user = session.users().getUserByUsername("bwilson", appRealm);
+// List<String> postalCodes = user.getAttribute("postal_code");
+// assertPostalCodes(postalCodes, "88441");
+// List<String> tmp = new LinkedList<>();
+// tmp.addAll(postalCodes);
+// postalCodes = tmp;
+// postalCodes.add("77332");
+// user.setAttribute("postal_code", postalCodes);
+// });
+
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// UserModel user = session.users().getUserByUsername("bwilson", appRealm);
+// assertPostalCodes(user.getAttribute("postal_code"), "88441", "77332");
+// });
+// }
+
+// private static void assertPostalCodes(List<String> postalCodes, String... expectedPostalCodes) {
+// if (expectedPostalCodes == null && postalCodes.isEmpty()) {
+// return;
+// }
+
+
+// Assert.assertEquals(expectedPostalCodes.length, postalCodes.size());
+// for (String expected : expectedPostalCodes) {
+// if (!postalCodes.contains(expected)) {
+// Assert.fail("postalCode '" + expected + "' not in postalCodes: " + postalCodes);
+// }
+// }
+// }
+
+// @Test
+// public void ldapPortalEndToEndTest() {
+// // Login as bwilson
+// oauth.clientId("ldap-portal");
+// oauth.redirectUri("/ldap-portal");
+
+// loginPage.open();
+// loginPage.login("bwilson", "Password1");
+
+// String code = new OAuthClient.AuthorizationEndpointResponse(oauth).getCode();
+// OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
+
+// Assert.assertEquals(200, response.getStatusCode());
+// IDToken idToken = oauth.verifyIDToken(response.getIdToken());
+
+// Assert.assertEquals("Bruce Wilson", idToken.getName());
+// Assert.assertEquals("Elm 5", idToken.getOtherClaims().get("street"));
+// Collection postalCodes = (Collection) idToken.getOtherClaims().get("postal_code");
+// Assert.assertEquals(2, postalCodes.size());
+// Assert.assertTrue(postalCodes.contains("88441"));
+// Assert.assertTrue(postalCodes.contains("77332"));
+
+// oauth.doLogout(response.getRefreshToken(), "password");
+
+// // Login as jbrown
+// loginPage.open();
+// loginPage.login("jbrown", "Password1");
+
+// code = new OAuthClient.AuthorizationEndpointResponse(oauth).getCode();
+// response = oauth.doAccessTokenRequest(code, "password");
+
+// org.keycloak.testsuite.Assert.assertEquals(200, response.getStatusCode());
+// idToken = oauth.verifyIDToken(response.getIdToken());
+
+// Assert.assertEquals("James Brown", idToken.getName());
+// Assert.assertNull(idToken.getOtherClaims().get("street"));
+// postalCodes = (Collection) idToken.getOtherClaims().get("postal_code");
+// Assert.assertEquals(1, postalCodes.size());
+// Assert.assertTrue(postalCodes.contains("88441"));
+// Assert.assertFalse(postalCodes.contains("77332"));
+
+// oauth.doLogout(response.getRefreshToken(), "password");
+// }
+
-
-}
+
+// }
diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPProvidersIntegrationTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPProvidersIntegrationTest.java
index 953b89b..2d6992c 100755
--- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPProvidersIntegrationTest.java
+++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPProvidersIntegrationTest.java
@@ -1,1117 +1,1117 @@
-/*
- * Copyright 2017 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.testsuite.federation.ldap;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.keycloak.testsuite.arquillian.DeploymentTargetModifier.AUTH_SERVER_CURRENT;
-
-import java.util.List;
-import java.util.Map;
-
-import javax.naming.AuthenticationException;
-import javax.ws.rs.core.Response;
-
-import org.jboss.arquillian.container.test.api.Deployment;
-import org.jboss.arquillian.container.test.api.TargetsContainer;
-import org.jboss.shrinkwrap.api.spec.WebArchive;
-import org.junit.Assert;
-import org.junit.ClassRule;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.runners.MethodSorters;
-import org.keycloak.OAuth2Constants;
-import org.keycloak.admin.client.resource.UserResource;
-import org.keycloak.component.ComponentModel;
-import org.keycloak.credential.CredentialModel;
-import org.keycloak.models.GroupModel;
-import org.keycloak.models.LDAPConstants;
-import org.keycloak.models.ModelException;
-import org.keycloak.models.RealmModel;
-import org.keycloak.models.RoleModel;
-import org.keycloak.models.UserCredentialModel;
-import org.keycloak.models.UserModel;
-import org.keycloak.models.cache.CachedUserModel;
-import org.keycloak.models.utils.KeycloakModelUtils;
-import org.keycloak.models.utils.ModelToRepresentation;
-import org.keycloak.representations.AccessToken;
-import org.keycloak.representations.idm.ComponentRepresentation;
-import org.keycloak.representations.idm.UserRepresentation;
-import org.keycloak.services.managers.RealmManager;
-import org.keycloak.storage.ReadOnlyException;
-import org.keycloak.storage.StorageId;
-import org.keycloak.storage.UserStorageProvider;
-import org.keycloak.storage.UserStorageProviderModel;
-import org.keycloak.storage.ldap.LDAPConfig;
-import org.keycloak.storage.ldap.LDAPStorageProvider;
-import org.keycloak.storage.ldap.idm.model.LDAPObject;
-import org.keycloak.storage.ldap.mappers.FullNameLDAPStorageMapper;
-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.HardcodedLDAPGroupStorageMapper;
-import org.keycloak.storage.ldap.mappers.HardcodedLDAPGroupStorageMapperFactory;
-import org.keycloak.storage.ldap.mappers.HardcodedLDAPRoleStorageMapper;
-import org.keycloak.storage.ldap.mappers.HardcodedLDAPRoleStorageMapperFactory;
-import org.keycloak.storage.ldap.mappers.LDAPStorageMapper;
-import org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapper;
-import org.keycloak.testsuite.AbstractAuthTest;
-import org.keycloak.testsuite.admin.ApiUtil;
-import org.keycloak.testsuite.pages.AppPage;
-import org.keycloak.testsuite.runonserver.RunOnServerDeployment;
-import org.keycloak.testsuite.util.LDAPRule;
-import org.keycloak.testsuite.util.LDAPTestUtils;
-import org.keycloak.testsuite.util.OAuthClient;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class LDAPProvidersIntegrationTest extends AbstractLDAPTest {
-
- @ClassRule
- public static LDAPRule ldapRule = new LDAPRule();
-
- @Deployment
- @TargetsContainer(AUTH_SERVER_CURRENT)
- public static WebArchive deploy() {
- return RunOnServerDeployment.create(UserResource.class, AbstractLDAPTest.class)
- .addPackages(true,
- "org.keycloak.testsuite",
- "org.keycloak.testsuite.federation.ldap");
- }
-
-
- @Override
- protected LDAPRule getLDAPRule() {
- return ldapRule;
- }
-
- @Override
- protected void afterImportTestRealm() {
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- LDAPTestUtils.addLocalUser(session, appRealm, "marykeycloak", "mary@test.com", "password-app");
-
- LDAPTestUtils.addZipCodeLDAPMapper(appRealm, ctx.getLdapModel());
-
- // Delete all LDAP users and add some new for testing
- LDAPTestUtils.removeAllLDAPUsers(ctx.getLdapProvider(), appRealm);
-
- LDAPObject john = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "johnkeycloak", "John", "Doe", "john@email.org", null, "1234");
- LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), john, "Password1");
-
- LDAPObject existing = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "existing", "Existing", "Foo", "existing@email.org", null, "5678");
-
- appRealm.getClientByClientId("test-app").setDirectAccessGrantsEnabled(true);
-
- });
- }
-
-
-
-// @Test
-// @Ignore
-// public void runit() throws Exception {
-// Thread.sleep(10000000);
-//
-// }
-
- /**
- * KEYCLOAK-3986
- *
- */
- @Test
- public void testSyncRegistrationOff() {
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- ctx.getLdapModel().put(LDAPConstants.SYNC_REGISTRATIONS, "false");
- ctx.getRealm().updateComponent(ctx.getLdapModel());
- });
-
- UserRepresentation newUser1 = AbstractAuthTest.createUserRepresentation("newUser1", "newUser1@email.cz", null, null, true);
- Response resp = testRealm().users().create(newUser1);
- String userId = ApiUtil.getCreatedId(resp);
- resp.close();
-
- testRealm().users().get(userId).toRepresentation();
- Assert.assertTrue(StorageId.isLocalStorage(userId));
- Assert.assertNull(newUser1.getFederationLink());
-
- // Revert
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- ctx.getLdapModel().getConfig().putSingle(LDAPConstants.SYNC_REGISTRATIONS, "true");
- ctx.getRealm().updateComponent(ctx.getLdapModel());
- });
- }
-
-
- @Test
- public void testRemoveImportedUsers() {
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- UserModel user = session.users().getUserByUsername("johnkeycloak", ctx.getRealm());
- Assert.assertEquals(ctx.getLdapModel().getId(), user.getFederationLink());
- });
-
- adminClient.realm("test").userStorage().removeImportedUsers(ldapModelId);
-
- testingClient.server().run(session -> {
- RealmManager manager = new RealmManager(session);
- RealmModel appRealm = manager.getRealm("test");
- UserModel user = session.userLocalStorage().getUserByUsername("johnkeycloak", appRealm);
- Assert.assertNull(user);
- });
- }
-
- // test name prefixed with zz to make sure it runs last as we are unlinking imported users
- @Test
- public void zzTestUnlinkUsers() {
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- UserModel user = session.users().getUserByUsername("johnkeycloak", ctx.getRealm());
- Assert.assertEquals(ctx.getLdapModel().getId(), user.getFederationLink());
- });
-
- adminClient.realm("test").userStorage().unlink(ldapModelId);
-
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- UserModel user = session.users().getUserByUsername("johnkeycloak", ctx.getRealm());
- Assert.assertNotNull(user);
- Assert.assertNull(user.getFederationLink());
- });
- }
-
- @Test
- public void caseInSensitiveImport() {
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- LDAPObject jbrown2 = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "JBrown2", "John", "Brown2", "jbrown2@email.org", null, "1234");
- LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), jbrown2, "Password1");
- LDAPObject jbrown3 = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "jbrown3", "John", "Brown3", "JBrown3@email.org", null, "1234");
- LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), jbrown3, "Password1");
- });
-
- loginSuccessAndLogout("jbrown2", "Password1");
- loginSuccessAndLogout("JBrown2", "Password1");
- loginSuccessAndLogout("jbrown2@email.org", "Password1");
- loginSuccessAndLogout("JBrown2@email.org", "Password1");
-
- loginSuccessAndLogout("jbrown3", "Password1");
- loginSuccessAndLogout("JBrown3", "Password1");
- loginSuccessAndLogout("jbrown3@email.org", "Password1");
- loginSuccessAndLogout("JBrown3@email.org", "Password1");
- }
-
- private void loginSuccessAndLogout(String username, String password) {
- loginPage.open();
- loginPage.login(username, password);
- Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
- Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
- oauth.openLogout();
- }
-
- @Test
- public void caseInsensitiveSearch() {
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
-
- LDAPObject jbrown4 = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "JBrown4", "John", "Brown4", "jbrown4@email.org", null, "1234");
- LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), jbrown4, "Password1");
- LDAPObject jbrown5 = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "jbrown5", "John", "Brown5", "JBrown5@Email.org", null, "1234");
- LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), jbrown5, "Password1");
- });
-
- // search by username
- List<UserRepresentation> users = testRealm().users().search("JBROwn4", 0, 10);
- UserRepresentation user4 = users.get(0);
- Assert.assertEquals("jbrown4", user4.getUsername());
- Assert.assertEquals("jbrown4@email.org", user4.getEmail());
-
- // search by email
- users = testRealm().users().search("JBROwn5@eMAil.org", 0, 10);
- Assert.assertEquals(1, users.size());
- UserRepresentation user5 = users.get(0);
- Assert.assertEquals("jbrown5", user5.getUsername());
- Assert.assertEquals("jbrown5@email.org", user5.getEmail());
- }
-
- @Test
- public void deleteFederationLink() throws Exception {
- // KEYCLOAK-4789: Login in client, which requires consent
- oauth.clientId("third-party");
- loginPage.open();
- loginPage.login("johnkeycloak", "Password1");
-
- grantPage.assertCurrent();
- grantPage.accept();
-
- Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
- Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
-
- ComponentRepresentation ldapRep = testRealm().components().component(ldapModelId).toRepresentation();
- testRealm().components().component(ldapModelId).remove();
-
- // User not available once LDAP provider was removed
- loginPage.open();
- loginPage.login("johnkeycloak", "Password1");
- loginPage.assertCurrent();
-
- Assert.assertEquals("Invalid username or password.", loginPage.getError());
-
- // Re-add LDAP provider
- Map<String, String> cfg = getLDAPRule().getConfig();
- ldapModelId = testingClient.testing().ldap(TEST_REALM_NAME).createLDAPProvider(cfg, isImportEnabled());
-
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
-
- LDAPTestUtils.addZipCodeLDAPMapper(ctx.getRealm(), ctx.getLdapModel());
- });
-
- oauth.clientId("test-app");
-
- loginLdap();
-
- }
-
- @Test
- public void loginClassic() {
- loginPage.open();
- loginPage.login("marykeycloak", "password-app");
-
- Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
- Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
-
- }
-
- @Test
- public void loginLdap() {
- loginPage.open();
- loginPage.login("johnkeycloak", "Password1");
-
- Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
- Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
-
- profilePage.open();
- Assert.assertEquals("John", profilePage.getFirstName());
- Assert.assertEquals("Doe", profilePage.getLastName());
- Assert.assertEquals("john@email.org", profilePage.getEmail());
- }
-
- @Test
- public void loginLdapWithDirectGrant() throws Exception {
- OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("password", "johnkeycloak", "Password1");
- Assert.assertEquals(200, response.getStatusCode());
- AccessToken accessToken = oauth.verifyToken(response.getAccessToken());
-
- response = oauth.doGrantAccessTokenRequest("password", "johnkeycloak", "");
- Assert.assertEquals(401, response.getStatusCode());
- }
+// /*
+// * Copyright 2017 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.testsuite.federation.ldap;
+
+// import static org.junit.Assert.assertEquals;
+// import static org.junit.Assert.assertNotNull;
+// import static org.keycloak.testsuite.arquillian.DeploymentTargetModifier.AUTH_SERVER_CURRENT;
+
+// import java.util.List;
+// import java.util.Map;
+
+// import javax.naming.AuthenticationException;
+// import javax.ws.rs.core.Response;
+
+// import org.jboss.arquillian.container.test.api.Deployment;
+// import org.jboss.arquillian.container.test.api.TargetsContainer;
+// import org.jboss.shrinkwrap.api.spec.WebArchive;
+// import org.junit.Assert;
+// import org.junit.ClassRule;
+// import org.junit.FixMethodOrder;
+// import org.junit.Test;
+// import org.junit.runners.MethodSorters;
+// import org.keycloak.OAuth2Constants;
+// import org.keycloak.admin.client.resource.UserResource;
+// import org.keycloak.component.ComponentModel;
+// import org.keycloak.credential.CredentialModel;
+// import org.keycloak.models.GroupModel;
+// import org.keycloak.models.LDAPConstants;
+// import org.keycloak.models.ModelException;
+// import org.keycloak.models.RealmModel;
+// import org.keycloak.models.RoleModel;
+// import org.keycloak.models.UserCredentialModel;
+// import org.keycloak.models.UserModel;
+// import org.keycloak.models.cache.CachedUserModel;
+// import org.keycloak.models.utils.KeycloakModelUtils;
+// import org.keycloak.models.utils.ModelToRepresentation;
+// import org.keycloak.representations.AccessToken;
+// import org.keycloak.representations.idm.ComponentRepresentation;
+// import org.keycloak.representations.idm.UserRepresentation;
+// import org.keycloak.services.managers.RealmManager;
+// import org.keycloak.storage.ReadOnlyException;
+// import org.keycloak.storage.StorageId;
+// import org.keycloak.storage.UserStorageProvider;
+// import org.keycloak.storage.UserStorageProviderModel;
+// import org.keycloak.storage.ldap.LDAPConfig;
+// import org.keycloak.storage.ldap.LDAPStorageProvider;
+// import org.keycloak.storage.ldap.idm.model.LDAPObject;
+// import org.keycloak.storage.ldap.mappers.FullNameLDAPStorageMapper;
+// 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.HardcodedLDAPGroupStorageMapper;
+// import org.keycloak.storage.ldap.mappers.HardcodedLDAPGroupStorageMapperFactory;
+// import org.keycloak.storage.ldap.mappers.HardcodedLDAPRoleStorageMapper;
+// import org.keycloak.storage.ldap.mappers.HardcodedLDAPRoleStorageMapperFactory;
+// import org.keycloak.storage.ldap.mappers.LDAPStorageMapper;
+// import org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapper;
+// import org.keycloak.testsuite.AbstractAuthTest;
+// import org.keycloak.testsuite.admin.ApiUtil;
+// import org.keycloak.testsuite.pages.AppPage;
+// import org.keycloak.testsuite.runonserver.RunOnServerDeployment;
+// import org.keycloak.testsuite.util.LDAPRule;
+// import org.keycloak.testsuite.util.LDAPTestUtils;
+// import org.keycloak.testsuite.util.OAuthClient;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @FixMethodOrder(MethodSorters.NAME_ASCENDING)
+// public class LDAPProvidersIntegrationTest extends AbstractLDAPTest {
+
+// @ClassRule
+// public static LDAPRule ldapRule = new LDAPRule();
+
+// @Deployment
+// @TargetsContainer(AUTH_SERVER_CURRENT)
+// public static WebArchive deploy() {
+// return RunOnServerDeployment.create(UserResource.class, AbstractLDAPTest.class)
+// .addPackages(true,
+// "org.keycloak.testsuite",
+// "org.keycloak.testsuite.federation.ldap");
+// }
+
+
+// @Override
+// protected LDAPRule getLDAPRule() {
+// return ldapRule;
+// }
+
+// @Override
+// protected void afterImportTestRealm() {
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// LDAPTestUtils.addLocalUser(session, appRealm, "marykeycloak", "mary@test.com", "password-app");
+
+// LDAPTestUtils.addZipCodeLDAPMapper(appRealm, ctx.getLdapModel());
+
+// // Delete all LDAP users and add some new for testing
+// LDAPTestUtils.removeAllLDAPUsers(ctx.getLdapProvider(), appRealm);
+
+// LDAPObject john = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "johnkeycloak", "John", "Doe", "john@email.org", null, "1234");
+// LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), john, "Password1");
+
+// LDAPObject existing = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "existing", "Existing", "Foo", "existing@email.org", null, "5678");
+
+// appRealm.getClientByClientId("test-app").setDirectAccessGrantsEnabled(true);
+
+// });
+// }
+
+
+
+// // @Test
+// // @Ignore
+// // public void runit() throws Exception {
+// // Thread.sleep(10000000);
+// //
+// // }
+
+// /**
+// * KEYCLOAK-3986
+// *
+// */
+// @Test
+// public void testSyncRegistrationOff() {
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// ctx.getLdapModel().put(LDAPConstants.SYNC_REGISTRATIONS, "false");
+// ctx.getRealm().updateComponent(ctx.getLdapModel());
+// });
+
+// UserRepresentation newUser1 = AbstractAuthTest.createUserRepresentation("newUser1", "newUser1@email.cz", null, null, true);
+// Response resp = testRealm().users().create(newUser1);
+// String userId = ApiUtil.getCreatedId(resp);
+// resp.close();
+
+// testRealm().users().get(userId).toRepresentation();
+// Assert.assertTrue(StorageId.isLocalStorage(userId));
+// Assert.assertNull(newUser1.getFederationLink());
+
+// // Revert
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// ctx.getLdapModel().getConfig().putSingle(LDAPConstants.SYNC_REGISTRATIONS, "true");
+// ctx.getRealm().updateComponent(ctx.getLdapModel());
+// });
+// }
+
+
+// @Test
+// public void testRemoveImportedUsers() {
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// UserModel user = session.users().getUserByUsername("johnkeycloak", ctx.getRealm());
+// Assert.assertEquals(ctx.getLdapModel().getId(), user.getFederationLink());
+// });
+
+// adminClient.realm("test").userStorage().removeImportedUsers(ldapModelId);
+
+// testingClient.server().run(session -> {
+// RealmManager manager = new RealmManager(session);
+// RealmModel appRealm = manager.getRealm("test");
+// UserModel user = session.userLocalStorage().getUserByUsername("johnkeycloak", appRealm);
+// Assert.assertNull(user);
+// });
+// }
+
+// // test name prefixed with zz to make sure it runs last as we are unlinking imported users
+// @Test
+// public void zzTestUnlinkUsers() {
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// UserModel user = session.users().getUserByUsername("johnkeycloak", ctx.getRealm());
+// Assert.assertEquals(ctx.getLdapModel().getId(), user.getFederationLink());
+// });
+
+// adminClient.realm("test").userStorage().unlink(ldapModelId);
+
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// UserModel user = session.users().getUserByUsername("johnkeycloak", ctx.getRealm());
+// Assert.assertNotNull(user);
+// Assert.assertNull(user.getFederationLink());
+// });
+// }
+
+// @Test
+// public void caseInSensitiveImport() {
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// LDAPObject jbrown2 = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "JBrown2", "John", "Brown2", "jbrown2@email.org", null, "1234");
+// LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), jbrown2, "Password1");
+// LDAPObject jbrown3 = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "jbrown3", "John", "Brown3", "JBrown3@email.org", null, "1234");
+// LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), jbrown3, "Password1");
+// });
+
+// loginSuccessAndLogout("jbrown2", "Password1");
+// loginSuccessAndLogout("JBrown2", "Password1");
+// loginSuccessAndLogout("jbrown2@email.org", "Password1");
+// loginSuccessAndLogout("JBrown2@email.org", "Password1");
+
+// loginSuccessAndLogout("jbrown3", "Password1");
+// loginSuccessAndLogout("JBrown3", "Password1");
+// loginSuccessAndLogout("jbrown3@email.org", "Password1");
+// loginSuccessAndLogout("JBrown3@email.org", "Password1");
+// }
+
+// private void loginSuccessAndLogout(String username, String password) {
+// loginPage.open();
+// loginPage.login(username, password);
+// Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
+// Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
+// oauth.openLogout();
+// }
+
+// @Test
+// public void caseInsensitiveSearch() {
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+
+// LDAPObject jbrown4 = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "JBrown4", "John", "Brown4", "jbrown4@email.org", null, "1234");
+// LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), jbrown4, "Password1");
+// LDAPObject jbrown5 = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "jbrown5", "John", "Brown5", "JBrown5@Email.org", null, "1234");
+// LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), jbrown5, "Password1");
+// });
+
+// // search by username
+// List<UserRepresentation> users = testRealm().users().search("JBROwn4", 0, 10);
+// UserRepresentation user4 = users.get(0);
+// Assert.assertEquals("jbrown4", user4.getUsername());
+// Assert.assertEquals("jbrown4@email.org", user4.getEmail());
+
+// // search by email
+// users = testRealm().users().search("JBROwn5@eMAil.org", 0, 10);
+// Assert.assertEquals(1, users.size());
+// UserRepresentation user5 = users.get(0);
+// Assert.assertEquals("jbrown5", user5.getUsername());
+// Assert.assertEquals("jbrown5@email.org", user5.getEmail());
+// }
+
+// @Test
+// public void deleteFederationLink() throws Exception {
+// // KEYCLOAK-4789: Login in client, which requires consent
+// oauth.clientId("third-party");
+// loginPage.open();
+// loginPage.login("johnkeycloak", "Password1");
+
+// grantPage.assertCurrent();
+// grantPage.accept();
+
+// Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
+// Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
+
+// ComponentRepresentation ldapRep = testRealm().components().component(ldapModelId).toRepresentation();
+// testRealm().components().component(ldapModelId).remove();
+
+// // User not available once LDAP provider was removed
+// loginPage.open();
+// loginPage.login("johnkeycloak", "Password1");
+// loginPage.assertCurrent();
+
+// Assert.assertEquals("Invalid username or password.", loginPage.getError());
+
+// // Re-add LDAP provider
+// Map<String, String> cfg = getLDAPRule().getConfig();
+// ldapModelId = testingClient.testing().ldap(TEST_REALM_NAME).createLDAPProvider(cfg, isImportEnabled());
+
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+
+// LDAPTestUtils.addZipCodeLDAPMapper(ctx.getRealm(), ctx.getLdapModel());
+// });
+
+// oauth.clientId("test-app");
+
+// loginLdap();
+
+// }
+
+// @Test
+// public void loginClassic() {
+// loginPage.open();
+// loginPage.login("marykeycloak", "password-app");
+
+// Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
+// Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
+
+// }
+
+// @Test
+// public void loginLdap() {
+// loginPage.open();
+// loginPage.login("johnkeycloak", "Password1");
+
+// Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
+// Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
+
+// profilePage.open();
+// Assert.assertEquals("John", profilePage.getFirstName());
+// Assert.assertEquals("Doe", profilePage.getLastName());
+// Assert.assertEquals("john@email.org", profilePage.getEmail());
+// }
+
+// @Test
+// public void loginLdapWithDirectGrant() throws Exception {
+// OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("password", "johnkeycloak", "Password1");
+// Assert.assertEquals(200, response.getStatusCode());
+// AccessToken accessToken = oauth.verifyToken(response.getAccessToken());
+
+// response = oauth.doGrantAccessTokenRequest("password", "johnkeycloak", "");
+// Assert.assertEquals(401, response.getStatusCode());
+// }
- @Test
- public void loginLdapWithEmail() {
- loginPage.open();
- loginPage.login("john@email.org", "Password1");
+// @Test
+// public void loginLdapWithEmail() {
+// loginPage.open();
+// loginPage.login("john@email.org", "Password1");
- Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
- Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
- }
-
- @Test
- public void loginLdapWithoutPassword() {
- loginPage.open();
- loginPage.login("john@email.org", "");
- Assert.assertEquals("Invalid username or password.", loginPage.getError());
- }
+// Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
+// Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
+// }
+
+// @Test
+// public void loginLdapWithoutPassword() {
+// loginPage.open();
+// loginPage.login("john@email.org", "");
+// Assert.assertEquals("Invalid username or password.", loginPage.getError());
+// }
- @Test
- public void passwordChangeLdap() throws Exception {
- changePasswordPage.open();
- loginPage.login("johnkeycloak", "Password1");
- changePasswordPage.changePassword("Password1", "New-password1", "New-password1");
+// @Test
+// public void passwordChangeLdap() throws Exception {
+// changePasswordPage.open();
+// loginPage.login("johnkeycloak", "Password1");
+// changePasswordPage.changePassword("Password1", "New-password1", "New-password1");
- Assert.assertEquals("Your password has been updated.", profilePage.getSuccess());
+// Assert.assertEquals("Your password has been updated.", profilePage.getSuccess());
- changePasswordPage.logout();
+// changePasswordPage.logout();
- loginPage.open();
- loginPage.login("johnkeycloak", "Bad-password1");
- Assert.assertEquals("Invalid username or password.", loginPage.getError());
+// loginPage.open();
+// loginPage.login("johnkeycloak", "Bad-password1");
+// Assert.assertEquals("Invalid username or password.", loginPage.getError());
- loginPage.open();
- loginPage.login("johnkeycloak", "New-password1");
- Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
+// loginPage.open();
+// loginPage.login("johnkeycloak", "New-password1");
+// Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
- // Change password back to previous value
- changePasswordPage.open();
- changePasswordPage.changePassword("New-password1", "Password1", "Password1");
- Assert.assertEquals("Your password has been updated.", profilePage.getSuccess());
- }
+// // Change password back to previous value
+// changePasswordPage.open();
+// changePasswordPage.changePassword("New-password1", "Password1", "Password1");
+// Assert.assertEquals("Your password has been updated.", profilePage.getSuccess());
+// }
- @Test
- public void registerExistingLdapUser() {
- loginPage.open();
- loginPage.clickRegister();
- registerPage.assertCurrent();
+// @Test
+// public void registerExistingLdapUser() {
+// loginPage.open();
+// loginPage.clickRegister();
+// registerPage.assertCurrent();
- // check existing username
- registerPage.register("firstName", "lastName", "email@mail.cz", "existing", "Password1", "Password1");
- registerPage.assertCurrent();
- Assert.assertEquals("Username already exists.", registerPage.getError());
+// // check existing username
+// registerPage.register("firstName", "lastName", "email@mail.cz", "existing", "Password1", "Password1");
+// registerPage.assertCurrent();
+// Assert.assertEquals("Username already exists.", registerPage.getError());
- // Check existing email
- registerPage.register("firstName", "lastName", "existing@email.org", "nonExisting", "Password1", "Password1");
- registerPage.assertCurrent();
- Assert.assertEquals("Email already exists.", registerPage.getError());
- }
+// // Check existing email
+// registerPage.register("firstName", "lastName", "existing@email.org", "nonExisting", "Password1", "Password1");
+// registerPage.assertCurrent();
+// Assert.assertEquals("Email already exists.", registerPage.getError());
+// }
- //
- // KEYCLOAK-4533
- //
- @Test
- public void testLDAPUserDeletionImport() {
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- LDAPConfig config = ctx.getLdapProvider().getLdapIdentityStore().getConfig();
+// //
+// // KEYCLOAK-4533
+// //
+// @Test
+// public void testLDAPUserDeletionImport() {
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// LDAPConfig config = ctx.getLdapProvider().getLdapIdentityStore().getConfig();
- // Make sure mary is gone
- LDAPTestUtils.removeLDAPUserByUsername(ctx.getLdapProvider(), ctx.getRealm(), config, "maryjane");
+// // Make sure mary is gone
+// LDAPTestUtils.removeLDAPUserByUsername(ctx.getLdapProvider(), ctx.getRealm(), config, "maryjane");
- // Create the user in LDAP and register him
-
- LDAPObject mary = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "maryjane", "mary", "yram", "mj@testing.redhat.cz", null, "12398");
- LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), mary, "Password1");
+// // Create the user in LDAP and register him
+
+// LDAPObject mary = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "maryjane", "mary", "yram", "mj@testing.redhat.cz", null, "12398");
+// LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), mary, "Password1");
- });
-
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- LDAPConfig config = ctx.getLdapProvider().getLdapIdentityStore().getConfig();
-
- // Delete LDAP User
- LDAPTestUtils.removeLDAPUserByUsername(ctx.getLdapProvider(), ctx.getRealm(), config, "maryjane");
-
- // Make sure the deletion took place.
- List<UserModel> deletedUsers = session.users().searchForUser("mary yram", ctx.getRealm());
- Assert.assertTrue(deletedUsers.isEmpty());
+// });
+
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// LDAPConfig config = ctx.getLdapProvider().getLdapIdentityStore().getConfig();
+
+// // Delete LDAP User
+// LDAPTestUtils.removeLDAPUserByUsername(ctx.getLdapProvider(), ctx.getRealm(), config, "maryjane");
+
+// // Make sure the deletion took place.
+// List<UserModel> deletedUsers = session.users().searchForUser("mary yram", ctx.getRealm());
+// Assert.assertTrue(deletedUsers.isEmpty());
- });
- }
+// });
+// }
- @Test
- public void registerUserLdapSuccess() {
- loginPage.open();
- loginPage.clickRegister();
- registerPage.assertCurrent();
+// @Test
+// public void registerUserLdapSuccess() {
+// loginPage.open();
+// loginPage.clickRegister();
+// registerPage.assertCurrent();
- registerPage.register("firstName", "lastName", "email2@check.cz", "registerUserSuccess2", "Password1", "Password1");
- Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
+// registerPage.register("firstName", "lastName", "email2@check.cz", "registerUserSuccess2", "Password1", "Password1");
+// Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
- UserRepresentation user = ApiUtil.findUserByUsername(testRealm(),"registerUserSuccess2");
- Assert.assertNotNull(user);
- assertFederatedUserLink(user);
- Assert.assertEquals("registerusersuccess2", user.getUsername());
- Assert.assertEquals("firstName", user.getFirstName());
- Assert.assertEquals("lastName", user.getLastName());
- Assert.assertTrue(user.isEnabled());
- }
+// UserRepresentation user = ApiUtil.findUserByUsername(testRealm(),"registerUserSuccess2");
+// Assert.assertNotNull(user);
+// assertFederatedUserLink(user);
+// Assert.assertEquals("registerusersuccess2", user.getUsername());
+// Assert.assertEquals("firstName", user.getFirstName());
+// Assert.assertEquals("lastName", user.getLastName());
+// Assert.assertTrue(user.isEnabled());
+// }
- protected void assertFederatedUserLink(UserRepresentation user) {
- Assert.assertTrue(StorageId.isLocalStorage(user.getId()));
- Assert.assertNotNull(user.getFederationLink());
- Assert.assertEquals(user.getFederationLink(), ldapModelId);
- }
+// protected void assertFederatedUserLink(UserRepresentation user) {
+// Assert.assertTrue(StorageId.isLocalStorage(user.getId()));
+// Assert.assertNotNull(user.getFederationLink());
+// Assert.assertEquals(user.getFederationLink(), ldapModelId);
+// }
- @Test
- public void testCaseSensitiveAttributeName() {
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
+// @Test
+// public void testCaseSensitiveAttributeName() {
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
- ComponentModel ldapModel = LDAPTestUtils.getLdapProviderModel(session, appRealm);
- LDAPStorageProvider ldapFedProvider = LDAPTestUtils.getLdapProvider(session, ldapModel);
- LDAPObject johnZip = LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "johnzip", "John", "Zip", "johnzip@email.org", null, "12398");
+// ComponentModel ldapModel = LDAPTestUtils.getLdapProviderModel(session, appRealm);
+// LDAPStorageProvider ldapFedProvider = LDAPTestUtils.getLdapProvider(session, ldapModel);
+// LDAPObject johnZip = LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "johnzip", "John", "Zip", "johnzip@email.org", null, "12398");
- // Remove default zipcode mapper and add the mapper for "POstalCode" to test case sensitivity
- ComponentModel currentZipMapper = LDAPTestUtils.getSubcomponentByName(appRealm, ldapModel, "zipCodeMapper");
- appRealm.removeComponent(currentZipMapper);
- LDAPTestUtils.addUserAttributeMapper(appRealm, ldapModel, "zipCodeMapper-cs", "postal_code", "POstalCode");
+// // Remove default zipcode mapper and add the mapper for "POstalCode" to test case sensitivity
+// ComponentModel currentZipMapper = LDAPTestUtils.getSubcomponentByName(appRealm, ldapModel, "zipCodeMapper");
+// appRealm.removeComponent(currentZipMapper);
+// LDAPTestUtils.addUserAttributeMapper(appRealm, ldapModel, "zipCodeMapper-cs", "postal_code", "POstalCode");
- // Fetch user from LDAP and check that postalCode is filled
- UserModel user = session.users().getUserByUsername("johnzip", appRealm);
- String postalCode = user.getFirstAttribute("postal_code");
- Assert.assertEquals("12398", postalCode);
+// // Fetch user from LDAP and check that postalCode is filled
+// UserModel user = session.users().getUserByUsername("johnzip", appRealm);
+// String postalCode = user.getFirstAttribute("postal_code");
+// Assert.assertEquals("12398", postalCode);
- });
- }
+// });
+// }
- @Test
- public void testCommaInUsername() {
- Boolean skipTest = testingClient.server().fetch(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
+// @Test
+// public void testCommaInUsername() {
+// Boolean skipTest = testingClient.server().fetch(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
- boolean skip = false;
+// boolean skip = false;
- // Workaround as comma is not allowed in sAMAccountName on active directory. So we will skip the test for this configuration
- LDAPConfig config = ctx.getLdapProvider().getLdapIdentityStore().getConfig();
- if (config.isActiveDirectory() && config.getUsernameLdapAttribute().equals(LDAPConstants.SAM_ACCOUNT_NAME)) {
- skip = true;
- }
+// // Workaround as comma is not allowed in sAMAccountName on active directory. So we will skip the test for this configuration
+// LDAPConfig config = ctx.getLdapProvider().getLdapIdentityStore().getConfig();
+// if (config.isActiveDirectory() && config.getUsernameLdapAttribute().equals(LDAPConstants.SAM_ACCOUNT_NAME)) {
+// skip = true;
+// }
- if (!skip) {
- LDAPObject johnComma = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "john,comma", "John", "Comma", "johncomma@email.org", null, "12387");
- LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), johnComma, "Password1");
+// if (!skip) {
+// LDAPObject johnComma = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "john,comma", "John", "Comma", "johncomma@email.org", null, "12387");
+// LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), johnComma, "Password1");
- LDAPObject johnPlus = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "john+plus,comma", "John", "Plus", "johnplus@email.org", null, "12387");
- LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), johnPlus, "Password1");
- }
+// LDAPObject johnPlus = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "john+plus,comma", "John", "Plus", "johnplus@email.org", null, "12387");
+// LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), johnPlus, "Password1");
+// }
- return skip;
+// return skip;
- }, Boolean.class);
+// }, Boolean.class);
- if (!skipTest) {
- // Try to import the user with comma in username into Keycloak
- loginSuccessAndLogout("john,comma", "Password1");
- loginSuccessAndLogout("john+plus,comma", "Password1");
- }
- }
+// if (!skipTest) {
+// // Try to import the user with comma in username into Keycloak
+// loginSuccessAndLogout("john,comma", "Password1");
+// loginSuccessAndLogout("john+plus,comma", "Password1");
+// }
+// }
- // TODO: Rather separate test class for fullNameMapper to better test all the possibilities
- @Test
- public void testFullNameMapper() {
+// // TODO: Rather separate test class for fullNameMapper to better test all the possibilities
+// @Test
+// public void testFullNameMapper() {
- ComponentRepresentation firstNameMapperRep = testingClient.server().fetch(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
+// ComponentRepresentation firstNameMapperRep = testingClient.server().fetch(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
- // assert that user "fullnameUser" is not in local DB
- Assert.assertNull(session.users().getUserByUsername("fullname", appRealm));
-
- // Add the user with some fullName into LDAP directly. Ensure that fullName is saved into "cn" attribute in LDAP (currently mapped to model firstName)
- ComponentModel ldapModel = LDAPTestUtils.getLdapProviderModel(session, appRealm);
- LDAPStorageProvider ldapFedProvider = LDAPTestUtils.getLdapProvider(session, ldapModel);
- LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "fullname", "James Dee", "Dee", "fullname@email.org", null, "4578");
-
- // add fullname mapper to the provider and remove "firstNameMapper". For this test, we will simply map full name to the LDAP attribute, which was before firstName ( "givenName" on active directory, "cn" on other LDAP servers)
- ComponentModel firstNameMapper = LDAPTestUtils.getSubcomponentByName(appRealm, ldapModel, "first name");
- String ldapFirstNameAttributeName = firstNameMapper.getConfig().getFirst(UserAttributeLDAPStorageMapper.LDAP_ATTRIBUTE);
- appRealm.removeComponent(firstNameMapper);
-
- ComponentRepresentation firstNameMapperRepp = ModelToRepresentation.toRepresentation(session, firstNameMapper, true);
-
- ComponentModel fullNameMapperModel = KeycloakModelUtils.createComponentModel("full name", ldapModel.getId(), FullNameLDAPStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(),
- FullNameLDAPStorageMapper.LDAP_FULL_NAME_ATTRIBUTE, ldapFirstNameAttributeName,
- FullNameLDAPStorageMapper.READ_ONLY, "false");
- appRealm.addComponentModel(fullNameMapperModel);
-
- return firstNameMapperRepp;
- }, ComponentRepresentation.class);
-
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
+// // assert that user "fullnameUser" is not in local DB
+// Assert.assertNull(session.users().getUserByUsername("fullname", appRealm));
+
+// // Add the user with some fullName into LDAP directly. Ensure that fullName is saved into "cn" attribute in LDAP (currently mapped to model firstName)
+// ComponentModel ldapModel = LDAPTestUtils.getLdapProviderModel(session, appRealm);
+// LDAPStorageProvider ldapFedProvider = LDAPTestUtils.getLdapProvider(session, ldapModel);
+// LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "fullname", "James Dee", "Dee", "fullname@email.org", null, "4578");
+
+// // add fullname mapper to the provider and remove "firstNameMapper". For this test, we will simply map full name to the LDAP attribute, which was before firstName ( "givenName" on active directory, "cn" on other LDAP servers)
+// ComponentModel firstNameMapper = LDAPTestUtils.getSubcomponentByName(appRealm, ldapModel, "first name");
+// String ldapFirstNameAttributeName = firstNameMapper.getConfig().getFirst(UserAttributeLDAPStorageMapper.LDAP_ATTRIBUTE);
+// appRealm.removeComponent(firstNameMapper);
+
+// ComponentRepresentation firstNameMapperRepp = ModelToRepresentation.toRepresentation(session, firstNameMapper, true);
+
+// ComponentModel fullNameMapperModel = KeycloakModelUtils.createComponentModel("full name", ldapModel.getId(), FullNameLDAPStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(),
+// FullNameLDAPStorageMapper.LDAP_FULL_NAME_ATTRIBUTE, ldapFirstNameAttributeName,
+// FullNameLDAPStorageMapper.READ_ONLY, "false");
+// appRealm.addComponentModel(fullNameMapperModel);
+
+// return firstNameMapperRepp;
+// }, ComponentRepresentation.class);
+
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
- // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName
- LDAPTestAsserts.assertUserImported(session.users(), appRealm, "fullname", "James", "Dee", "fullname@email.org", "4578");
- });
-
- // Assert user will be changed in LDAP too
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- UserModel fullnameUser = session.users().getUserByUsername("fullname", appRealm);
- fullnameUser.setFirstName("James2");
- fullnameUser.setLastName("Dee2");
- });
-
-
- // Assert changed user available in Keycloak
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName
- LDAPTestAsserts.assertUserImported(session.users(), appRealm, "fullname", "James2", "Dee2", "fullname@email.org", "4578");
-
- // Remove "fullnameUser" to assert he is removed from LDAP. Revert mappers to previous state
- UserModel fullnameUser = session.users().getUserByUsername("fullname", appRealm);
- session.users().removeUser(appRealm, fullnameUser);
-
- // Revert mappers
- ComponentModel fullNameMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "full name");
- appRealm.removeComponent(fullNameMapperModel);
- });
-
- firstNameMapperRep.setId(null);
- Response response = testRealm().components().add(firstNameMapperRep);
- Assert.assertEquals(201, response.getStatus());
- response.close();
- }
-
-
- @Test
- public void testHardcodedAttributeMapperTest() throws Exception {
- // Create hardcoded mapper for "description"
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
-
- ComponentModel hardcodedMapperModel = KeycloakModelUtils.createComponentModel("hardcodedAttr-description", ctx.getLdapModel().getId(), HardcodedLDAPAttributeMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(),
- HardcodedLDAPAttributeMapper.LDAP_ATTRIBUTE_NAME, "description",
- HardcodedLDAPAttributeMapper.LDAP_ATTRIBUTE_VALUE, "some-${RANDOM}");
- ctx.getRealm().addComponentModel(hardcodedMapperModel);
- });
-
- // Register new user
- loginPage.open();
- loginPage.clickRegister();
- registerPage.assertCurrent();
-
- registerPage.register("firstName", "lastName", "email34@check.cz", "register123", "Password1", "Password1");
- Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
-
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- // See that user don't yet have any description
- UserModel user = LDAPTestAsserts.assertUserImported(session.users(), appRealm, "register123", "firstName", "lastName", "email34@check.cz", null);
- Assert.assertNull(user.getFirstAttribute("desc"));
- Assert.assertNull(user.getFirstAttribute("description"));
-
- // Remove hardcoded mapper for "description" and create regular userAttribute mapper for description
- ComponentModel hardcodedMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "hardcodedAttr-description");
- appRealm.removeComponent(hardcodedMapperModel);
-
- ComponentModel userAttrMapper = LDAPTestUtils.addUserAttributeMapper(appRealm, ctx.getLdapModel(), "desc-attribute-mapper", "desc", "description");
- userAttrMapper.put(UserAttributeLDAPStorageMapper.ALWAYS_READ_VALUE_FROM_LDAP, "true");
- appRealm.updateComponent(userAttrMapper);
- });
-
- // Check that user has description on him now
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- session.userCache().evict(appRealm, session.users().getUserByUsername("register123", appRealm));
-
- // See that user don't yet have any description
- UserModel user = session.users().getUserByUsername("register123", appRealm);
- Assert.assertNull(user.getFirstAttribute("description"));
- Assert.assertNotNull(user.getFirstAttribute("desc"));
- String desc = user.getFirstAttribute("desc");
- Assert.assertTrue(desc.startsWith("some-"));
- Assert.assertEquals(35, desc.length());
-
- // Remove mapper for "description"
- ComponentModel userAttrMapper = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "desc-attribute-mapper");
- appRealm.removeComponent(userAttrMapper);
- });
- }
-
-
- @Test
- public void testHardcodedRoleMapper() {
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
- RoleModel hardcodedRole = appRealm.addRole("hardcoded-role");
-
- // assert that user "johnkeycloak" doesn't have hardcoded role
- UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm);
- Assert.assertFalse(john.hasRole(hardcodedRole));
-
- ComponentModel hardcodedMapperModel = KeycloakModelUtils.createComponentModel("hardcoded role", ctx.getLdapModel().getId(),
- HardcodedLDAPRoleStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(),
- HardcodedLDAPRoleStorageMapper.ROLE, "hardcoded-role");
- appRealm.addComponentModel(hardcodedMapperModel);
- });
-
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- RoleModel hardcodedRole = appRealm.getRole("hardcoded-role");
-
- // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName
- UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm);
- Assert.assertTrue(john.hasRole(hardcodedRole));
-
- // Can't remove user from hardcoded role
- try {
- john.deleteRoleMapping(hardcodedRole);
- Assert.fail("Didn't expected to remove role mapping");
- } catch (ModelException expected) {
- }
-
- // Revert mappers
- ComponentModel hardcodedMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "hardcoded role");
- appRealm.removeComponent(hardcodedMapperModel);
- });
- }
-
- @Test
- public void testHardcodedGroupMapper() {
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- GroupModel hardcodedGroup = appRealm.createGroup("hardcoded-group", "hardcoded-group");
-
- // assert that user "johnkeycloak" doesn't have hardcoded group
- UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm);
- Assert.assertFalse(john.isMemberOf(hardcodedGroup));
-
- ComponentModel hardcodedMapperModel = KeycloakModelUtils.createComponentModel("hardcoded group",
- ctx.getLdapModel().getId(), HardcodedLDAPGroupStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(),
- HardcodedLDAPGroupStorageMapper.GROUP, "hardcoded-group");
- appRealm.addComponentModel(hardcodedMapperModel);
- });
-
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- GroupModel hardcodedGroup = appRealm.getGroupById("hardcoded-group");
-
- // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName
- UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm);
- Assert.assertTrue(john.isMemberOf(hardcodedGroup));
-
- // Can't remove user from hardcoded role
- try {
- john.leaveGroup(hardcodedGroup);
- Assert.fail("Didn't expected to leave group");
- } catch (ModelException expected) {
- }
-
- // Revert mappers
- ComponentModel hardcodedMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "hardcoded group");
- appRealm.removeComponent(hardcodedMapperModel);
- });
- }
-
- @Test
- public void testImportExistingUserFromLDAP() throws Exception {
- // Add LDAP user with same email like existing model user
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "marykeycloak", "Mary1", "Kelly1", "mary1@email.org", null, "123");
- LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "mary-duplicatemail", "Mary2", "Kelly2", "mary@test.com", null, "123");
- LDAPObject marynoemail = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "marynoemail", "Mary1", "Kelly1", null, null, "123");
- LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), marynoemail, "Password1");
- });
-
-
- // Try to import the duplicated LDAP user into Keycloak
- loginPage.open();
- loginPage.login("mary-duplicatemail", "password");
- Assert.assertEquals("Email already exists.", loginPage.getError());
-
- loginPage.login("mary1@email.org", "password");
- Assert.assertEquals("Username already exists.", loginPage.getError());
-
- loginSuccessAndLogout("marynoemail", "Password1");
- }
-
- @Test
- public void testReadonly() {
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- ctx.getLdapModel().getConfig().putSingle(LDAPConstants.EDIT_MODE, UserStorageProvider.EditMode.READ_ONLY.toString());
- appRealm.updateComponent(ctx.getLdapModel());
- });
-
- UserRepresentation userRep = ApiUtil.findUserByUsername(testRealm(), "johnkeycloak");
- assertFederatedUserLink(userRep);
-
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- UserModel user = session.users().getUserByUsername("johnkeycloak", appRealm);
- Assert.assertNotNull(user);
- try {
- user.setEmail("error@error.com");
- Assert.fail("should fail");
- } catch (ReadOnlyException e) {
-
- }
- try {
- user.setLastName("Berk");
- Assert.fail("should fail");
- } catch (ReadOnlyException e) {
-
- }
- try {
- user.setFirstName("Bilbo");
- Assert.fail("should fail");
- } catch (ReadOnlyException e) {
-
- }
- try {
- UserCredentialModel cred = UserCredentialModel.password("PoopyPoop1", true);
- session.userCredentialManager().updateCredential(appRealm, user, cred);
- Assert.fail("should fail");
- } catch (ReadOnlyException e) {
-
- }
-
- Assert.assertTrue(session.users().removeUser(appRealm, user));
- });
-
- // Revert
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- ctx.getLdapModel().put(LDAPConstants.EDIT_MODE, UserStorageProvider.EditMode.WRITABLE.toString());
- appRealm.updateComponent(ctx.getLdapModel());
-
- Assert.assertEquals(UserStorageProvider.EditMode.WRITABLE.toString(),
- appRealm.getComponent(ctx.getLdapModel().getId()).getConfig().getFirst(LDAPConstants.EDIT_MODE));
- });
- }
-
- @Test
- public void testRemoveFederatedUser() {
- UserRepresentation user = ApiUtil.findUserByUsername(testRealm(), "registerusersuccess2");
-
- // Case when this test was executed "alone" (User "registerusersuccess2" is registered inside registerUserLdapSuccess)
- if (user == null) {
- registerUserLdapSuccess();
- user = ApiUtil.findUserByUsername(testRealm(), "registerusersuccess2");
- }
-
- assertFederatedUserLink(user);
- testRealm().users().get(user.getId()).remove();
- user = ApiUtil.findUserByUsername(testRealm(), "registerusersuccess2");
- Assert.assertNull(user);
- }
-
- @Test
- public void testSearch() {
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username1", "John1", "Doel1", "user1@email.org", null, "121");
- LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username2", "John2", "Doel2", "user2@email.org", null, "122");
- LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username3", "John3", "Doel3", "user3@email.org", null, "123");
- LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username4", "John4", "Doel4", "user4@email.org", null, "124");
-
- // Users are not at local store at this moment
- Assert.assertNull(session.userLocalStorage().getUserByUsername("username1", appRealm));
- Assert.assertNull(session.userLocalStorage().getUserByUsername("username2", appRealm));
- Assert.assertNull(session.userLocalStorage().getUserByUsername("username3", appRealm));
- Assert.assertNull(session.userLocalStorage().getUserByUsername("username4", appRealm));
-
- // search by username
- session.users().searchForUser("username1", appRealm);
- LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username1", "John1", "Doel1", "user1@email.org", "121");
-
- // search by email
- session.users().searchForUser("user2@email.org", appRealm);
- LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username2", "John2", "Doel2", "user2@email.org", "122");
-
- // search by lastName
- session.users().searchForUser("Doel3", appRealm);
- LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username3", "John3", "Doel3", "user3@email.org", "123");
-
- // search by firstName + lastName
- session.users().searchForUser("John4 Doel4", appRealm);
- LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username4", "John4", "Doel4", "user4@email.org", "124");
- });
- }
-
- @Test
- public void testSearchWithCustomLDAPFilter() {
- // Add custom filter for searching users
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- ctx.getLdapModel().getConfig().putSingle(LDAPConstants.CUSTOM_USER_SEARCH_FILTER, "(|(mail=user5@email.org)(mail=user6@email.org))");
- appRealm.updateComponent(ctx.getLdapModel());
- });
-
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username5", "John5", "Doel5", "user5@email.org", null, "125");
- LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username6", "John6", "Doel6", "user6@email.org", null, "126");
- LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username7", "John7", "Doel7", "user7@email.org", null, "127");
-
- // search by email
- List<UserModel> list = session.users().searchForUser("user5@email.org", appRealm);
- LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username5", "John5", "Doel5", "user5@email.org", "125");
-
- session.users().searchForUser("John6 Doel6", appRealm);
- LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username6", "John6", "Doel6", "user6@email.org", "126");
-
- session.users().searchForUser("user7@email.org", appRealm);
- session.users().searchForUser("John7 Doel7", appRealm);
- Assert.assertNull(session.userLocalStorage().getUserByUsername("username7", appRealm));
-
- // Remove custom filter
- ctx.getLdapModel().getConfig().remove(LDAPConstants.CUSTOM_USER_SEARCH_FILTER);
- appRealm.updateComponent(ctx.getLdapModel());
- });
- }
-
- @Test
- public void testUnsynced() throws Exception {
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- UserStorageProviderModel model = new UserStorageProviderModel(ctx.getLdapModel());
- model.getConfig().putSingle(LDAPConstants.EDIT_MODE, UserStorageProvider.EditMode.UNSYNCED.toString());
- appRealm.updateComponent(model);
- });
-
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- UserModel user = session.users().getUserByUsername("johnkeycloak", appRealm);
- Assert.assertNotNull(user);
- Assert.assertNotNull(user.getFederationLink());
- Assert.assertEquals(user.getFederationLink(), ctx.getLdapModel().getId());
-
- UserCredentialModel cred = UserCredentialModel.password("Candycand1", true);
- session.userCredentialManager().updateCredential(appRealm, user, cred);
- CredentialModel userCredentialValueModel = session.userCredentialManager().getStoredCredentialsByType(appRealm, user, CredentialModel.PASSWORD).get(0);
- Assert.assertEquals(UserCredentialModel.PASSWORD, userCredentialValueModel.getType());
- Assert.assertTrue(session.userCredentialManager().isValid(appRealm, user, cred));
-
- // LDAP password is still unchanged
- try {
- LDAPObject ldapUser = ctx.getLdapProvider().loadLDAPUserByUsername(appRealm, "johnkeycloak");
- ctx.getLdapProvider().getLdapIdentityStore().validatePassword(ldapUser, "Password1");
- } catch (AuthenticationException ex) {
- throw new RuntimeException(ex);
- }
-
- // User is deleted just locally
- Assert.assertTrue(session.users().removeUser(appRealm, user));
-
- // Assert user not available locally, but will be reimported from LDAP once searched
- Assert.assertNull(session.userLocalStorage().getUserByUsername("johnkeycloak", appRealm));
- Assert.assertNotNull(session.users().getUserByUsername("johnkeycloak", appRealm));
- });
-
- // Revert
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- ctx.getLdapModel().getConfig().putSingle(LDAPConstants.EDIT_MODE, UserStorageProvider.EditMode.WRITABLE.toString());
-
- appRealm.updateComponent(ctx.getLdapModel());
-
- Assert.assertEquals(UserStorageProvider.EditMode.WRITABLE.toString(), appRealm.getComponent(ctx.getLdapModel().getId()).getConfig().getFirst(LDAPConstants.EDIT_MODE));
- });
- }
-
-
- @Test
- public void testSearchByAttributes() {
- testingClient.server().run(session -> {
- final String ATTRIBUTE = "postal_code";
- final String ATTRIBUTE_VALUE = "80330340";
-
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username8", "John8", "Doel8", "user8@email.org", null, ATTRIBUTE_VALUE);
- LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username9", "John9", "Doel9", "user9@email.org", null, ATTRIBUTE_VALUE);
- LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username10", "John10", "Doel10", "user10@email.org", null, "1210");
-
- // Users are not at local store at this moment
- Assert.assertNull(session.userLocalStorage().getUserByUsername("username8", appRealm));
- Assert.assertNull(session.userLocalStorage().getUserByUsername("username9", appRealm));
- Assert.assertNull(session.userLocalStorage().getUserByUsername("username10", appRealm));
-
- // search for user by attribute
- List<UserModel> users = ctx.getLdapProvider().searchForUserByUserAttribute(ATTRIBUTE, ATTRIBUTE_VALUE, appRealm);
- assertEquals(2, users.size());
- assertNotNull(users.get(0).getAttribute(ATTRIBUTE));
- assertEquals(1, users.get(0).getAttribute(ATTRIBUTE).size());
- assertEquals(ATTRIBUTE_VALUE, users.get(0).getAttribute(ATTRIBUTE).get(0));
-
- assertNotNull(users.get(1).getAttribute(ATTRIBUTE));
- assertEquals(1, users.get(1).getAttribute(ATTRIBUTE).size());
- assertEquals(ATTRIBUTE_VALUE, users.get(1).getAttribute(ATTRIBUTE).get(0));
-
- // user are now imported to local store
- LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username8", "John8", "Doel8", "user8@email.org", ATTRIBUTE_VALUE);
- LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username9", "John9", "Doel9", "user9@email.org", ATTRIBUTE_VALUE);
- // but the one not looked up is not
- Assert.assertNull(session.userLocalStorage().getUserByUsername("username10", appRealm));
-
- });
- }
-
-
- // KEYCLOAK-9002
- @Test
- public void testSearchWithPartiallyCachedUser() {
- testingClient.server().run(session -> {
- session.userCache().clear();
- });
+// // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName
+// LDAPTestAsserts.assertUserImported(session.users(), appRealm, "fullname", "James", "Dee", "fullname@email.org", "4578");
+// });
+
+// // Assert user will be changed in LDAP too
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// UserModel fullnameUser = session.users().getUserByUsername("fullname", appRealm);
+// fullnameUser.setFirstName("James2");
+// fullnameUser.setLastName("Dee2");
+// });
+
+
+// // Assert changed user available in Keycloak
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName
+// LDAPTestAsserts.assertUserImported(session.users(), appRealm, "fullname", "James2", "Dee2", "fullname@email.org", "4578");
+
+// // Remove "fullnameUser" to assert he is removed from LDAP. Revert mappers to previous state
+// UserModel fullnameUser = session.users().getUserByUsername("fullname", appRealm);
+// session.users().removeUser(appRealm, fullnameUser);
+
+// // Revert mappers
+// ComponentModel fullNameMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "full name");
+// appRealm.removeComponent(fullNameMapperModel);
+// });
+
+// firstNameMapperRep.setId(null);
+// Response response = testRealm().components().add(firstNameMapperRep);
+// Assert.assertEquals(201, response.getStatus());
+// response.close();
+// }
+
+
+// @Test
+// public void testHardcodedAttributeMapperTest() throws Exception {
+// // Create hardcoded mapper for "description"
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+
+// ComponentModel hardcodedMapperModel = KeycloakModelUtils.createComponentModel("hardcodedAttr-description", ctx.getLdapModel().getId(), HardcodedLDAPAttributeMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(),
+// HardcodedLDAPAttributeMapper.LDAP_ATTRIBUTE_NAME, "description",
+// HardcodedLDAPAttributeMapper.LDAP_ATTRIBUTE_VALUE, "some-${RANDOM}");
+// ctx.getRealm().addComponentModel(hardcodedMapperModel);
+// });
+
+// // Register new user
+// loginPage.open();
+// loginPage.clickRegister();
+// registerPage.assertCurrent();
+
+// registerPage.register("firstName", "lastName", "email34@check.cz", "register123", "Password1", "Password1");
+// Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
+
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// // See that user don't yet have any description
+// UserModel user = LDAPTestAsserts.assertUserImported(session.users(), appRealm, "register123", "firstName", "lastName", "email34@check.cz", null);
+// Assert.assertNull(user.getFirstAttribute("desc"));
+// Assert.assertNull(user.getFirstAttribute("description"));
+
+// // Remove hardcoded mapper for "description" and create regular userAttribute mapper for description
+// ComponentModel hardcodedMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "hardcodedAttr-description");
+// appRealm.removeComponent(hardcodedMapperModel);
+
+// ComponentModel userAttrMapper = LDAPTestUtils.addUserAttributeMapper(appRealm, ctx.getLdapModel(), "desc-attribute-mapper", "desc", "description");
+// userAttrMapper.put(UserAttributeLDAPStorageMapper.ALWAYS_READ_VALUE_FROM_LDAP, "true");
+// appRealm.updateComponent(userAttrMapper);
+// });
+
+// // Check that user has description on him now
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// session.userCache().evict(appRealm, session.users().getUserByUsername("register123", appRealm));
+
+// // See that user don't yet have any description
+// UserModel user = session.users().getUserByUsername("register123", appRealm);
+// Assert.assertNull(user.getFirstAttribute("description"));
+// Assert.assertNotNull(user.getFirstAttribute("desc"));
+// String desc = user.getFirstAttribute("desc");
+// Assert.assertTrue(desc.startsWith("some-"));
+// Assert.assertEquals(35, desc.length());
+
+// // Remove mapper for "description"
+// ComponentModel userAttrMapper = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "desc-attribute-mapper");
+// appRealm.removeComponent(userAttrMapper);
+// });
+// }
+
+
+// @Test
+// public void testHardcodedRoleMapper() {
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+// RoleModel hardcodedRole = appRealm.addRole("hardcoded-role");
+
+// // assert that user "johnkeycloak" doesn't have hardcoded role
+// UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm);
+// Assert.assertFalse(john.hasRole(hardcodedRole));
+
+// ComponentModel hardcodedMapperModel = KeycloakModelUtils.createComponentModel("hardcoded role", ctx.getLdapModel().getId(),
+// HardcodedLDAPRoleStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(),
+// HardcodedLDAPRoleStorageMapper.ROLE, "hardcoded-role");
+// appRealm.addComponentModel(hardcodedMapperModel);
+// });
+
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// RoleModel hardcodedRole = appRealm.getRole("hardcoded-role");
+
+// // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName
+// UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm);
+// Assert.assertTrue(john.hasRole(hardcodedRole));
+
+// // Can't remove user from hardcoded role
+// try {
+// john.deleteRoleMapping(hardcodedRole);
+// Assert.fail("Didn't expected to remove role mapping");
+// } catch (ModelException expected) {
+// }
+
+// // Revert mappers
+// ComponentModel hardcodedMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "hardcoded role");
+// appRealm.removeComponent(hardcodedMapperModel);
+// });
+// }
+
+// @Test
+// public void testHardcodedGroupMapper() {
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// GroupModel hardcodedGroup = appRealm.createGroup("hardcoded-group", "hardcoded-group");
+
+// // assert that user "johnkeycloak" doesn't have hardcoded group
+// UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm);
+// Assert.assertFalse(john.isMemberOf(hardcodedGroup));
+
+// ComponentModel hardcodedMapperModel = KeycloakModelUtils.createComponentModel("hardcoded group",
+// ctx.getLdapModel().getId(), HardcodedLDAPGroupStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(),
+// HardcodedLDAPGroupStorageMapper.GROUP, "hardcoded-group");
+// appRealm.addComponentModel(hardcodedMapperModel);
+// });
+
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// GroupModel hardcodedGroup = appRealm.getGroupById("hardcoded-group");
+
+// // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName
+// UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm);
+// Assert.assertTrue(john.isMemberOf(hardcodedGroup));
+
+// // Can't remove user from hardcoded role
+// try {
+// john.leaveGroup(hardcodedGroup);
+// Assert.fail("Didn't expected to leave group");
+// } catch (ModelException expected) {
+// }
+
+// // Revert mappers
+// ComponentModel hardcodedMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "hardcoded group");
+// appRealm.removeComponent(hardcodedMapperModel);
+// });
+// }
+
+// @Test
+// public void testImportExistingUserFromLDAP() throws Exception {
+// // Add LDAP user with same email like existing model user
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "marykeycloak", "Mary1", "Kelly1", "mary1@email.org", null, "123");
+// LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "mary-duplicatemail", "Mary2", "Kelly2", "mary@test.com", null, "123");
+// LDAPObject marynoemail = LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "marynoemail", "Mary1", "Kelly1", null, null, "123");
+// LDAPTestUtils.updateLDAPPassword(ctx.getLdapProvider(), marynoemail, "Password1");
+// });
+
+
+// // Try to import the duplicated LDAP user into Keycloak
+// loginPage.open();
+// loginPage.login("mary-duplicatemail", "password");
+// Assert.assertEquals("Email already exists.", loginPage.getError());
+
+// loginPage.login("mary1@email.org", "password");
+// Assert.assertEquals("Username already exists.", loginPage.getError());
+
+// loginSuccessAndLogout("marynoemail", "Password1");
+// }
+
+// @Test
+// public void testReadonly() {
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// ctx.getLdapModel().getConfig().putSingle(LDAPConstants.EDIT_MODE, UserStorageProvider.EditMode.READ_ONLY.toString());
+// appRealm.updateComponent(ctx.getLdapModel());
+// });
+
+// UserRepresentation userRep = ApiUtil.findUserByUsername(testRealm(), "johnkeycloak");
+// assertFederatedUserLink(userRep);
+
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// UserModel user = session.users().getUserByUsername("johnkeycloak", appRealm);
+// Assert.assertNotNull(user);
+// try {
+// user.setEmail("error@error.com");
+// Assert.fail("should fail");
+// } catch (ReadOnlyException e) {
+
+// }
+// try {
+// user.setLastName("Berk");
+// Assert.fail("should fail");
+// } catch (ReadOnlyException e) {
+
+// }
+// try {
+// user.setFirstName("Bilbo");
+// Assert.fail("should fail");
+// } catch (ReadOnlyException e) {
+
+// }
+// try {
+// UserCredentialModel cred = UserCredentialModel.password("PoopyPoop1", true);
+// session.userCredentialManager().updateCredential(appRealm, user, cred);
+// Assert.fail("should fail");
+// } catch (ReadOnlyException e) {
+
+// }
+
+// Assert.assertTrue(session.users().removeUser(appRealm, user));
+// });
+
+// // Revert
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// ctx.getLdapModel().put(LDAPConstants.EDIT_MODE, UserStorageProvider.EditMode.WRITABLE.toString());
+// appRealm.updateComponent(ctx.getLdapModel());
+
+// Assert.assertEquals(UserStorageProvider.EditMode.WRITABLE.toString(),
+// appRealm.getComponent(ctx.getLdapModel().getId()).getConfig().getFirst(LDAPConstants.EDIT_MODE));
+// });
+// }
+
+// @Test
+// public void testRemoveFederatedUser() {
+// UserRepresentation user = ApiUtil.findUserByUsername(testRealm(), "registerusersuccess2");
+
+// // Case when this test was executed "alone" (User "registerusersuccess2" is registered inside registerUserLdapSuccess)
+// if (user == null) {
+// registerUserLdapSuccess();
+// user = ApiUtil.findUserByUsername(testRealm(), "registerusersuccess2");
+// }
+
+// assertFederatedUserLink(user);
+// testRealm().users().get(user.getId()).remove();
+// user = ApiUtil.findUserByUsername(testRealm(), "registerusersuccess2");
+// Assert.assertNull(user);
+// }
+
+// @Test
+// public void testSearch() {
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username1", "John1", "Doel1", "user1@email.org", null, "121");
+// LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username2", "John2", "Doel2", "user2@email.org", null, "122");
+// LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username3", "John3", "Doel3", "user3@email.org", null, "123");
+// LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username4", "John4", "Doel4", "user4@email.org", null, "124");
+
+// // Users are not at local store at this moment
+// Assert.assertNull(session.userLocalStorage().getUserByUsername("username1", appRealm));
+// Assert.assertNull(session.userLocalStorage().getUserByUsername("username2", appRealm));
+// Assert.assertNull(session.userLocalStorage().getUserByUsername("username3", appRealm));
+// Assert.assertNull(session.userLocalStorage().getUserByUsername("username4", appRealm));
+
+// // search by username
+// session.users().searchForUser("username1", appRealm);
+// LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username1", "John1", "Doel1", "user1@email.org", "121");
+
+// // search by email
+// session.users().searchForUser("user2@email.org", appRealm);
+// LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username2", "John2", "Doel2", "user2@email.org", "122");
+
+// // search by lastName
+// session.users().searchForUser("Doel3", appRealm);
+// LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username3", "John3", "Doel3", "user3@email.org", "123");
+
+// // search by firstName + lastName
+// session.users().searchForUser("John4 Doel4", appRealm);
+// LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username4", "John4", "Doel4", "user4@email.org", "124");
+// });
+// }
+
+// @Test
+// public void testSearchWithCustomLDAPFilter() {
+// // Add custom filter for searching users
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// ctx.getLdapModel().getConfig().putSingle(LDAPConstants.CUSTOM_USER_SEARCH_FILTER, "(|(mail=user5@email.org)(mail=user6@email.org))");
+// appRealm.updateComponent(ctx.getLdapModel());
+// });
+
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username5", "John5", "Doel5", "user5@email.org", null, "125");
+// LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username6", "John6", "Doel6", "user6@email.org", null, "126");
+// LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username7", "John7", "Doel7", "user7@email.org", null, "127");
+
+// // search by email
+// List<UserModel> list = session.users().searchForUser("user5@email.org", appRealm);
+// LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username5", "John5", "Doel5", "user5@email.org", "125");
+
+// session.users().searchForUser("John6 Doel6", appRealm);
+// LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username6", "John6", "Doel6", "user6@email.org", "126");
+
+// session.users().searchForUser("user7@email.org", appRealm);
+// session.users().searchForUser("John7 Doel7", appRealm);
+// Assert.assertNull(session.userLocalStorage().getUserByUsername("username7", appRealm));
+
+// // Remove custom filter
+// ctx.getLdapModel().getConfig().remove(LDAPConstants.CUSTOM_USER_SEARCH_FILTER);
+// appRealm.updateComponent(ctx.getLdapModel());
+// });
+// }
+
+// @Test
+// public void testUnsynced() throws Exception {
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// UserStorageProviderModel model = new UserStorageProviderModel(ctx.getLdapModel());
+// model.getConfig().putSingle(LDAPConstants.EDIT_MODE, UserStorageProvider.EditMode.UNSYNCED.toString());
+// appRealm.updateComponent(model);
+// });
+
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// UserModel user = session.users().getUserByUsername("johnkeycloak", appRealm);
+// Assert.assertNotNull(user);
+// Assert.assertNotNull(user.getFederationLink());
+// Assert.assertEquals(user.getFederationLink(), ctx.getLdapModel().getId());
+
+// UserCredentialModel cred = UserCredentialModel.password("Candycand1", true);
+// session.userCredentialManager().updateCredential(appRealm, user, cred);
+// CredentialModel userCredentialValueModel = session.userCredentialManager().getStoredCredentialsByType(appRealm, user, CredentialModel.PASSWORD).get(0);
+// Assert.assertEquals(UserCredentialModel.PASSWORD, userCredentialValueModel.getType());
+// Assert.assertTrue(session.userCredentialManager().isValid(appRealm, user, cred));
+
+// // LDAP password is still unchanged
+// try {
+// LDAPObject ldapUser = ctx.getLdapProvider().loadLDAPUserByUsername(appRealm, "johnkeycloak");
+// ctx.getLdapProvider().getLdapIdentityStore().validatePassword(ldapUser, "Password1");
+// } catch (AuthenticationException ex) {
+// throw new RuntimeException(ex);
+// }
+
+// // User is deleted just locally
+// Assert.assertTrue(session.users().removeUser(appRealm, user));
+
+// // Assert user not available locally, but will be reimported from LDAP once searched
+// Assert.assertNull(session.userLocalStorage().getUserByUsername("johnkeycloak", appRealm));
+// Assert.assertNotNull(session.users().getUserByUsername("johnkeycloak", appRealm));
+// });
+
+// // Revert
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// ctx.getLdapModel().getConfig().putSingle(LDAPConstants.EDIT_MODE, UserStorageProvider.EditMode.WRITABLE.toString());
+
+// appRealm.updateComponent(ctx.getLdapModel());
+
+// Assert.assertEquals(UserStorageProvider.EditMode.WRITABLE.toString(), appRealm.getComponent(ctx.getLdapModel().getId()).getConfig().getFirst(LDAPConstants.EDIT_MODE));
+// });
+// }
+
+
+// @Test
+// public void testSearchByAttributes() {
+// testingClient.server().run(session -> {
+// final String ATTRIBUTE = "postal_code";
+// final String ATTRIBUTE_VALUE = "80330340";
+
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username8", "John8", "Doel8", "user8@email.org", null, ATTRIBUTE_VALUE);
+// LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username9", "John9", "Doel9", "user9@email.org", null, ATTRIBUTE_VALUE);
+// LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username10", "John10", "Doel10", "user10@email.org", null, "1210");
+
+// // Users are not at local store at this moment
+// Assert.assertNull(session.userLocalStorage().getUserByUsername("username8", appRealm));
+// Assert.assertNull(session.userLocalStorage().getUserByUsername("username9", appRealm));
+// Assert.assertNull(session.userLocalStorage().getUserByUsername("username10", appRealm));
+
+// // search for user by attribute
+// List<UserModel> users = ctx.getLdapProvider().searchForUserByUserAttribute(ATTRIBUTE, ATTRIBUTE_VALUE, appRealm);
+// assertEquals(2, users.size());
+// assertNotNull(users.get(0).getAttribute(ATTRIBUTE));
+// assertEquals(1, users.get(0).getAttribute(ATTRIBUTE).size());
+// assertEquals(ATTRIBUTE_VALUE, users.get(0).getAttribute(ATTRIBUTE).get(0));
+
+// assertNotNull(users.get(1).getAttribute(ATTRIBUTE));
+// assertEquals(1, users.get(1).getAttribute(ATTRIBUTE).size());
+// assertEquals(ATTRIBUTE_VALUE, users.get(1).getAttribute(ATTRIBUTE).get(0));
+
+// // user are now imported to local store
+// LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username8", "John8", "Doel8", "user8@email.org", ATTRIBUTE_VALUE);
+// LDAPTestAsserts.assertUserImported(session.userLocalStorage(), appRealm, "username9", "John9", "Doel9", "user9@email.org", ATTRIBUTE_VALUE);
+// // but the one not looked up is not
+// Assert.assertNull(session.userLocalStorage().getUserByUsername("username10", appRealm));
+
+// });
+// }
+
+
+// // KEYCLOAK-9002
+// @Test
+// public void testSearchWithPartiallyCachedUser() {
+// testingClient.server().run(session -> {
+// session.userCache().clear();
+// });
- // This will load user from LDAP and partially cache him (including attributes)
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
- UserModel user = session.users().getUserByUsername("johnkeycloak", appRealm);
- Assert.assertNotNull(user);
-
- user.getAttributes();
- });
+// // This will load user from LDAP and partially cache him (including attributes)
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+// UserModel user = session.users().getUserByUsername("johnkeycloak", appRealm);
+// Assert.assertNotNull(user);
+
+// user.getAttributes();
+// });
- // Assert search without arguments won't blow up with StackOverflowError
- adminClient.realm("test").users().search(null, 0, 10, false);
-
- List<UserRepresentation> users = adminClient.realm("test").users().search("johnkeycloak", 0, 10, false);
- Assert.assertTrue(users.stream().anyMatch(userRepresentation -> "johnkeycloak".equals(userRepresentation.getUsername())));
- }
-
-
- @Test
- public void testLDAPUserRefreshCache() {
- testingClient.server().run(session -> {
- session.userCache().clear();
- });
-
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
+// // Assert search without arguments won't blow up with StackOverflowError
+// adminClient.realm("test").users().search(null, 0, 10, false);
+
+// List<UserRepresentation> users = adminClient.realm("test").users().search("johnkeycloak", 0, 10, false);
+// Assert.assertTrue(users.stream().anyMatch(userRepresentation -> "johnkeycloak".equals(userRepresentation.getUsername())));
+// }
+
+
+// @Test
+// public void testLDAPUserRefreshCache() {
+// testingClient.server().run(session -> {
+// session.userCache().clear();
+// });
+
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
- LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ctx.getLdapModel());
- LDAPTestUtils.addLDAPUser(ldapProvider, appRealm, "johndirect", "John", "Direct", "johndirect@email.org", null, "1234");
+// LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ctx.getLdapModel());
+// LDAPTestUtils.addLDAPUser(ldapProvider, appRealm, "johndirect", "John", "Direct", "johndirect@email.org", null, "1234");
- // Fetch user from LDAP and check that postalCode is filled
- UserModel user = session.users().getUserByUsername("johndirect", appRealm);
- String postalCode = user.getFirstAttribute("postal_code");
- Assert.assertEquals("1234", postalCode);
+// // Fetch user from LDAP and check that postalCode is filled
+// UserModel user = session.users().getUserByUsername("johndirect", appRealm);
+// String postalCode = user.getFirstAttribute("postal_code");
+// Assert.assertEquals("1234", postalCode);
- LDAPTestUtils.removeLDAPUserByUsername(ldapProvider, appRealm, ldapProvider.getLdapIdentityStore().getConfig(), "johndirect");
- });
+// LDAPTestUtils.removeLDAPUserByUsername(ldapProvider, appRealm, ldapProvider.getLdapIdentityStore().getConfig(), "johndirect");
+// });
- setTimeOffset(60 * 5); // 5 minutes in future, user should be cached still
+// setTimeOffset(60 * 5); // 5 minutes in future, user should be cached still
- testingClient.server().run(session -> {
- RealmModel appRealm = new RealmManager(session).getRealmByName("test");
- CachedUserModel user = (CachedUserModel) session.users().getUserByUsername("johndirect", appRealm);
- String postalCode = user.getFirstAttribute("postal_code");
- String email = user.getEmail();
- Assert.assertEquals("1234", postalCode);
- Assert.assertEquals("johndirect@email.org", email);
- });
+// testingClient.server().run(session -> {
+// RealmModel appRealm = new RealmManager(session).getRealmByName("test");
+// CachedUserModel user = (CachedUserModel) session.users().getUserByUsername("johndirect", appRealm);
+// String postalCode = user.getFirstAttribute("postal_code");
+// String email = user.getEmail();
+// Assert.assertEquals("1234", postalCode);
+// Assert.assertEquals("johndirect@email.org", email);
+// });
- setTimeOffset(60 * 20); // 20 minutes into future, cache will be invalidated
-
- testingClient.server().run(session -> {
- RealmModel appRealm = new RealmManager(session).getRealmByName("test");
- UserModel user = session.users().getUserByUsername("johndirect", appRealm);
- Assert.assertNull(user);
- });
+// setTimeOffset(60 * 20); // 20 minutes into future, cache will be invalidated
+
+// testingClient.server().run(session -> {
+// RealmModel appRealm = new RealmManager(session).getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("johndirect", appRealm);
+// Assert.assertNull(user);
+// });
- setTimeOffset(0);
- }
-
- @Test
- public void testCacheUser() {
- String userId = testingClient.server().fetch(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- ctx.getLdapModel().setCachePolicy(UserStorageProviderModel.CachePolicy.NO_CACHE);
- ctx.getRealm().updateComponent(ctx.getLdapModel());
-
- LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "testCacheUser", "John", "Cached", "johndirect@test.com", null, "1234");
+// setTimeOffset(0);
+// }
+
+// @Test
+// public void testCacheUser() {
+// String userId = testingClient.server().fetch(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// ctx.getLdapModel().setCachePolicy(UserStorageProviderModel.CachePolicy.NO_CACHE);
+// ctx.getRealm().updateComponent(ctx.getLdapModel());
+
+// LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), ctx.getRealm(), "testCacheUser", "John", "Cached", "johndirect@test.com", null, "1234");
- // Fetch user from LDAP and check that postalCode is filled
- UserModel testedUser = session.users().getUserByUsername("testCacheUser", ctx.getRealm());
-
- String usserId = testedUser.getId();
- Assert.assertNotNull(usserId);
- Assert.assertFalse(usserId.isEmpty());
+// // Fetch user from LDAP and check that postalCode is filled
+// UserModel testedUser = session.users().getUserByUsername("testCacheUser", ctx.getRealm());
+
+// String usserId = testedUser.getId();
+// Assert.assertNotNull(usserId);
+// Assert.assertFalse(usserId.isEmpty());
- return usserId;
- }, String.class);
+// return usserId;
+// }, String.class);
- testingClient.server().run(session -> {
+// testingClient.server().run(session -> {
- RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME);
- UserModel testedUser = session.users().getUserById(userId, appRealm);
- Assert.assertFalse(testedUser instanceof CachedUserModel);
- });
+// RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME);
+// UserModel testedUser = session.users().getUserById(userId, appRealm);
+// Assert.assertFalse(testedUser instanceof CachedUserModel);
+// });
- // restore default cache policy
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
+// // restore default cache policy
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
- ctx.getLdapModel().setCachePolicy(UserStorageProviderModel.CachePolicy.MAX_LIFESPAN);
- ctx.getLdapModel().setMaxLifespan(600000); // Lifetime is 10 minutes
- ctx.getRealm().updateComponent(ctx.getLdapModel());
- });
+// ctx.getLdapModel().setCachePolicy(UserStorageProviderModel.CachePolicy.MAX_LIFESPAN);
+// ctx.getLdapModel().setMaxLifespan(600000); // Lifetime is 10 minutes
+// ctx.getRealm().updateComponent(ctx.getLdapModel());
+// });
- testingClient.server().run(session -> {
- RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME);
- UserModel testedUser = session.users().getUserById(userId, appRealm);
- Assert.assertTrue(testedUser instanceof CachedUserModel);
- });
+// testingClient.server().run(session -> {
+// RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME);
+// UserModel testedUser = session.users().getUserById(userId, appRealm);
+// Assert.assertTrue(testedUser instanceof CachedUserModel);
+// });
- setTimeOffset(60 * 5); // 5 minutes in future, should be cached still
- testingClient.server().run(session -> {
- RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME);
- UserModel testedUser = session.users().getUserById(userId, appRealm);
- Assert.assertTrue(testedUser instanceof CachedUserModel);
- });
+// setTimeOffset(60 * 5); // 5 minutes in future, should be cached still
+// testingClient.server().run(session -> {
+// RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME);
+// UserModel testedUser = session.users().getUserById(userId, appRealm);
+// Assert.assertTrue(testedUser instanceof CachedUserModel);
+// });
- setTimeOffset(60 * 10); // 10 minutes into future, cache will be invalidated
- testingClient.server().run(session -> {
- RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME);
- UserModel testedUser = session.users().getUserByUsername("thor", appRealm);
- Assert.assertFalse(testedUser instanceof CachedUserModel);
- });
-
- setTimeOffset(0);
- }
-}
+// setTimeOffset(60 * 10); // 10 minutes into future, cache will be invalidated
+// testingClient.server().run(session -> {
+// RealmModel appRealm = session.realms().getRealmByName(TEST_REALM_NAME);
+// UserModel testedUser = session.users().getUserByUsername("thor", appRealm);
+// Assert.assertFalse(testedUser instanceof CachedUserModel);
+// });
+
+// setTimeOffset(0);
+// }
+// }
diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSyncTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSyncTest.java
index c48507b..5ee14c5 100755
--- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSyncTest.java
+++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/LDAPSyncTest.java
@@ -35,7 +35,7 @@ import org.keycloak.models.LDAPConstants;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.models.UserProvider;
-import org.keycloak.models.cache.UserCache;
+// import org.keycloak.models.cache.UserCache;
import org.keycloak.storage.UserStorageProviderModel;
import org.keycloak.storage.ldap.LDAPStorageProvider;
import org.keycloak.storage.ldap.LDAPStorageProviderFactory;
@@ -304,10 +304,10 @@ public class LDAPSyncTest extends AbstractLDAPTest {
// Remove all users from model
for (UserModel user : session.userLocalStorage().getUsers(ctx.getRealm(), true)) {
System.out.println("trying to delete user: " + user.getUsername());
- UserCache userCache = session.userCache();
- if (userCache != null) {
- userCache.evict(ctx.getRealm(), user);
- }
+ // UserCache userCache = session.userCache();
+ // if (userCache != null) {
+ // userCache.evict(ctx.getRealm(), user);
+ // }
session.userLocalStorage().removeUser(ctx.getRealm(), user);
}
diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPMultipleAttributesNoImportTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPMultipleAttributesNoImportTest.java
index 2505df8..78ac1a3 100755
--- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPMultipleAttributesNoImportTest.java
+++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPMultipleAttributesNoImportTest.java
@@ -1,61 +1,61 @@
-/*
- * Copyright 2017 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.testsuite.federation.ldap.noimport;
-
-import org.junit.Assert;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.runners.MethodSorters;
-import org.keycloak.models.RealmModel;
-import org.keycloak.models.UserModel;
-import org.keycloak.testsuite.federation.ldap.LDAPMultipleAttributesTest;
-import org.keycloak.testsuite.federation.ldap.LDAPTestAsserts;
-import org.keycloak.testsuite.federation.ldap.LDAPTestContext;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class LDAPMultipleAttributesNoImportTest extends LDAPMultipleAttributesTest {
-
-
- @Override
- protected boolean isImportEnabled() {
- return false;
- }
-
-
- @Test
- public void testUserImport() {
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- session.userCache().clear();
- RealmModel appRealm = ctx.getRealm();
-
- // Test user NOT imported in local storage now. He is available just through "session.users()"
- UserModel user = session.users().getUserByUsername("jbrown", appRealm);
- Assert.assertNotNull(user);
- Assert.assertNull(session.userLocalStorage().getUserById(user.getId(), appRealm));
- LDAPTestAsserts.assertUserImported(session.users(), appRealm, "jbrown", "James", "Brown", "jbrown@keycloak.org", "88441");
- });
- }
-
-
-}
+// /*
+// * Copyright 2017 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.testsuite.federation.ldap.noimport;
+
+// import org.junit.Assert;
+// import org.junit.FixMethodOrder;
+// import org.junit.Test;
+// import org.junit.runners.MethodSorters;
+// import org.keycloak.models.RealmModel;
+// import org.keycloak.models.UserModel;
+// import org.keycloak.testsuite.federation.ldap.LDAPMultipleAttributesTest;
+// import org.keycloak.testsuite.federation.ldap.LDAPTestAsserts;
+// import org.keycloak.testsuite.federation.ldap.LDAPTestContext;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @FixMethodOrder(MethodSorters.NAME_ASCENDING)
+// public class LDAPMultipleAttributesNoImportTest extends LDAPMultipleAttributesTest {
+
+
+// @Override
+// protected boolean isImportEnabled() {
+// return false;
+// }
+
+
+// @Test
+// public void testUserImport() {
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// session.userCache().clear();
+// RealmModel appRealm = ctx.getRealm();
+
+// // Test user NOT imported in local storage now. He is available just through "session.users()"
+// UserModel user = session.users().getUserByUsername("jbrown", appRealm);
+// Assert.assertNotNull(user);
+// Assert.assertNull(session.userLocalStorage().getUserById(user.getId(), appRealm));
+// LDAPTestAsserts.assertUserImported(session.users(), appRealm, "jbrown", "James", "Brown", "jbrown@keycloak.org", "88441");
+// });
+// }
+
+
+// }
diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPProvidersIntegrationNoImportTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPProvidersIntegrationNoImportTest.java
index f105f05..5ffa18d 100755
--- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPProvidersIntegrationNoImportTest.java
+++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPProvidersIntegrationNoImportTest.java
@@ -1,246 +1,246 @@
-/*
- * Copyright 2017 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.testsuite.federation.ldap.noimport;
-
-import javax.ws.rs.core.Response;
-
-import org.junit.Assert;
-import org.junit.FixMethodOrder;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.runners.MethodSorters;
-import org.keycloak.component.ComponentModel;
-import org.keycloak.models.LDAPConstants;
-import org.keycloak.models.RealmModel;
-import org.keycloak.models.UserModel;
-import org.keycloak.models.utils.KeycloakModelUtils;
-import org.keycloak.models.utils.ModelToRepresentation;
-import org.keycloak.representations.idm.ComponentRepresentation;
-import org.keycloak.representations.idm.UserRepresentation;
-import org.keycloak.storage.StorageId;
-import org.keycloak.storage.ldap.LDAPStorageProvider;
-import org.keycloak.storage.ldap.mappers.FullNameLDAPStorageMapper;
-import org.keycloak.storage.ldap.mappers.FullNameLDAPStorageMapperFactory;
-import org.keycloak.storage.ldap.mappers.LDAPStorageMapper;
-import org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapper;
-import org.keycloak.testsuite.federation.ldap.LDAPProvidersIntegrationTest;
-import org.keycloak.testsuite.federation.ldap.LDAPTestAsserts;
-import org.keycloak.testsuite.federation.ldap.LDAPTestContext;
-import org.keycloak.testsuite.util.LDAPTestUtils;
-
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class LDAPProvidersIntegrationNoImportTest extends LDAPProvidersIntegrationTest {
-
-
- @Override
- protected boolean isImportEnabled() {
- return false;
- }
-
-
- @Override
- protected void assertFederatedUserLink(UserRepresentation user) {
- StorageId storageId = new StorageId(user.getId());
- Assert.assertFalse(storageId.isLocal());
- Assert.assertEquals(ldapModelId, storageId.getProviderId());
-
- // TODO: It should be possibly LDAP_ID (LDAP UUID) used as an externalId inside storageId...
- Assert.assertEquals(storageId.getExternalId(), user.getUsername());
- Assert.assertNull(user.getFederationLink());
- }
-
-
- // No sense to test this in no-import mode
- @Test
- @Ignore
- @Override
- public void testRemoveImportedUsers() {
- }
-
-
- @Test
- @Override
- public void testSearch() {
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username1", "John1", "Doel1", "user1@email.org", null, "121");
- LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username2", "John2", "Doel2", "user2@email.org", null, "122");
- LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username3", "John3", "Doel3", "user3@email.org", null, "123");
- LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username4", "John4", "Doel4", "user4@email.org", null, "124");
-
- // search by username
- UserModel user = session.users().searchForUser("username1", appRealm).get(0);
- LDAPTestAsserts.assertLoaded(user, "username1", "John1", "Doel1", "user1@email.org", "121");
-
- // search by email
- user = session.users().searchForUser("user2@email.org", appRealm).get(0);
- LDAPTestAsserts.assertLoaded(user, "username2", "John2", "Doel2", "user2@email.org", "122");
-
- // search by lastName
- user = session.users().searchForUser("Doel3", appRealm).get(0);
- LDAPTestAsserts.assertLoaded(user, "username3", "John3", "Doel3", "user3@email.org", "123");
-
- // search by firstName + lastName
- user = session.users().searchForUser("John4 Doel4", appRealm).get(0);
- LDAPTestAsserts.assertLoaded(user, "username4", "John4", "Doel4", "user4@email.org", "124");
- });
- }
-
-
- // No need to test this in no-import mode. There won't be any users in localStorage after LDAP search
- @Test
- @Ignore
- @Override
- public void testSearchByAttributes() {
- }
-
-
- @Test
- @Override
- public void testSearchWithCustomLDAPFilter() {
- // Add custom filter for searching users
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- ctx.getLdapModel().getConfig().putSingle(LDAPConstants.CUSTOM_USER_SEARCH_FILTER, "(|(mail=user5@email.org)(mail=user6@email.org))");
- appRealm.updateComponent(ctx.getLdapModel());
- });
-
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username5", "John5", "Doel5", "user5@email.org", null, "125");
- LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username6", "John6", "Doel6", "user6@email.org", null, "126");
- LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username7", "John7", "Doel7", "user7@email.org", null, "127");
-
- // search by email
- UserModel user = session.users().searchForUser("user5@email.org", appRealm).get(0);
- LDAPTestAsserts.assertLoaded(user, "username5", "John5", "Doel5", "user5@email.org", "125");
+// /*
+// * Copyright 2017 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.testsuite.federation.ldap.noimport;
+
+// import javax.ws.rs.core.Response;
+
+// import org.junit.Assert;
+// import org.junit.FixMethodOrder;
+// import org.junit.Ignore;
+// import org.junit.Test;
+// import org.junit.runners.MethodSorters;
+// import org.keycloak.component.ComponentModel;
+// import org.keycloak.models.LDAPConstants;
+// import org.keycloak.models.RealmModel;
+// import org.keycloak.models.UserModel;
+// import org.keycloak.models.utils.KeycloakModelUtils;
+// import org.keycloak.models.utils.ModelToRepresentation;
+// import org.keycloak.representations.idm.ComponentRepresentation;
+// import org.keycloak.representations.idm.UserRepresentation;
+// import org.keycloak.storage.StorageId;
+// import org.keycloak.storage.ldap.LDAPStorageProvider;
+// import org.keycloak.storage.ldap.mappers.FullNameLDAPStorageMapper;
+// import org.keycloak.storage.ldap.mappers.FullNameLDAPStorageMapperFactory;
+// import org.keycloak.storage.ldap.mappers.LDAPStorageMapper;
+// import org.keycloak.storage.ldap.mappers.UserAttributeLDAPStorageMapper;
+// import org.keycloak.testsuite.federation.ldap.LDAPProvidersIntegrationTest;
+// import org.keycloak.testsuite.federation.ldap.LDAPTestAsserts;
+// import org.keycloak.testsuite.federation.ldap.LDAPTestContext;
+// import org.keycloak.testsuite.util.LDAPTestUtils;
+
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @FixMethodOrder(MethodSorters.NAME_ASCENDING)
+// public class LDAPProvidersIntegrationNoImportTest extends LDAPProvidersIntegrationTest {
+
+
+// @Override
+// protected boolean isImportEnabled() {
+// return false;
+// }
+
+
+// @Override
+// protected void assertFederatedUserLink(UserRepresentation user) {
+// StorageId storageId = new StorageId(user.getId());
+// Assert.assertFalse(storageId.isLocal());
+// Assert.assertEquals(ldapModelId, storageId.getProviderId());
+
+// // TODO: It should be possibly LDAP_ID (LDAP UUID) used as an externalId inside storageId...
+// Assert.assertEquals(storageId.getExternalId(), user.getUsername());
+// Assert.assertNull(user.getFederationLink());
+// }
+
+
+// // No sense to test this in no-import mode
+// @Test
+// @Ignore
+// @Override
+// public void testRemoveImportedUsers() {
+// }
+
+
+// @Test
+// @Override
+// public void testSearch() {
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username1", "John1", "Doel1", "user1@email.org", null, "121");
+// LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username2", "John2", "Doel2", "user2@email.org", null, "122");
+// LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username3", "John3", "Doel3", "user3@email.org", null, "123");
+// LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username4", "John4", "Doel4", "user4@email.org", null, "124");
+
+// // search by username
+// UserModel user = session.users().searchForUser("username1", appRealm).get(0);
+// LDAPTestAsserts.assertLoaded(user, "username1", "John1", "Doel1", "user1@email.org", "121");
+
+// // search by email
+// user = session.users().searchForUser("user2@email.org", appRealm).get(0);
+// LDAPTestAsserts.assertLoaded(user, "username2", "John2", "Doel2", "user2@email.org", "122");
+
+// // search by lastName
+// user = session.users().searchForUser("Doel3", appRealm).get(0);
+// LDAPTestAsserts.assertLoaded(user, "username3", "John3", "Doel3", "user3@email.org", "123");
+
+// // search by firstName + lastName
+// user = session.users().searchForUser("John4 Doel4", appRealm).get(0);
+// LDAPTestAsserts.assertLoaded(user, "username4", "John4", "Doel4", "user4@email.org", "124");
+// });
+// }
+
+
+// // No need to test this in no-import mode. There won't be any users in localStorage after LDAP search
+// @Test
+// @Ignore
+// @Override
+// public void testSearchByAttributes() {
+// }
+
+
+// @Test
+// @Override
+// public void testSearchWithCustomLDAPFilter() {
+// // Add custom filter for searching users
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// ctx.getLdapModel().getConfig().putSingle(LDAPConstants.CUSTOM_USER_SEARCH_FILTER, "(|(mail=user5@email.org)(mail=user6@email.org))");
+// appRealm.updateComponent(ctx.getLdapModel());
+// });
+
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username5", "John5", "Doel5", "user5@email.org", null, "125");
+// LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username6", "John6", "Doel6", "user6@email.org", null, "126");
+// LDAPTestUtils.addLDAPUser(ctx.getLdapProvider(), appRealm, "username7", "John7", "Doel7", "user7@email.org", null, "127");
+
+// // search by email
+// UserModel user = session.users().searchForUser("user5@email.org", appRealm).get(0);
+// LDAPTestAsserts.assertLoaded(user, "username5", "John5", "Doel5", "user5@email.org", "125");
- user = session.users().searchForUser("John6 Doel6", appRealm).get(0);
- LDAPTestAsserts.assertLoaded(user, "username6", "John6", "Doel6", "user6@email.org", "126");
+// user = session.users().searchForUser("John6 Doel6", appRealm).get(0);
+// LDAPTestAsserts.assertLoaded(user, "username6", "John6", "Doel6", "user6@email.org", "126");
- Assert.assertTrue(session.users().searchForUser("user7@email.org", appRealm).isEmpty());
- Assert.assertTrue(session.users().searchForUser("John7 Doel7", appRealm).isEmpty());
+// Assert.assertTrue(session.users().searchForUser("user7@email.org", appRealm).isEmpty());
+// Assert.assertTrue(session.users().searchForUser("John7 Doel7", appRealm).isEmpty());
- // Remove custom filter
- ctx.getLdapModel().getConfig().remove(LDAPConstants.CUSTOM_USER_SEARCH_FILTER);
- appRealm.updateComponent(ctx.getLdapModel());
- });
- }
-
-
- @Test
- @Override
- @Ignore // Unsynced mode doesn't have much sense in no-import
- public void testUnsynced() throws Exception {
- }
-
-
- @Test
- @Override
- @Ignore // Unlinking users doesn't have much sense in no-import
- public void zzTestUnlinkUsers() {
- }
+// // Remove custom filter
+// ctx.getLdapModel().getConfig().remove(LDAPConstants.CUSTOM_USER_SEARCH_FILTER);
+// appRealm.updateComponent(ctx.getLdapModel());
+// });
+// }
+
+
+// @Test
+// @Override
+// @Ignore // Unsynced mode doesn't have much sense in no-import
+// public void testUnsynced() throws Exception {
+// }
+
+
+// @Test
+// @Override
+// @Ignore // Unlinking users doesn't have much sense in no-import
+// public void zzTestUnlinkUsers() {
+// }
- @Test
- public void testFullNameMapperWriteOnly() {
- ComponentRepresentation firstNameMapperRep = testingClient.server().fetch(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- // assert that user "fullnameUser" is not in local DB
- Assert.assertNull(session.users().getUserByUsername("fullname", appRealm));
+// @Test
+// public void testFullNameMapperWriteOnly() {
+// ComponentRepresentation firstNameMapperRep = testingClient.server().fetch(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// // assert that user "fullnameUser" is not in local DB
+// Assert.assertNull(session.users().getUserByUsername("fullname", appRealm));
- // Add the user with some fullName into LDAP directly. Ensure that fullName is saved into "cn" attribute in LDAP (currently mapped to model firstName)
- ComponentModel ldapModel = LDAPTestUtils.getLdapProviderModel(session, appRealm);
- LDAPStorageProvider ldapFedProvider = LDAPTestUtils.getLdapProvider(session, ldapModel);
- LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "fullname", "James Dee", "Dee", "fullname@email.org", null, "4578");
-
- // add fullname mapper to the provider and remove "firstNameMapper". For this test, we will simply map full name to the LDAP attribute, which was before firstName ( "givenName" on active directory, "cn" on other LDAP servers)
- ComponentModel firstNameMapper = LDAPTestUtils.getSubcomponentByName(appRealm, ldapModel, "first name");
- String ldapFirstNameAttributeName = firstNameMapper.getConfig().getFirst(UserAttributeLDAPStorageMapper.LDAP_ATTRIBUTE);
- appRealm.removeComponent(firstNameMapper);
+// // Add the user with some fullName into LDAP directly. Ensure that fullName is saved into "cn" attribute in LDAP (currently mapped to model firstName)
+// ComponentModel ldapModel = LDAPTestUtils.getLdapProviderModel(session, appRealm);
+// LDAPStorageProvider ldapFedProvider = LDAPTestUtils.getLdapProvider(session, ldapModel);
+// LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "fullname", "James Dee", "Dee", "fullname@email.org", null, "4578");
+
+// // add fullname mapper to the provider and remove "firstNameMapper". For this test, we will simply map full name to the LDAP attribute, which was before firstName ( "givenName" on active directory, "cn" on other LDAP servers)
+// ComponentModel firstNameMapper = LDAPTestUtils.getSubcomponentByName(appRealm, ldapModel, "first name");
+// String ldapFirstNameAttributeName = firstNameMapper.getConfig().getFirst(UserAttributeLDAPStorageMapper.LDAP_ATTRIBUTE);
+// appRealm.removeComponent(firstNameMapper);
- ComponentRepresentation firstNameMapperRepp = ModelToRepresentation.toRepresentation(session, firstNameMapper, true);
+// ComponentRepresentation firstNameMapperRepp = ModelToRepresentation.toRepresentation(session, firstNameMapper, true);
- ComponentModel fullNameMapperModel = KeycloakModelUtils.createComponentModel("full name", ldapModel.getId(), FullNameLDAPStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(),
- FullNameLDAPStorageMapper.LDAP_FULL_NAME_ATTRIBUTE, ldapFirstNameAttributeName,
- FullNameLDAPStorageMapper.READ_ONLY, "false");
- appRealm.addComponentModel(fullNameMapperModel);
+// ComponentModel fullNameMapperModel = KeycloakModelUtils.createComponentModel("full name", ldapModel.getId(), FullNameLDAPStorageMapperFactory.PROVIDER_ID, LDAPStorageMapper.class.getName(),
+// FullNameLDAPStorageMapper.LDAP_FULL_NAME_ATTRIBUTE, ldapFirstNameAttributeName,
+// FullNameLDAPStorageMapper.READ_ONLY, "false");
+// appRealm.addComponentModel(fullNameMapperModel);
- return firstNameMapperRepp;
- }, ComponentRepresentation.class);
+// return firstNameMapperRepp;
+// }, ComponentRepresentation.class);
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
- // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName
- LDAPTestAsserts.assertUserImported(session.users(), appRealm, "fullname", "James", "Dee", "fullname@email.org", "4578");
+// // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName
+// LDAPTestAsserts.assertUserImported(session.users(), appRealm, "fullname", "James", "Dee", "fullname@email.org", "4578");
- // change mapper to writeOnly
- ComponentModel fullNameMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "full name");
- fullNameMapperModel.getConfig().putSingle(FullNameLDAPStorageMapper.WRITE_ONLY, "true");
- appRealm.updateComponent(fullNameMapperModel);
- });
-
- // User will be changed in LDAP too
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
+// // change mapper to writeOnly
+// ComponentModel fullNameMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "full name");
+// fullNameMapperModel.getConfig().putSingle(FullNameLDAPStorageMapper.WRITE_ONLY, "true");
+// appRealm.updateComponent(fullNameMapperModel);
+// });
+
+// // User will be changed in LDAP too
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
- UserModel fullnameUser = session.users().getUserByUsername("fullname", appRealm);
- fullnameUser.setFirstName("James2");
- fullnameUser.setLastName("Dee2");
- });
+// UserModel fullnameUser = session.users().getUserByUsername("fullname", appRealm);
+// fullnameUser.setFirstName("James2");
+// fullnameUser.setLastName("Dee2");
+// });
- // Assert changed user available in Keycloak, but his firstName is null (due the fullnameMapper is write-only and firstName mapper is removed)
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
+// // Assert changed user available in Keycloak, but his firstName is null (due the fullnameMapper is write-only and firstName mapper is removed)
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
- // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName
- LDAPTestAsserts.assertUserImported(session.users(), appRealm, "fullname", null, "Dee2", "fullname@email.org", "4578");
+// // Assert user is successfully imported in Keycloak DB now with correct firstName and lastName
+// LDAPTestAsserts.assertUserImported(session.users(), appRealm, "fullname", null, "Dee2", "fullname@email.org", "4578");
- // Remove "fullnameUser" to assert he is removed from LDAP. Revert mappers to previous state
- UserModel fullnameUser = session.users().getUserByUsername("fullname", appRealm);
- session.users().removeUser(appRealm, fullnameUser);
+// // Remove "fullnameUser" to assert he is removed from LDAP. Revert mappers to previous state
+// UserModel fullnameUser = session.users().getUserByUsername("fullname", appRealm);
+// session.users().removeUser(appRealm, fullnameUser);
- // Revert mappers
- ComponentModel fullNameMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "full name");
- appRealm.removeComponent(fullNameMapperModel);
- });
+// // Revert mappers
+// ComponentModel fullNameMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "full name");
+// appRealm.removeComponent(fullNameMapperModel);
+// });
- firstNameMapperRep.setId(null);
- Response response = testRealm().components().add(firstNameMapperRep);
- Assert.assertEquals(201, response.getStatus());
- response.close();
- }
+// firstNameMapperRep.setId(null);
+// Response response = testRealm().components().add(firstNameMapperRep);
+// Assert.assertEquals(201, response.getStatus());
+// response.close();
+// }
-}
+// }
diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPRoleMappingsNoImportTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPRoleMappingsNoImportTest.java
index e9bcba3..ea0ffe6 100644
--- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPRoleMappingsNoImportTest.java
+++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/ldap/noimport/LDAPRoleMappingsNoImportTest.java
@@ -1,355 +1,355 @@
-/*
- * Copyright 2017 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.testsuite.federation.ldap.noimport;
-
-import org.jboss.arquillian.container.test.api.Deployment;
-import org.jboss.arquillian.container.test.api.TargetsContainer;
-import org.jboss.shrinkwrap.api.spec.WebArchive;
-import org.junit.Assert;
-import org.junit.ClassRule;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.runners.MethodSorters;
-import org.keycloak.admin.client.resource.UserResource;
-import org.keycloak.component.ComponentModel;
-import org.keycloak.models.AccountRoles;
-import org.keycloak.models.ClientModel;
-import org.keycloak.models.Constants;
-import org.keycloak.models.LDAPConstants;
-import org.keycloak.models.RealmModel;
-import org.keycloak.models.RoleModel;
-import org.keycloak.models.UserModel;
-import org.keycloak.storage.UserStorageProviderModel;
-import org.keycloak.storage.ldap.LDAPStorageProvider;
-import org.keycloak.storage.ldap.idm.model.LDAPObject;
-import org.keycloak.storage.ldap.mappers.membership.LDAPGroupMapperMode;
-import org.keycloak.storage.ldap.mappers.membership.role.RoleLDAPStorageMapper;
-import org.keycloak.testsuite.federation.ldap.AbstractLDAPTest;
-import org.keycloak.testsuite.federation.ldap.LDAPTestContext;
-import org.keycloak.testsuite.runonserver.RunOnServerDeployment;
-import org.keycloak.testsuite.util.LDAPRule;
-import org.keycloak.testsuite.util.LDAPTestUtils;
-
-import java.util.Set;
-
-import static org.keycloak.testsuite.arquillian.DeploymentTargetModifier.AUTH_SERVER_CURRENT;
-
-/**
- * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
- */
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class LDAPRoleMappingsNoImportTest extends AbstractLDAPTest {
-
-
- @ClassRule
- public static LDAPRule ldapRule = new LDAPRule();
-
-
- @Deployment
- @TargetsContainer(AUTH_SERVER_CURRENT)
- public static WebArchive deploy() {
- return RunOnServerDeployment.create(UserResource.class, AbstractLDAPTest.class)
- .addPackages(true,
- "org.keycloak.testsuite",
- "org.keycloak.testsuite.federation.ldap",
- "org.keycloak.testsuite.federation.ldap.noimport");
- }
-
-
- @Override
- protected LDAPRule getLDAPRule() {
- return ldapRule;
- }
-
-
- @Override
- protected boolean isImportEnabled() {
- return false;
- }
-
- @Override
- protected void afterImportTestRealm() {
- // Disable pagination
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
-
- ctx.getLdapModel().put(LDAPConstants.PAGINATION, "false");
- appRealm.updateComponent(ctx.getLdapModel());
-
- });
-
-
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
- UserStorageProviderModel ldapModel = ctx.getLdapModel();
-
- LDAPTestUtils.addLocalUser(session, appRealm, "mary", "mary@test.com", "password-app");
-
-
- // Delete all LDAP users
- LDAPStorageProvider ldapFedProvider = LDAPTestUtils.getLdapProvider(session, ldapModel);
- LDAPTestUtils.removeAllLDAPUsers(ldapFedProvider, appRealm);
-
- // Add sample application
- ClientModel finance = appRealm.addClient("finance");
-
- // Delete all LDAP roles
- LDAPTestUtils.addOrUpdateRoleLDAPMappers(appRealm, ldapModel, LDAPGroupMapperMode.LDAP_ONLY);
- LDAPTestUtils.removeAllLDAPRoles(session, appRealm, ldapModel, "realmRolesMapper");
- LDAPTestUtils.removeAllLDAPRoles(session, appRealm, ldapModel, "financeRolesMapper");
+// /*
+// * Copyright 2017 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.testsuite.federation.ldap.noimport;
+
+// import org.jboss.arquillian.container.test.api.Deployment;
+// import org.jboss.arquillian.container.test.api.TargetsContainer;
+// import org.jboss.shrinkwrap.api.spec.WebArchive;
+// import org.junit.Assert;
+// import org.junit.ClassRule;
+// import org.junit.FixMethodOrder;
+// import org.junit.Test;
+// import org.junit.runners.MethodSorters;
+// import org.keycloak.admin.client.resource.UserResource;
+// import org.keycloak.component.ComponentModel;
+// import org.keycloak.models.AccountRoles;
+// import org.keycloak.models.ClientModel;
+// import org.keycloak.models.Constants;
+// import org.keycloak.models.LDAPConstants;
+// import org.keycloak.models.RealmModel;
+// import org.keycloak.models.RoleModel;
+// import org.keycloak.models.UserModel;
+// import org.keycloak.storage.UserStorageProviderModel;
+// import org.keycloak.storage.ldap.LDAPStorageProvider;
+// import org.keycloak.storage.ldap.idm.model.LDAPObject;
+// import org.keycloak.storage.ldap.mappers.membership.LDAPGroupMapperMode;
+// import org.keycloak.storage.ldap.mappers.membership.role.RoleLDAPStorageMapper;
+// import org.keycloak.testsuite.federation.ldap.AbstractLDAPTest;
+// import org.keycloak.testsuite.federation.ldap.LDAPTestContext;
+// import org.keycloak.testsuite.runonserver.RunOnServerDeployment;
+// import org.keycloak.testsuite.util.LDAPRule;
+// import org.keycloak.testsuite.util.LDAPTestUtils;
+
+// import java.util.Set;
+
+// import static org.keycloak.testsuite.arquillian.DeploymentTargetModifier.AUTH_SERVER_CURRENT;
+
+// /**
+// * @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
+// */
+// @FixMethodOrder(MethodSorters.NAME_ASCENDING)
+// public class LDAPRoleMappingsNoImportTest extends AbstractLDAPTest {
+
+
+// @ClassRule
+// public static LDAPRule ldapRule = new LDAPRule();
+
+
+// @Deployment
+// @TargetsContainer(AUTH_SERVER_CURRENT)
+// public static WebArchive deploy() {
+// return RunOnServerDeployment.create(UserResource.class, AbstractLDAPTest.class)
+// .addPackages(true,
+// "org.keycloak.testsuite",
+// "org.keycloak.testsuite.federation.ldap",
+// "org.keycloak.testsuite.federation.ldap.noimport");
+// }
+
+
+// @Override
+// protected LDAPRule getLDAPRule() {
+// return ldapRule;
+// }
+
+
+// @Override
+// protected boolean isImportEnabled() {
+// return false;
+// }
+
+// @Override
+// protected void afterImportTestRealm() {
+// // Disable pagination
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+
+// ctx.getLdapModel().put(LDAPConstants.PAGINATION, "false");
+// appRealm.updateComponent(ctx.getLdapModel());
+
+// });
+
+
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
+// UserStorageProviderModel ldapModel = ctx.getLdapModel();
+
+// LDAPTestUtils.addLocalUser(session, appRealm, "mary", "mary@test.com", "password-app");
+
+
+// // Delete all LDAP users
+// LDAPStorageProvider ldapFedProvider = LDAPTestUtils.getLdapProvider(session, ldapModel);
+// LDAPTestUtils.removeAllLDAPUsers(ldapFedProvider, appRealm);
+
+// // Add sample application
+// ClientModel finance = appRealm.addClient("finance");
+
+// // Delete all LDAP roles
+// LDAPTestUtils.addOrUpdateRoleLDAPMappers(appRealm, ldapModel, LDAPGroupMapperMode.LDAP_ONLY);
+// LDAPTestUtils.removeAllLDAPRoles(session, appRealm, ldapModel, "realmRolesMapper");
+// LDAPTestUtils.removeAllLDAPRoles(session, appRealm, ldapModel, "financeRolesMapper");
- // Add some users for testing
- LDAPObject john = LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "johnkeycloak", "John", "Doe", "john@email.org", null, "1234");
- LDAPTestUtils.updateLDAPPassword(ldapFedProvider, john, "Password1");
+// // Add some users for testing
+// LDAPObject john = LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "johnkeycloak", "John", "Doe", "john@email.org", null, "1234");
+// LDAPTestUtils.updateLDAPPassword(ldapFedProvider, john, "Password1");
- LDAPObject mary = LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "marykeycloak", "Mary", "Kelly", "mary@email.org", null, "5678");
- LDAPTestUtils.updateLDAPPassword(ldapFedProvider, mary, "Password1");
+// LDAPObject mary = LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "marykeycloak", "Mary", "Kelly", "mary@email.org", null, "5678");
+// LDAPTestUtils.updateLDAPPassword(ldapFedProvider, mary, "Password1");
- LDAPObject rob = LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "robkeycloak", "Rob", "Brown", "rob@email.org", null, "8910");
- LDAPTestUtils.updateLDAPPassword(ldapFedProvider, rob, "Password1");
+// LDAPObject rob = LDAPTestUtils.addLDAPUser(ldapFedProvider, appRealm, "robkeycloak", "Rob", "Brown", "rob@email.org", null, "8910");
+// LDAPTestUtils.updateLDAPPassword(ldapFedProvider, rob, "Password1");
- // Add some roles for testing
- LDAPTestUtils.createLDAPRole(session, appRealm, ldapModel, "realmRolesMapper", "realmRole1");
- LDAPTestUtils.createLDAPRole(session, appRealm, ldapModel, "realmRolesMapper", "realmRole2");
- LDAPTestUtils.createLDAPRole(session, appRealm, ldapModel, "financeRolesMapper", "financeRole1");
+// // Add some roles for testing
+// LDAPTestUtils.createLDAPRole(session, appRealm, ldapModel, "realmRolesMapper", "realmRole1");
+// LDAPTestUtils.createLDAPRole(session, appRealm, ldapModel, "realmRolesMapper", "realmRole2");
+// LDAPTestUtils.createLDAPRole(session, appRealm, ldapModel, "financeRolesMapper", "financeRole1");
- // Sync LDAP roles to Keycloak DB
- LDAPTestUtils.syncRolesFromLDAP(appRealm, ldapFedProvider, ldapModel);
- });
+// // Sync LDAP roles to Keycloak DB
+// LDAPTestUtils.syncRolesFromLDAP(appRealm, ldapFedProvider, ldapModel);
+// });
- }
+// }
- @Test
- public void test01ReadMappings() {
- testingClient.server().run(session -> {
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
+// @Test
+// public void test01ReadMappings() {
+// testingClient.server().run(session -> {
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
- LDAPTestUtils.addOrUpdateRoleLDAPMappers(appRealm, ctx.getLdapModel(), LDAPGroupMapperMode.LDAP_ONLY);
+// LDAPTestUtils.addOrUpdateRoleLDAPMappers(appRealm, ctx.getLdapModel(), LDAPGroupMapperMode.LDAP_ONLY);
- ComponentModel roleMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "realmRolesMapper");
- LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ctx.getLdapModel());
- RoleLDAPStorageMapper roleMapper = LDAPTestUtils.getRoleMapper(roleMapperModel, ldapProvider, appRealm);
+// ComponentModel roleMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "realmRolesMapper");
+// LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ctx.getLdapModel());
+// RoleLDAPStorageMapper roleMapper = LDAPTestUtils.getRoleMapper(roleMapperModel, ldapProvider, appRealm);
- LDAPObject maryLdap = ldapProvider.loadLDAPUserByUsername(appRealm, "marykeycloak");
- roleMapper.addRoleMappingInLDAP("realmRole1", maryLdap);
- roleMapper.addRoleMappingInLDAP("realmRole2", maryLdap);
- } );
+// LDAPObject maryLdap = ldapProvider.loadLDAPUserByUsername(appRealm, "marykeycloak");
+// roleMapper.addRoleMappingInLDAP("realmRole1", maryLdap);
+// roleMapper.addRoleMappingInLDAP("realmRole2", maryLdap);
+// } );
- testingClient.server().run(session -> {
- session.userCache().clear();
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
+// testingClient.server().run(session -> {
+// session.userCache().clear();
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
- UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm);
- // make sure we are in no-import mode!
- Assert.assertNull(session.userLocalStorage().getUserByUsername("marykeycloak", appRealm));
+// UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm);
+// // make sure we are in no-import mode!
+// Assert.assertNull(session.userLocalStorage().getUserByUsername("marykeycloak", appRealm));
- // This role should already exists as it was imported from LDAP
- RoleModel realmRole1 = appRealm.getRole("realmRole1");
+// // This role should already exists as it was imported from LDAP
+// RoleModel realmRole1 = appRealm.getRole("realmRole1");
- // This role should already exists as it was imported from LDAP
- RoleModel realmRole2 = appRealm.getRole("realmRole2");
+// // This role should already exists as it was imported from LDAP
+// RoleModel realmRole2 = appRealm.getRole("realmRole2");
- Set<RoleModel> maryRoles = mary.getRealmRoleMappings();
- Assert.assertTrue(maryRoles.contains(realmRole1));
- Assert.assertTrue(maryRoles.contains(realmRole2));
+// Set<RoleModel> maryRoles = mary.getRealmRoleMappings();
+// Assert.assertTrue(maryRoles.contains(realmRole1));
+// Assert.assertTrue(maryRoles.contains(realmRole2));
- // Add some role mappings directly into LDAP
- ComponentModel roleMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "realmRolesMapper");
- LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ctx.getLdapModel());
- RoleLDAPStorageMapper roleMapper = LDAPTestUtils.getRoleMapper(roleMapperModel, ldapProvider, appRealm);
+// // Add some role mappings directly into LDAP
+// ComponentModel roleMapperModel = LDAPTestUtils.getSubcomponentByName(appRealm, ctx.getLdapModel(), "realmRolesMapper");
+// LDAPStorageProvider ldapProvider = LDAPTestUtils.getLdapProvider(session, ctx.getLdapModel());
+// RoleLDAPStorageMapper roleMapper = LDAPTestUtils.getRoleMapper(roleMapperModel, ldapProvider, appRealm);
- LDAPObject maryLdap = ldapProvider.loadLDAPUserByUsername(appRealm, "marykeycloak");
- deleteRoleMappingsInLDAP(roleMapper, maryLdap, "realmRole1");
- deleteRoleMappingsInLDAP(roleMapper, maryLdap, "realmRole2");
- });
+// LDAPObject maryLdap = ldapProvider.loadLDAPUserByUsername(appRealm, "marykeycloak");
+// deleteRoleMappingsInLDAP(roleMapper, maryLdap, "realmRole1");
+// deleteRoleMappingsInLDAP(roleMapper, maryLdap, "realmRole2");
+// });
- testingClient.server().run(session -> {
- session.userCache().clear();
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
+// testingClient.server().run(session -> {
+// session.userCache().clear();
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
- UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm);
- // This role should already exists as it was imported from LDAP
- RoleModel realmRole1 = appRealm.getRole("realmRole1");
+// UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm);
+// // This role should already exists as it was imported from LDAP
+// RoleModel realmRole1 = appRealm.getRole("realmRole1");
- // This role should already exists as it was imported from LDAP
- RoleModel realmRole2 = appRealm.getRole("realmRole2");
+// // This role should already exists as it was imported from LDAP
+// RoleModel realmRole2 = appRealm.getRole("realmRole2");
- Set<RoleModel> maryRoles = mary.getRealmRoleMappings();
- Assert.assertFalse(maryRoles.contains(realmRole1));
- Assert.assertFalse(maryRoles.contains(realmRole2));
- });
- }
+// Set<RoleModel> maryRoles = mary.getRealmRoleMappings();
+// Assert.assertFalse(maryRoles.contains(realmRole1));
+// Assert.assertFalse(maryRoles.contains(realmRole2));
+// });
+// }
- @Test
- public void test02WriteMappings() {
- testingClient.server().run(session -> {
- session.userCache().clear();
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
+// @Test
+// public void test02WriteMappings() {
+// testingClient.server().run(session -> {
+// session.userCache().clear();
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
- LDAPTestUtils.addOrUpdateRoleLDAPMappers(appRealm, ctx.getLdapModel(), LDAPGroupMapperMode.LDAP_ONLY);
+// LDAPTestUtils.addOrUpdateRoleLDAPMappers(appRealm, ctx.getLdapModel(), LDAPGroupMapperMode.LDAP_ONLY);
- UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm);
- UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm);
+// UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm);
+// UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm);
- // make sure we are in no-import mode
- Assert.assertNull(session.userLocalStorage().getUserByUsername("johnkeycloak", appRealm));
- Assert.assertNull(session.userLocalStorage().getUserByUsername("marykeycloak", appRealm));
+// // make sure we are in no-import mode
+// Assert.assertNull(session.userLocalStorage().getUserByUsername("johnkeycloak", appRealm));
+// Assert.assertNull(session.userLocalStorage().getUserByUsername("marykeycloak", appRealm));
- // 1 - Grant some roles in LDAP
+// // 1 - Grant some roles in LDAP
- // This role should already exists as it was imported from LDAP
- RoleModel realmRole1 = appRealm.getRole("realmRole1");
- john.grantRole(realmRole1);
+// // This role should already exists as it was imported from LDAP
+// RoleModel realmRole1 = appRealm.getRole("realmRole1");
+// john.grantRole(realmRole1);
- // This role should already exists as it was imported from LDAP
- RoleModel realmRole2 = appRealm.getRole("realmRole2");
- mary.grantRole(realmRole2);
+// // This role should already exists as it was imported from LDAP
+// RoleModel realmRole2 = appRealm.getRole("realmRole2");
+// mary.grantRole(realmRole2);
- // This role may already exists from previous test (was imported from LDAP), but may not
- RoleModel realmRole3 = appRealm.getRole("realmRole3");
- if (realmRole3 == null) {
- realmRole3 = appRealm.addRole("realmRole3");
- }
+// // This role may already exists from previous test (was imported from LDAP), but may not
+// RoleModel realmRole3 = appRealm.getRole("realmRole3");
+// if (realmRole3 == null) {
+// realmRole3 = appRealm.addRole("realmRole3");
+// }
- john.grantRole(realmRole3);
- mary.grantRole(realmRole3);
+// john.grantRole(realmRole3);
+// mary.grantRole(realmRole3);
- ClientModel accountApp = appRealm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);
- ClientModel financeApp = appRealm.getClientByClientId("finance");
+// ClientModel accountApp = appRealm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);
+// ClientModel financeApp = appRealm.getClientByClientId("finance");
- RoleModel manageAccountRole = accountApp.getRole(AccountRoles.MANAGE_ACCOUNT);
- RoleModel financeRole1 = financeApp.getRole("financeRole1");
- john.grantRole(financeRole1);
- session.userCache().clear();
- });
+// RoleModel manageAccountRole = accountApp.getRole(AccountRoles.MANAGE_ACCOUNT);
+// RoleModel financeRole1 = financeApp.getRole("financeRole1");
+// john.grantRole(financeRole1);
+// session.userCache().clear();
+// });
- testingClient.server().run(session -> {
- session.userCache().clear();
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
+// testingClient.server().run(session -> {
+// session.userCache().clear();
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
- UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm);
- UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm);
+// UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm);
+// UserModel mary = session.users().getUserByUsername("marykeycloak", appRealm);
- // make sure we are in no-import mode
- Assert.assertNull(session.userLocalStorage().getUserByUsername("johnkeycloak", appRealm));
- Assert.assertNull(session.userLocalStorage().getUserByUsername("marykeycloak", appRealm));
+// // make sure we are in no-import mode
+// Assert.assertNull(session.userLocalStorage().getUserByUsername("johnkeycloak", appRealm));
+// Assert.assertNull(session.userLocalStorage().getUserByUsername("marykeycloak", appRealm));
- RoleModel realmRole1 = appRealm.getRole("realmRole1");
- RoleModel realmRole2 = appRealm.getRole("realmRole2");
- RoleModel realmRole3 = appRealm.getRole("realmRole3");
- ClientModel accountApp = appRealm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);
- ClientModel financeApp = appRealm.getClientByClientId("finance");
- RoleModel manageAccountRole = accountApp.getRole(AccountRoles.MANAGE_ACCOUNT);
- RoleModel financeRole1 = financeApp.getRole("financeRole1");
+// RoleModel realmRole1 = appRealm.getRole("realmRole1");
+// RoleModel realmRole2 = appRealm.getRole("realmRole2");
+// RoleModel realmRole3 = appRealm.getRole("realmRole3");
+// ClientModel accountApp = appRealm.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID);
+// ClientModel financeApp = appRealm.getClientByClientId("finance");
+// RoleModel manageAccountRole = accountApp.getRole(AccountRoles.MANAGE_ACCOUNT);
+// RoleModel financeRole1 = financeApp.getRole("financeRole1");
- // 3 - Check that role mappings are in LDAP and hence available through federation
+// // 3 - Check that role mappings are in LDAP and hence available through federation
- Set<RoleModel> johnRoles = john.getRoleMappings();
- Assert.assertTrue(johnRoles.contains(realmRole1));
- Assert.assertFalse(johnRoles.contains(realmRole2));
- Assert.assertTrue(johnRoles.contains(realmRole3));
- Assert.assertTrue(johnRoles.contains(financeRole1));
- Assert.assertTrue(johnRoles.contains(manageAccountRole));
+// Set<RoleModel> johnRoles = john.getRoleMappings();
+// Assert.assertTrue(johnRoles.contains(realmRole1));
+// Assert.assertFalse(johnRoles.contains(realmRole2));
+// Assert.assertTrue(johnRoles.contains(realmRole3));
+// Assert.assertTrue(johnRoles.contains(financeRole1));
+// Assert.assertTrue(johnRoles.contains(manageAccountRole));
- Set<RoleModel> johnRealmRoles = john.getRealmRoleMappings();
- Assert.assertEquals(2, johnRealmRoles.size());
- Assert.assertTrue(johnRealmRoles.contains(realmRole1));
- Assert.assertTrue(johnRealmRoles.contains(realmRole3));
+// Set<RoleModel> johnRealmRoles = john.getRealmRoleMappings();
+// Assert.assertEquals(2, johnRealmRoles.size());
+// Assert.assertTrue(johnRealmRoles.contains(realmRole1));
+// Assert.assertTrue(johnRealmRoles.contains(realmRole3));
- // account roles are not mapped in LDAP. Those are in Keycloak DB
- Set<RoleModel> johnAccountRoles = john.getClientRoleMappings(accountApp);
- Assert.assertTrue(johnAccountRoles.contains(manageAccountRole));
+// // account roles are not mapped in LDAP. Those are in Keycloak DB
+// Set<RoleModel> johnAccountRoles = john.getClientRoleMappings(accountApp);
+// Assert.assertTrue(johnAccountRoles.contains(manageAccountRole));
- Set<RoleModel> johnFinanceRoles = john.getClientRoleMappings(financeApp);
- Assert.assertEquals(1, johnFinanceRoles.size());
- Assert.assertTrue(johnFinanceRoles.contains(financeRole1));
+// Set<RoleModel> johnFinanceRoles = john.getClientRoleMappings(financeApp);
+// Assert.assertEquals(1, johnFinanceRoles.size());
+// Assert.assertTrue(johnFinanceRoles.contains(financeRole1));
- // 4 - Delete some role mappings and check they are deleted
+// // 4 - Delete some role mappings and check they are deleted
- john.deleteRoleMapping(realmRole3);
- john.deleteRoleMapping(realmRole1);
- john.deleteRoleMapping(financeRole1);
+// john.deleteRoleMapping(realmRole3);
+// john.deleteRoleMapping(realmRole1);
+// john.deleteRoleMapping(financeRole1);
- johnRoles = john.getRoleMappings();
- Assert.assertFalse(johnRoles.contains(realmRole1));
- Assert.assertFalse(johnRoles.contains(realmRole2));
- Assert.assertFalse(johnRoles.contains(realmRole3));
- Assert.assertFalse(johnRoles.contains(financeRole1));
+// johnRoles = john.getRoleMappings();
+// Assert.assertFalse(johnRoles.contains(realmRole1));
+// Assert.assertFalse(johnRoles.contains(realmRole2));
+// Assert.assertFalse(johnRoles.contains(realmRole3));
+// Assert.assertFalse(johnRoles.contains(financeRole1));
- // Cleanup
- mary.deleteRoleMapping(realmRole2);
- mary.deleteRoleMapping(realmRole3);
- session.userCache().clear();
- });
- }
+// // Cleanup
+// mary.deleteRoleMapping(realmRole2);
+// mary.deleteRoleMapping(realmRole3);
+// session.userCache().clear();
+// });
+// }
- @Test
- public void test03_newUserDefaultRolesNoImportModeTest() throws Exception {
+// @Test
+// public void test03_newUserDefaultRolesNoImportModeTest() throws Exception {
- // Check user group memberships
- testingClient.server().run(session -> {
- session.userCache().clear();
- LDAPTestContext ctx = LDAPTestContext.init(session);
- RealmModel appRealm = ctx.getRealm();
+// // Check user group memberships
+// testingClient.server().run(session -> {
+// session.userCache().clear();
+// LDAPTestContext ctx = LDAPTestContext.init(session);
+// RealmModel appRealm = ctx.getRealm();
- LDAPTestUtils.addOrUpdateRoleLDAPMappers(appRealm, ctx.getLdapModel(), LDAPGroupMapperMode.LDAP_ONLY);
+// LDAPTestUtils.addOrUpdateRoleLDAPMappers(appRealm, ctx.getLdapModel(), LDAPGroupMapperMode.LDAP_ONLY);
- // Set a default role on the realm
- appRealm.addDefaultRole("realmRole1");
+// // Set a default role on the realm
+// appRealm.addDefaultRole("realmRole1");
- UserModel david = session.users().addUser(appRealm, "davidkeycloak");
+// UserModel david = session.users().addUser(appRealm, "davidkeycloak");
- // make sure we are in no-import mode
- Assert.assertNull(session.userLocalStorage().getUserByUsername("davidkeycloak", appRealm));
+// // make sure we are in no-import mode
+// Assert.assertNull(session.userLocalStorage().getUserByUsername("davidkeycloak", appRealm));
- RoleModel defaultRole = appRealm.getRole("realmRole1");
- RoleModel realmRole2 = appRealm.getRole("realmRole2");
+// RoleModel defaultRole = appRealm.getRole("realmRole1");
+// RoleModel realmRole2 = appRealm.getRole("realmRole2");
- Assert.assertNotNull(defaultRole);
- Assert.assertNotNull(realmRole2);
+// Assert.assertNotNull(defaultRole);
+// Assert.assertNotNull(realmRole2);
- Set<RoleModel> davidRoles = david.getRealmRoleMappings();
+// Set<RoleModel> davidRoles = david.getRealmRoleMappings();
- Assert.assertTrue(davidRoles.contains(defaultRole));
- Assert.assertFalse(davidRoles.contains(realmRole2));
+// Assert.assertTrue(davidRoles.contains(defaultRole));
+// Assert.assertFalse(davidRoles.contains(realmRole2));
- // Make sure john has not received the default role
- UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm);
- Set<RoleModel> johnRoles = john.getRealmRoleMappings();
+// // Make sure john has not received the default role
+// UserModel john = session.users().getUserByUsername("johnkeycloak", appRealm);
+// Set<RoleModel> johnRoles = john.getRealmRoleMappings();
- Assert.assertFalse(johnRoles.contains(defaultRole));
- });
- }
+// Assert.assertFalse(johnRoles.contains(defaultRole));
+// });
+// }
- private static void deleteRoleMappingsInLDAP(RoleLDAPStorageMapper roleMapper, LDAPObject ldapUser, String roleName) {
- LDAPObject ldapRole1 = roleMapper.loadLDAPRoleByName(roleName);
- roleMapper.deleteRoleMappingInLDAP(ldapUser, ldapRole1);
- }
-}
+// private static void deleteRoleMappingsInLDAP(RoleLDAPStorageMapper roleMapper, LDAPObject ldapUser, String roleName) {
+// LDAPObject ldapRole1 = roleMapper.loadLDAPRoleByName(roleName);
+// roleMapper.deleteRoleMappingInLDAP(ldapUser, ldapRole1);
+// }
+// }
diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/ClientStorageTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/ClientStorageTest.java
index 4deb2ce..c7bea0f 100644
--- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/ClientStorageTest.java
+++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/ClientStorageTest.java
@@ -1,460 +1,460 @@
-/*
- * Copyright 2017 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.testsuite.federation.storage;
-
-import org.jboss.arquillian.container.test.api.Deployment;
-import org.jboss.arquillian.graphene.page.Page;
-import org.jboss.shrinkwrap.api.spec.WebArchive;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.keycloak.OAuth2Constants;
-import org.keycloak.admin.client.resource.UserResource;
-import org.keycloak.common.util.MultivaluedHashMap;
-import org.keycloak.events.Details;
-import org.keycloak.models.ClientModel;
-import org.keycloak.models.Constants;
-import org.keycloak.models.RealmModel;
-import org.keycloak.models.cache.infinispan.ClientAdapter;
-import org.keycloak.representations.AccessToken;
-import org.keycloak.representations.RefreshToken;
-import org.keycloak.representations.idm.ComponentRepresentation;
-import org.keycloak.representations.idm.EventRepresentation;
-import org.keycloak.representations.idm.RealmRepresentation;
-import org.keycloak.storage.CacheableStorageProviderModel;
-import org.keycloak.storage.client.ClientStorageProvider;
-import org.keycloak.storage.client.ClientStorageProviderModel;
-import org.keycloak.testsuite.AbstractTestRealmKeycloakTest;
-import org.keycloak.testsuite.AssertEvents;
-import org.keycloak.testsuite.admin.ApiUtil;
-import org.keycloak.testsuite.federation.HardcodedClientStorageProviderFactory;
-import org.keycloak.testsuite.pages.AppPage;
-import org.keycloak.testsuite.pages.ErrorPage;
-import org.keycloak.testsuite.pages.LoginPage;
-import org.keycloak.testsuite.runonserver.RunOnServerDeployment;
-import org.keycloak.testsuite.util.OAuthClient;
-import org.keycloak.util.BasicAuthHelper;
-import org.keycloak.util.TokenUtil;
-
-import javax.ws.rs.NotFoundException;
-import javax.ws.rs.client.Client;
-import javax.ws.rs.client.Entity;
-import javax.ws.rs.client.WebTarget;
-import javax.ws.rs.core.Form;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.Response;
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.util.Calendar;
-import java.util.List;
-import java.util.Map;
-
-import static java.util.Calendar.DAY_OF_WEEK;
-import static java.util.Calendar.HOUR_OF_DAY;
-import static java.util.Calendar.MINUTE;
-import static org.junit.Assert.assertEquals;
-import static org.keycloak.testsuite.admin.ApiUtil.findUserByUsername;
-
-/**
- * Test that clients can override auth flows
- *
- * @author <a href="mailto:bburke@redhat.com">Bill Burke</a>
- */
-public class ClientStorageTest extends AbstractTestRealmKeycloakTest {
- @Rule
- public AssertEvents events = new AssertEvents(this);
-
- @Page
- protected AppPage appPage;
-
- @Page
- protected LoginPage loginPage;
-
- @Page
- protected ErrorPage errorPage;
-
- @Override
- public void configureTestRealm(RealmRepresentation testRealm) {
- }
-
- protected String providerId;
-
- @Deployment
- public static WebArchive deploy() {
- return RunOnServerDeployment.create(UserResource.class)
- .addPackages(true, "org.keycloak.testsuite");
- }
-
- protected String addComponent(ComponentRepresentation component) {
- Response resp = adminClient.realm("test").components().add(component);
- resp.close();
- String id = ApiUtil.getCreatedId(resp);
- getCleanup().addComponentId(id);
- return id;
- }
-
- @Before
- public void addProvidersBeforeTest() throws URISyntaxException, IOException {
- ComponentRepresentation provider = new ComponentRepresentation();
- provider.setName("client-storage-hardcoded");
- provider.setProviderId(HardcodedClientStorageProviderFactory.PROVIDER_ID);
- provider.setProviderType(ClientStorageProvider.class.getName());
- provider.setConfig(new MultivaluedHashMap<>());
- provider.getConfig().putSingle(HardcodedClientStorageProviderFactory.CLIENT_ID, "hardcoded-client");
- provider.getConfig().putSingle(HardcodedClientStorageProviderFactory.REDIRECT_URI, oauth.getRedirectUri());
-
- providerId = addComponent(provider);
- }
-
- protected String userId;
-
- @Before
- public void clientConfiguration() {
- userId = findUserByUsername(adminClient.realm("test"), "test-user@localhost").getId();
- oauth.clientId("hardcoded-client");
- }
-
-
-
-
-
- @Test
- public void testClientStats() throws Exception {
- testDirectGrant("hardcoded-client");
- testDirectGrant("hardcoded-client");
- testBrowser("test-app");
- offlineTokenDirectGrantFlowNoRefresh();
- List<Map<String, String>> list = adminClient.realm("test").getClientSessionStats();
- boolean hardTested = false;
- boolean testAppTested = false;
- for (Map<String, String> entry : list) {
- if (entry.get("clientId").equals("hardcoded-client")) {
- Assert.assertEquals("3", entry.get("active"));
- Assert.assertEquals("1", entry.get("offline"));
- hardTested = true;
- } else if (entry.get("clientId").equals("test-app")) {
- Assert.assertEquals("1", entry.get("active"));
- Assert.assertEquals("0", entry.get("offline"));
- testAppTested = true;
- }
- }
- Assert.assertTrue(hardTested && testAppTested);
- }
-
-
- @Test
- public void testBrowser() throws Exception {
- String clientId = "hardcoded-client";
- testBrowser(clientId);
- //Thread.sleep(10000000);
- }
-
- private void testBrowser(String clientId) {
- oauth.clientId(clientId);
- String loginFormUrl = oauth.getLoginFormUrl();
- //log.info("loginFormUrl: " + loginFormUrl);
-
- //Thread.sleep(10000000);
-
- driver.navigate().to(loginFormUrl);
-
- loginPage.assertCurrent();
-
- // Fill username+password. I am successfully authenticated
- oauth.fillLoginForm("test-user@localhost", "password");
- appPage.assertCurrent();
-
- events.expectLogin().client(clientId).detail(Details.USERNAME, "test-user@localhost").assertEvent();
-
- String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
- OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password");
- Assert.assertNotNull(tokenResponse.getAccessToken());
- Assert.assertNotNull(tokenResponse.getRefreshToken());
-
- events.clear();
-
- }
-
- @Test
- public void testGrantAccessTokenNoOverride() throws Exception {
- testDirectGrant("hardcoded-client");
- }
-
- private void testDirectGrant(String clientId) {
- Client httpClient = javax.ws.rs.client.ClientBuilder.newClient();
- String grantUri = oauth.getResourceOwnerPasswordCredentialGrantUrl();
- WebTarget grantTarget = httpClient.target(grantUri);
-
- { // test no password
- String header = BasicAuthHelper.createHeader(clientId, "password");
- Form form = new Form();
- form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
- form.param("username", "test-user@localhost");
- Response response = grantTarget.request()
- .header(HttpHeaders.AUTHORIZATION, header)
- .post(Entity.form(form));
- assertEquals(401, response.getStatus());
- response.close();
- }
-
- { // test invalid password
- String header = BasicAuthHelper.createHeader(clientId, "password");
- Form form = new Form();
- form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
- form.param("username", "test-user@localhost");
- form.param("password", "invalid");
- Response response = grantTarget.request()
- .header(HttpHeaders.AUTHORIZATION, header)
- .post(Entity.form(form));
- assertEquals(401, response.getStatus());
- response.close();
- }
-
- { // test valid password
- String header = BasicAuthHelper.createHeader(clientId, "password");
- Form form = new Form();
- form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
- form.param("username", "test-user@localhost");
- form.param("password", "password");
- Response response = grantTarget.request()
- .header(HttpHeaders.AUTHORIZATION, header)
- .post(Entity.form(form));
- assertEquals(200, response.getStatus());
- response.close();
- }
-
- httpClient.close();
- events.clear();
- }
-
- @Test
- public void testDailyEviction() {
- testIsCached();
-
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- ClientStorageProviderModel model = realm.getClientStorageProviders().get(0);
- Calendar eviction = Calendar.getInstance();
- eviction.add(Calendar.HOUR, 1);
- model.setCachePolicy(CacheableStorageProviderModel.CachePolicy.EVICT_DAILY);
- model.setEvictionHour(eviction.get(HOUR_OF_DAY));
- model.setEvictionMinute(eviction.get(MINUTE));
- realm.updateComponent(model);
- });
- testIsCached();
- setTimeOffset(2 * 60 * 60); // 2 hours in future
- testNotCached();
- testIsCached();
-
- setDefaultCachePolicy();
- testIsCached();
-
- }
- @Test
- public void testWeeklyEviction() {
- testIsCached();
-
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- ClientStorageProviderModel model = realm.getClientStorageProviders().get(0);
- Calendar eviction = Calendar.getInstance();
- eviction.add(Calendar.HOUR, 4 * 24);
- model.setCachePolicy(CacheableStorageProviderModel.CachePolicy.EVICT_WEEKLY);
- model.setEvictionDay(eviction.get(DAY_OF_WEEK));
- model.setEvictionHour(eviction.get(HOUR_OF_DAY));
- model.setEvictionMinute(eviction.get(MINUTE));
- realm.updateComponent(model);
- });
- testIsCached();
- setTimeOffset(2 * 24 * 60 * 60); // 2 days in future
- testIsCached();
- setTimeOffset(5 * 24 * 60 * 60); // 5 days in future
- testNotCached();
- testIsCached();
-
- setDefaultCachePolicy();
- testIsCached();
-
- }
- @Test
- public void testMaxLifespan() {
- testIsCached();
-
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- ClientStorageProviderModel model = realm.getClientStorageProviders().get(0);
- model.setCachePolicy(CacheableStorageProviderModel.CachePolicy.MAX_LIFESPAN);
- model.setMaxLifespan(1 * 60 * 60 * 1000);
- realm.updateComponent(model);
- });
- testIsCached();
-
- setTimeOffset(1/2 * 60 * 60); // 1/2 hour in future
-
- testIsCached();
-
- setTimeOffset(2 * 60 * 60); // 2 hours in future
-
- testNotCached();
- testIsCached();
-
- setDefaultCachePolicy();
- testIsCached();
-
- }
-
- private void testNotCached() {
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- ClientModel hardcoded = realm.getClientByClientId("hardcoded-client");
- Assert.assertNotNull(hardcoded);
- Assert.assertFalse(hardcoded instanceof ClientAdapter);
- });
- }
-
-
- @Test
- public void testIsCached() {
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- ClientModel hardcoded = realm.getClientByClientId("hardcoded-client");
- Assert.assertNotNull(hardcoded);
- Assert.assertTrue(hardcoded instanceof org.keycloak.models.cache.infinispan.ClientAdapter);
- });
- }
-
-
- @Test
- public void testNoCache() {
- testIsCached();
-
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- ClientStorageProviderModel model = realm.getClientStorageProviders().get(0);
- model.setCachePolicy(CacheableStorageProviderModel.CachePolicy.NO_CACHE);
- realm.updateComponent(model);
- });
-
- testNotCached();
-
- // test twice because updating component should evict
- testNotCached();
-
- // set it back
- setDefaultCachePolicy();
- testIsCached();
-
-
- }
-
- private void setDefaultCachePolicy() {
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- ClientStorageProviderModel model = realm.getClientStorageProviders().get(0);
- model.setCachePolicy(CacheableStorageProviderModel.CachePolicy.DEFAULT);
- realm.updateComponent(model);
- });
- }
-
- @Test
- public void offlineTokenDirectGrantFlow() throws Exception {
- oauth.scope(OAuth2Constants.OFFLINE_ACCESS);
- oauth.clientId("hardcoded-client");
- OAuthClient.AccessTokenResponse tokenResponse = oauth.doGrantAccessTokenRequest("password", "test-user@localhost", "password");
- Assert.assertNull(tokenResponse.getErrorDescription());
- AccessToken token = oauth.verifyToken(tokenResponse.getAccessToken());
- String offlineTokenString = tokenResponse.getRefreshToken();
- RefreshToken offlineToken = oauth.parseRefreshToken(offlineTokenString);
-
- events.expectLogin()
- .client("hardcoded-client")
- .user(userId)
- .session(token.getSessionState())
- .detail(Details.GRANT_TYPE, OAuth2Constants.PASSWORD)
- .detail(Details.TOKEN_ID, token.getId())
- .detail(Details.REFRESH_TOKEN_ID, offlineToken.getId())
- .detail(Details.REFRESH_TOKEN_TYPE, TokenUtil.TOKEN_TYPE_OFFLINE)
- .detail(Details.USERNAME, "test-user@localhost")
- .removeDetail(Details.CODE_ID)
- .removeDetail(Details.REDIRECT_URI)
- .removeDetail(Details.CONSENT)
- .assertEvent();
-
- Assert.assertEquals(TokenUtil.TOKEN_TYPE_OFFLINE, offlineToken.getType());
- Assert.assertEquals(0, offlineToken.getExpiration());
-
- testRefreshWithOfflineToken(token, offlineToken, offlineTokenString, token.getSessionState(), userId);
-
- // Assert same token can be refreshed again
- testRefreshWithOfflineToken(token, offlineToken, offlineTokenString, token.getSessionState(), userId);
- }
- public void offlineTokenDirectGrantFlowNoRefresh() throws Exception {
- oauth.scope(OAuth2Constants.OFFLINE_ACCESS);
- oauth.clientId("hardcoded-client");
- OAuthClient.AccessTokenResponse tokenResponse = oauth.doGrantAccessTokenRequest("password", "test-user@localhost", "password");
- Assert.assertNull(tokenResponse.getErrorDescription());
- AccessToken token = oauth.verifyToken(tokenResponse.getAccessToken());
- String offlineTokenString = tokenResponse.getRefreshToken();
- RefreshToken offlineToken = oauth.parseRefreshToken(offlineTokenString);
- }
-
- private String testRefreshWithOfflineToken(AccessToken oldToken, RefreshToken offlineToken, String offlineTokenString,
- final String sessionId, String userId) {
- // Change offset to big value to ensure userSession expired
- setTimeOffset(99999);
- Assert.assertFalse(oldToken.isActive());
- Assert.assertTrue(offlineToken.isActive());
-
- // Assert userSession expired
- testingClient.testing().removeExpired("test");
- try {
- testingClient.testing().removeUserSession("test", sessionId);
- } catch (NotFoundException nfe) {
- // Ignore
- }
-
- OAuthClient.AccessTokenResponse response = oauth.doRefreshTokenRequest(offlineTokenString, "password");
- AccessToken refreshedToken = oauth.verifyToken(response.getAccessToken());
- Assert.assertEquals(200, response.getStatusCode());
- Assert.assertEquals(sessionId, refreshedToken.getSessionState());
-
- // Assert new refreshToken in the response
- String newRefreshToken = response.getRefreshToken();
- Assert.assertNotNull(newRefreshToken);
- Assert.assertNotEquals(oldToken.getId(), refreshedToken.getId());
-
- Assert.assertEquals(userId, refreshedToken.getSubject());
-
- Assert.assertTrue(refreshedToken.getRealmAccess().isUserInRole(Constants.OFFLINE_ACCESS_ROLE));
-
-
- EventRepresentation refreshEvent = events.expectRefresh(offlineToken.getId(), sessionId)
- .client("hardcoded-client")
- .user(userId)
- .removeDetail(Details.UPDATED_REFRESH_TOKEN_ID)
- .detail(Details.REFRESH_TOKEN_TYPE, TokenUtil.TOKEN_TYPE_OFFLINE)
- .assertEvent();
- Assert.assertNotEquals(oldToken.getId(), refreshEvent.getDetails().get(Details.TOKEN_ID));
-
- setTimeOffset(0);
- return newRefreshToken;
- }
-
-
-}
+// /*
+// * Copyright 2017 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.testsuite.federation.storage;
+
+// import org.jboss.arquillian.container.test.api.Deployment;
+// import org.jboss.arquillian.graphene.page.Page;
+// import org.jboss.shrinkwrap.api.spec.WebArchive;
+// import org.junit.Assert;
+// import org.junit.Before;
+// import org.junit.Rule;
+// import org.junit.Test;
+// import org.keycloak.OAuth2Constants;
+// import org.keycloak.admin.client.resource.UserResource;
+// import org.keycloak.common.util.MultivaluedHashMap;
+// import org.keycloak.events.Details;
+// import org.keycloak.models.ClientModel;
+// import org.keycloak.models.Constants;
+// import org.keycloak.models.RealmModel;
+// import org.keycloak.models.cache.infinispan.ClientAdapter;
+// import org.keycloak.representations.AccessToken;
+// import org.keycloak.representations.RefreshToken;
+// import org.keycloak.representations.idm.ComponentRepresentation;
+// import org.keycloak.representations.idm.EventRepresentation;
+// import org.keycloak.representations.idm.RealmRepresentation;
+// import org.keycloak.storage.CacheableStorageProviderModel;
+// import org.keycloak.storage.client.ClientStorageProvider;
+// import org.keycloak.storage.client.ClientStorageProviderModel;
+// import org.keycloak.testsuite.AbstractTestRealmKeycloakTest;
+// import org.keycloak.testsuite.AssertEvents;
+// import org.keycloak.testsuite.admin.ApiUtil;
+// import org.keycloak.testsuite.federation.HardcodedClientStorageProviderFactory;
+// import org.keycloak.testsuite.pages.AppPage;
+// import org.keycloak.testsuite.pages.ErrorPage;
+// import org.keycloak.testsuite.pages.LoginPage;
+// import org.keycloak.testsuite.runonserver.RunOnServerDeployment;
+// import org.keycloak.testsuite.util.OAuthClient;
+// import org.keycloak.util.BasicAuthHelper;
+// import org.keycloak.util.TokenUtil;
+
+// import javax.ws.rs.NotFoundException;
+// import javax.ws.rs.client.Client;
+// import javax.ws.rs.client.Entity;
+// import javax.ws.rs.client.WebTarget;
+// import javax.ws.rs.core.Form;
+// import javax.ws.rs.core.HttpHeaders;
+// import javax.ws.rs.core.Response;
+// import java.io.IOException;
+// import java.net.URISyntaxException;
+// import java.util.Calendar;
+// import java.util.List;
+// import java.util.Map;
+
+// import static java.util.Calendar.DAY_OF_WEEK;
+// import static java.util.Calendar.HOUR_OF_DAY;
+// import static java.util.Calendar.MINUTE;
+// import static org.junit.Assert.assertEquals;
+// import static org.keycloak.testsuite.admin.ApiUtil.findUserByUsername;
+
+// /**
+// * Test that clients can override auth flows
+// *
+// * @author <a href="mailto:bburke@redhat.com">Bill Burke</a>
+// */
+// public class ClientStorageTest extends AbstractTestRealmKeycloakTest {
+// @Rule
+// public AssertEvents events = new AssertEvents(this);
+
+// @Page
+// protected AppPage appPage;
+
+// @Page
+// protected LoginPage loginPage;
+
+// @Page
+// protected ErrorPage errorPage;
+
+// @Override
+// public void configureTestRealm(RealmRepresentation testRealm) {
+// }
+
+// protected String providerId;
+
+// @Deployment
+// public static WebArchive deploy() {
+// return RunOnServerDeployment.create(UserResource.class)
+// .addPackages(true, "org.keycloak.testsuite");
+// }
+
+// protected String addComponent(ComponentRepresentation component) {
+// Response resp = adminClient.realm("test").components().add(component);
+// resp.close();
+// String id = ApiUtil.getCreatedId(resp);
+// getCleanup().addComponentId(id);
+// return id;
+// }
+
+// @Before
+// public void addProvidersBeforeTest() throws URISyntaxException, IOException {
+// ComponentRepresentation provider = new ComponentRepresentation();
+// provider.setName("client-storage-hardcoded");
+// provider.setProviderId(HardcodedClientStorageProviderFactory.PROVIDER_ID);
+// provider.setProviderType(ClientStorageProvider.class.getName());
+// provider.setConfig(new MultivaluedHashMap<>());
+// provider.getConfig().putSingle(HardcodedClientStorageProviderFactory.CLIENT_ID, "hardcoded-client");
+// provider.getConfig().putSingle(HardcodedClientStorageProviderFactory.REDIRECT_URI, oauth.getRedirectUri());
+
+// providerId = addComponent(provider);
+// }
+
+// protected String userId;
+
+// @Before
+// public void clientConfiguration() {
+// userId = findUserByUsername(adminClient.realm("test"), "test-user@localhost").getId();
+// oauth.clientId("hardcoded-client");
+// }
+
+
+
+
+
+// @Test
+// public void testClientStats() throws Exception {
+// testDirectGrant("hardcoded-client");
+// testDirectGrant("hardcoded-client");
+// testBrowser("test-app");
+// offlineTokenDirectGrantFlowNoRefresh();
+// List<Map<String, String>> list = adminClient.realm("test").getClientSessionStats();
+// boolean hardTested = false;
+// boolean testAppTested = false;
+// for (Map<String, String> entry : list) {
+// if (entry.get("clientId").equals("hardcoded-client")) {
+// Assert.assertEquals("3", entry.get("active"));
+// Assert.assertEquals("1", entry.get("offline"));
+// hardTested = true;
+// } else if (entry.get("clientId").equals("test-app")) {
+// Assert.assertEquals("1", entry.get("active"));
+// Assert.assertEquals("0", entry.get("offline"));
+// testAppTested = true;
+// }
+// }
+// Assert.assertTrue(hardTested && testAppTested);
+// }
+
+
+// @Test
+// public void testBrowser() throws Exception {
+// String clientId = "hardcoded-client";
+// testBrowser(clientId);
+// //Thread.sleep(10000000);
+// }
+
+// private void testBrowser(String clientId) {
+// oauth.clientId(clientId);
+// String loginFormUrl = oauth.getLoginFormUrl();
+// //log.info("loginFormUrl: " + loginFormUrl);
+
+// //Thread.sleep(10000000);
+
+// driver.navigate().to(loginFormUrl);
+
+// loginPage.assertCurrent();
+
+// // Fill username+password. I am successfully authenticated
+// oauth.fillLoginForm("test-user@localhost", "password");
+// appPage.assertCurrent();
+
+// events.expectLogin().client(clientId).detail(Details.USERNAME, "test-user@localhost").assertEvent();
+
+// String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
+// OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password");
+// Assert.assertNotNull(tokenResponse.getAccessToken());
+// Assert.assertNotNull(tokenResponse.getRefreshToken());
+
+// events.clear();
+
+// }
+
+// @Test
+// public void testGrantAccessTokenNoOverride() throws Exception {
+// testDirectGrant("hardcoded-client");
+// }
+
+// private void testDirectGrant(String clientId) {
+// Client httpClient = javax.ws.rs.client.ClientBuilder.newClient();
+// String grantUri = oauth.getResourceOwnerPasswordCredentialGrantUrl();
+// WebTarget grantTarget = httpClient.target(grantUri);
+
+// { // test no password
+// String header = BasicAuthHelper.createHeader(clientId, "password");
+// Form form = new Form();
+// form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
+// form.param("username", "test-user@localhost");
+// Response response = grantTarget.request()
+// .header(HttpHeaders.AUTHORIZATION, header)
+// .post(Entity.form(form));
+// assertEquals(401, response.getStatus());
+// response.close();
+// }
+
+// { // test invalid password
+// String header = BasicAuthHelper.createHeader(clientId, "password");
+// Form form = new Form();
+// form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
+// form.param("username", "test-user@localhost");
+// form.param("password", "invalid");
+// Response response = grantTarget.request()
+// .header(HttpHeaders.AUTHORIZATION, header)
+// .post(Entity.form(form));
+// assertEquals(401, response.getStatus());
+// response.close();
+// }
+
+// { // test valid password
+// String header = BasicAuthHelper.createHeader(clientId, "password");
+// Form form = new Form();
+// form.param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.PASSWORD);
+// form.param("username", "test-user@localhost");
+// form.param("password", "password");
+// Response response = grantTarget.request()
+// .header(HttpHeaders.AUTHORIZATION, header)
+// .post(Entity.form(form));
+// assertEquals(200, response.getStatus());
+// response.close();
+// }
+
+// httpClient.close();
+// events.clear();
+// }
+
+// @Test
+// public void testDailyEviction() {
+// testIsCached();
+
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// ClientStorageProviderModel model = realm.getClientStorageProviders().get(0);
+// Calendar eviction = Calendar.getInstance();
+// eviction.add(Calendar.HOUR, 1);
+// model.setCachePolicy(CacheableStorageProviderModel.CachePolicy.EVICT_DAILY);
+// model.setEvictionHour(eviction.get(HOUR_OF_DAY));
+// model.setEvictionMinute(eviction.get(MINUTE));
+// realm.updateComponent(model);
+// });
+// testIsCached();
+// setTimeOffset(2 * 60 * 60); // 2 hours in future
+// testNotCached();
+// testIsCached();
+
+// setDefaultCachePolicy();
+// testIsCached();
+
+// }
+// @Test
+// public void testWeeklyEviction() {
+// testIsCached();
+
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// ClientStorageProviderModel model = realm.getClientStorageProviders().get(0);
+// Calendar eviction = Calendar.getInstance();
+// eviction.add(Calendar.HOUR, 4 * 24);
+// model.setCachePolicy(CacheableStorageProviderModel.CachePolicy.EVICT_WEEKLY);
+// model.setEvictionDay(eviction.get(DAY_OF_WEEK));
+// model.setEvictionHour(eviction.get(HOUR_OF_DAY));
+// model.setEvictionMinute(eviction.get(MINUTE));
+// realm.updateComponent(model);
+// });
+// testIsCached();
+// setTimeOffset(2 * 24 * 60 * 60); // 2 days in future
+// testIsCached();
+// setTimeOffset(5 * 24 * 60 * 60); // 5 days in future
+// testNotCached();
+// testIsCached();
+
+// setDefaultCachePolicy();
+// testIsCached();
+
+// }
+// @Test
+// public void testMaxLifespan() {
+// testIsCached();
+
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// ClientStorageProviderModel model = realm.getClientStorageProviders().get(0);
+// model.setCachePolicy(CacheableStorageProviderModel.CachePolicy.MAX_LIFESPAN);
+// model.setMaxLifespan(1 * 60 * 60 * 1000);
+// realm.updateComponent(model);
+// });
+// testIsCached();
+
+// setTimeOffset(1/2 * 60 * 60); // 1/2 hour in future
+
+// testIsCached();
+
+// setTimeOffset(2 * 60 * 60); // 2 hours in future
+
+// testNotCached();
+// testIsCached();
+
+// setDefaultCachePolicy();
+// testIsCached();
+
+// }
+
+// private void testNotCached() {
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// ClientModel hardcoded = realm.getClientByClientId("hardcoded-client");
+// Assert.assertNotNull(hardcoded);
+// Assert.assertFalse(hardcoded instanceof ClientAdapter);
+// });
+// }
+
+
+// @Test
+// public void testIsCached() {
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// ClientModel hardcoded = realm.getClientByClientId("hardcoded-client");
+// Assert.assertNotNull(hardcoded);
+// Assert.assertTrue(hardcoded instanceof org.keycloak.models.cache.infinispan.ClientAdapter);
+// });
+// }
+
+
+// @Test
+// public void testNoCache() {
+// testIsCached();
+
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// ClientStorageProviderModel model = realm.getClientStorageProviders().get(0);
+// model.setCachePolicy(CacheableStorageProviderModel.CachePolicy.NO_CACHE);
+// realm.updateComponent(model);
+// });
+
+// testNotCached();
+
+// // test twice because updating component should evict
+// testNotCached();
+
+// // set it back
+// setDefaultCachePolicy();
+// testIsCached();
+
+
+// }
+
+// private void setDefaultCachePolicy() {
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// ClientStorageProviderModel model = realm.getClientStorageProviders().get(0);
+// model.setCachePolicy(CacheableStorageProviderModel.CachePolicy.DEFAULT);
+// realm.updateComponent(model);
+// });
+// }
+
+// @Test
+// public void offlineTokenDirectGrantFlow() throws Exception {
+// oauth.scope(OAuth2Constants.OFFLINE_ACCESS);
+// oauth.clientId("hardcoded-client");
+// OAuthClient.AccessTokenResponse tokenResponse = oauth.doGrantAccessTokenRequest("password", "test-user@localhost", "password");
+// Assert.assertNull(tokenResponse.getErrorDescription());
+// AccessToken token = oauth.verifyToken(tokenResponse.getAccessToken());
+// String offlineTokenString = tokenResponse.getRefreshToken();
+// RefreshToken offlineToken = oauth.parseRefreshToken(offlineTokenString);
+
+// events.expectLogin()
+// .client("hardcoded-client")
+// .user(userId)
+// .session(token.getSessionState())
+// .detail(Details.GRANT_TYPE, OAuth2Constants.PASSWORD)
+// .detail(Details.TOKEN_ID, token.getId())
+// .detail(Details.REFRESH_TOKEN_ID, offlineToken.getId())
+// .detail(Details.REFRESH_TOKEN_TYPE, TokenUtil.TOKEN_TYPE_OFFLINE)
+// .detail(Details.USERNAME, "test-user@localhost")
+// .removeDetail(Details.CODE_ID)
+// .removeDetail(Details.REDIRECT_URI)
+// .removeDetail(Details.CONSENT)
+// .assertEvent();
+
+// Assert.assertEquals(TokenUtil.TOKEN_TYPE_OFFLINE, offlineToken.getType());
+// Assert.assertEquals(0, offlineToken.getExpiration());
+
+// testRefreshWithOfflineToken(token, offlineToken, offlineTokenString, token.getSessionState(), userId);
+
+// // Assert same token can be refreshed again
+// testRefreshWithOfflineToken(token, offlineToken, offlineTokenString, token.getSessionState(), userId);
+// }
+// public void offlineTokenDirectGrantFlowNoRefresh() throws Exception {
+// oauth.scope(OAuth2Constants.OFFLINE_ACCESS);
+// oauth.clientId("hardcoded-client");
+// OAuthClient.AccessTokenResponse tokenResponse = oauth.doGrantAccessTokenRequest("password", "test-user@localhost", "password");
+// Assert.assertNull(tokenResponse.getErrorDescription());
+// AccessToken token = oauth.verifyToken(tokenResponse.getAccessToken());
+// String offlineTokenString = tokenResponse.getRefreshToken();
+// RefreshToken offlineToken = oauth.parseRefreshToken(offlineTokenString);
+// }
+
+// private String testRefreshWithOfflineToken(AccessToken oldToken, RefreshToken offlineToken, String offlineTokenString,
+// final String sessionId, String userId) {
+// // Change offset to big value to ensure userSession expired
+// setTimeOffset(99999);
+// Assert.assertFalse(oldToken.isActive());
+// Assert.assertTrue(offlineToken.isActive());
+
+// // Assert userSession expired
+// testingClient.testing().removeExpired("test");
+// try {
+// testingClient.testing().removeUserSession("test", sessionId);
+// } catch (NotFoundException nfe) {
+// // Ignore
+// }
+
+// OAuthClient.AccessTokenResponse response = oauth.doRefreshTokenRequest(offlineTokenString, "password");
+// AccessToken refreshedToken = oauth.verifyToken(response.getAccessToken());
+// Assert.assertEquals(200, response.getStatusCode());
+// Assert.assertEquals(sessionId, refreshedToken.getSessionState());
+
+// // Assert new refreshToken in the response
+// String newRefreshToken = response.getRefreshToken();
+// Assert.assertNotNull(newRefreshToken);
+// Assert.assertNotEquals(oldToken.getId(), refreshedToken.getId());
+
+// Assert.assertEquals(userId, refreshedToken.getSubject());
+
+// Assert.assertTrue(refreshedToken.getRealmAccess().isUserInRole(Constants.OFFLINE_ACCESS_ROLE));
+
+
+// EventRepresentation refreshEvent = events.expectRefresh(offlineToken.getId(), sessionId)
+// .client("hardcoded-client")
+// .user(userId)
+// .removeDetail(Details.UPDATED_REFRESH_TOKEN_ID)
+// .detail(Details.REFRESH_TOKEN_TYPE, TokenUtil.TOKEN_TYPE_OFFLINE)
+// .assertEvent();
+// Assert.assertNotEquals(oldToken.getId(), refreshEvent.getDetails().get(Details.TOKEN_ID));
+
+// setTimeOffset(0);
+// return newRefreshToken;
+// }
+
+
+// }
diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageTest.java
index a6bdc68..9a540c4 100644
--- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageTest.java
+++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageTest.java
@@ -1,788 +1,788 @@
-package org.keycloak.testsuite.federation.storage;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Calendar;
-import static java.util.Calendar.DAY_OF_WEEK;
-import static java.util.Calendar.HOUR_OF_DAY;
-import static java.util.Calendar.MINUTE;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import javax.ws.rs.NotFoundException;
-import javax.ws.rs.core.Response;
-
-import org.apache.commons.io.FileUtils;
-import org.jboss.arquillian.container.test.api.Deployment;
-import org.jboss.shrinkwrap.api.spec.WebArchive;
-import org.junit.After;
-import org.junit.Assert;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.keycloak.admin.client.resource.UserResource;
-import org.keycloak.common.util.MultivaluedHashMap;
-import org.keycloak.models.RealmModel;
-import org.keycloak.models.UserModel;
-import static org.keycloak.models.UserModel.RequiredAction.UPDATE_PROFILE;
-import org.keycloak.models.cache.CachedUserModel;
-import org.keycloak.representations.idm.ComponentRepresentation;
-import org.keycloak.representations.idm.GroupRepresentation;
-import org.keycloak.representations.idm.RealmRepresentation;
-import org.keycloak.representations.idm.RoleRepresentation;
-import org.keycloak.representations.idm.UserRepresentation;
-import org.keycloak.storage.UserStorageProvider;
-import static org.keycloak.storage.UserStorageProviderModel.CACHE_POLICY;
-import org.keycloak.storage.CacheableStorageProviderModel.CachePolicy;
-import static org.keycloak.storage.UserStorageProviderModel.EVICTION_DAY;
-import static org.keycloak.storage.UserStorageProviderModel.EVICTION_HOUR;
-import static org.keycloak.storage.UserStorageProviderModel.EVICTION_MINUTE;
-import static org.keycloak.storage.UserStorageProviderModel.MAX_LIFESPAN;
-import org.keycloak.testsuite.AbstractAuthTest;
-import org.keycloak.testsuite.admin.ApiUtil;
-import org.keycloak.testsuite.federation.UserMapStorage;
-import org.keycloak.testsuite.federation.UserMapStorageFactory;
-import org.keycloak.testsuite.federation.UserPropertyFileStorageFactory;
-import org.keycloak.testsuite.pages.LoginPage;
-import org.keycloak.testsuite.pages.RegisterPage;
-import org.keycloak.testsuite.pages.VerifyEmailPage;
-import org.keycloak.testsuite.runonserver.RunOnServerDeployment;
-import org.keycloak.testsuite.updaters.RealmAttributeUpdater;
-import org.keycloak.testsuite.util.GreenMailRule;
-import java.util.Map;
-import javax.mail.internet.MimeMessage;
-import org.jboss.arquillian.graphene.page.Page;
-import org.junit.Rule;
-import static org.keycloak.testsuite.actions.RequiredActionEmailVerificationTest.getPasswordResetEmailLink;
-import static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlDoesntStartWith;
-import static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlStartsWith;
-
-/**
- *
- * @author tkyjovsk
- */
-public class UserStorageTest extends AbstractAuthTest {
-
- private String memProviderId;
- private String propProviderROId;
- private String propProviderRWId;
-
- @Rule
- public GreenMailRule greenMail = new GreenMailRule();
-
- @Page
- protected LoginPage loginPage;
-
- @Page
- protected RegisterPage registerPage;
-
- @Page
- protected VerifyEmailPage verifyEmailPage;
-
- private static final File CONFIG_DIR = new File(System.getProperty("auth.server.config.dir", ""));
-
- @Before
- public void addProvidersBeforeTest() throws URISyntaxException, IOException {
- ComponentRepresentation memProvider = new ComponentRepresentation();
- memProvider.setName("memory");
- memProvider.setProviderId(UserMapStorageFactory.PROVIDER_ID);
- memProvider.setProviderType(UserStorageProvider.class.getName());
- memProvider.setConfig(new MultivaluedHashMap<>());
- memProvider.getConfig().putSingle("priority", Integer.toString(0));
-
- memProviderId = addComponent(memProvider);
-
- // copy files used by the following RO/RW user providers
- File stResDir = new File(getClass().getResource("/storage-test").toURI());
- if (stResDir.exists() && stResDir.isDirectory() && CONFIG_DIR.exists() && CONFIG_DIR.isDirectory()) {
- for (File f : stResDir.listFiles()) {
- log.infof("Copying %s to %s", f.getName(), CONFIG_DIR.getAbsolutePath());
- FileUtils.copyFileToDirectory(f, CONFIG_DIR);
- }
- } else {
- throw new RuntimeException("Property `auth.server.config.dir` must be set to run UserStorageTests.");
- }
-
- ComponentRepresentation propProviderRO = new ComponentRepresentation();
- propProviderRO.setName("read-only-user-props");
- propProviderRO.setProviderId(UserPropertyFileStorageFactory.PROVIDER_ID);
- propProviderRO.setProviderType(UserStorageProvider.class.getName());
- propProviderRO.setConfig(new MultivaluedHashMap<>());
- propProviderRO.getConfig().putSingle("priority", Integer.toString(1));
- propProviderRO.getConfig().putSingle("propertyFile",
- CONFIG_DIR.getAbsolutePath() + File.separator + "read-only-user-password.properties");
-
- propProviderROId = addComponent(propProviderRO);
-
- propProviderRWId = addComponent(newPropProviderRW());
-
- }
-
- @After
- public void removeTestUser() throws URISyntaxException, IOException {
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- if (realm == null) {
- return;
- }
-
- UserModel user = session.users().getUserByUsername("thor", realm);
- if (user != null) {
- session.userLocalStorage().removeUser(realm, user);
- session.userCache().clear();
- }
- });
- }
-
- protected ComponentRepresentation newPropProviderRW() {
- ComponentRepresentation propProviderRW = new ComponentRepresentation();
- propProviderRW.setName("user-props");
- propProviderRW.setProviderId(UserPropertyFileStorageFactory.PROVIDER_ID);
- propProviderRW.setProviderType(UserStorageProvider.class.getName());
- propProviderRW.setConfig(new MultivaluedHashMap<>());
- propProviderRW.getConfig().putSingle("priority", Integer.toString(2));
- propProviderRW.getConfig().putSingle("propertyFile", CONFIG_DIR.getAbsolutePath() + File.separator + "user-password.properties");
- propProviderRW.getConfig().putSingle("federatedStorage", "true");
- return propProviderRW;
- }
-
- protected String addComponent(ComponentRepresentation component) {
- Response resp = testRealmResource().components().add(component);
- resp.close();
- String id = ApiUtil.getCreatedId(resp);
- getCleanup().addComponentId(id);
- return id;
- }
-
- private void loginSuccessAndLogout(String username, String password) {
- testRealmAccountPage.navigateTo();
- testRealmLoginPage.form().login(username, password);
- assertCurrentUrlStartsWith(testRealmAccountPage);
- testRealmAccountPage.logOut();
- }
-
- public void loginBadPassword(String username) {
- testRealmAccountPage.navigateTo();
- testRealmLoginPage.form().login(username, "badpassword");
- assertCurrentUrlDoesntStartWith(testRealmAccountPage);
- }
-
-// @Test
- public void listComponents() {
- log.info("COMPONENTS:");
- testRealmResource().components().query().forEach((c) -> {
- log.infof("%s - %s - %s", c.getId(), c.getProviderType(), c.getName());
- });
- }
-
- @Test
- public void testLoginSuccess() {
- loginSuccessAndLogout("tbrady", "goat");
- loginSuccessAndLogout("thor", "hammer");
- loginBadPassword("tbrady");
- }
-
- @Test
- public void testUpdate() {
- UserRepresentation thor = ApiUtil.findUserByUsername(testRealmResource(), "thor");
-
- // update entity
- thor.setFirstName("Stian");
- thor.setLastName("Thorgersen");
- thor.setEmailVerified(true);
- long thorCreated = System.currentTimeMillis() - 100;
- thor.setCreatedTimestamp(thorCreated);
- thor.setEmail("thor@hammer.com");
- thor.setAttributes(new HashMap<>());
- thor.getAttributes().put("test-attribute", Arrays.asList("value"));
- thor.setRequiredActions(new ArrayList<>());
- thor.getRequiredActions().add(UPDATE_PROFILE.name());
- testRealmResource().users().get(thor.getId()).update(thor);
-
- // check entity
- thor = ApiUtil.findUserByUsername(testRealmResource(), "thor");
- Assert.assertEquals("Stian", thor.getFirstName());
- Assert.assertEquals("Thorgersen", thor.getLastName());
- Assert.assertEquals("thor@hammer.com", thor.getEmail());
- Assert.assertTrue(thor.getAttributes().containsKey("test-attribute"));
- Assert.assertEquals(1, thor.getAttributes().get("test-attribute").size());
- Assert.assertEquals("value", thor.getAttributes().get("test-attribute").get(0));
- Assert.assertTrue(thor.isEmailVerified());
-
- // update group
- GroupRepresentation g = new GroupRepresentation();
- g.setName("my-group");
- String gid = ApiUtil.getCreatedId(testRealmResource().groups().add(g));
-
- testRealmResource().users().get(thor.getId()).joinGroup(gid);
-
- // check group
- boolean foundGroup = false;
- for (GroupRepresentation ug : testRealmResource().users().get(thor.getId()).groups()) {
- if (ug.getId().equals(gid)) {
- foundGroup = true;
- }
- }
- Assert.assertTrue(foundGroup);
-
- // check required actions
- assertTrue(thor.getRequiredActions().contains(UPDATE_PROFILE.name()));
- // remove req. actions
- thor.getRequiredActions().remove(UPDATE_PROFILE.name());
- testRealmResource().users().get(thor.getId()).update(thor);
-
- // change pass
- ApiUtil.resetUserPassword(testRealmResource().users().get(thor.getId()), "lightning", false);
- loginSuccessAndLogout("thor", "lightning");
-
- // update role
- RoleRepresentation r = new RoleRepresentation("foo-role", "foo role", false);
- testRealmResource().roles().create(r);
- ApiUtil.assignRealmRoles(testRealmResource(), thor.getId(), "foo-role");
-
- // check role
- boolean foundRole = false;
- for (RoleRepresentation rr : user(thor.getId()).roles().getAll().getRealmMappings()) {
- if ("foo-role".equals(rr.getName())) {
- foundRole = true;
- break;
- }
- }
- assertTrue(foundRole);
-
- // test removal of provider
- testRealmResource().components().component(propProviderRWId).remove();
- propProviderRWId = addComponent(newPropProviderRW());
- loginSuccessAndLogout("thor", "hammer");
-
- thor = ApiUtil.findUserByUsername(testRealmResource(), "thor");
-
- Assert.assertNull(thor.getFirstName());
- Assert.assertNull(thor.getLastName());
- Assert.assertNull(thor.getEmail());
- Assert.assertNull(thor.getAttributes());
- Assert.assertFalse(thor.isEmailVerified());
-
- foundGroup = false;
- for (GroupRepresentation ug : testRealmResource().users().get(thor.getId()).groups()) {
- if (ug.getId().equals(gid)) {
- foundGroup = true;
- }
- }
- Assert.assertFalse(foundGroup);
-
- foundRole = false;
- for (RoleRepresentation rr : user(thor.getId()).roles().getAll().getRealmMappings()) {
- if ("foo-role".equals(rr.getName())) {
- foundRole = true;
- break;
- }
- }
- assertFalse(foundRole);
- }
-
- @Test
- public void testRegisterWithRequiredEmail() throws Exception {
- try (AutoCloseable c = new RealmAttributeUpdater(testRealmResource())
- .updateWith(r -> {
- Map<String, String> config = new HashMap<>();
- config.put("from", "auto@keycloak.org");
- config.put("host", "0.0.0.0");
- config.put("port", "3025");
- r.setSmtpServer(config);
- r.setRegistrationAllowed(true);
- r.setVerifyEmail(true);
- })
- .update()) {
-
- testRealmAccountPage.navigateTo();
- loginPage.clickRegister();
- registerPage.register("firstName", "lastName", "email@mail.com", "verifyEmail", "password", "password");
-
- verifyEmailPage.assertCurrent();
-
- Assert.assertEquals(1, greenMail.getReceivedMessages().length);
-
- MimeMessage message = greenMail.getReceivedMessages()[0];
-
- String verificationUrl = getPasswordResetEmailLink(message);
-
- driver.navigate().to(verificationUrl.trim());
-
- testRealmAccountPage.assertCurrent();
- }
- }
-
- public UserResource user(String userId) {
- return testRealmResource().users().get(userId);
- }
-
- @Test
- public void testRegistration() {
- UserRepresentation memuser = new UserRepresentation();
- memuser.setUsername("memuser");
- String uid = ApiUtil.createUserAndResetPasswordWithAdminClient(testRealmResource(), memuser, "password");
- loginSuccessAndLogout("memuser", "password");
- loginSuccessAndLogout("memuser", "password");
- loginSuccessAndLogout("memuser", "password");
-
- memuser = user(uid).toRepresentation();
- assertNotNull(memuser);
- assertNotNull(memuser.getOrigin());
- ComponentRepresentation origin = testRealmResource().components().component(memuser.getOrigin()).toRepresentation();
- Assert.assertEquals("memory", origin.getName());
-
- testRealmResource().users().get(memuser.getId()).remove();
- try {
- user(uid).toRepresentation(); // provider doesn't implement UserQueryProvider --> have to lookup by uid
- fail("`memuser` wasn't removed");
- } catch (NotFoundException nfe) {
- // expected
- }
- }
-
- @Test
- public void testQuery() {
- Set<UserRepresentation> queried = new HashSet<>();
- int first = 0;
- while (queried.size() < 8) {
- List<UserRepresentation> results = testRealmResource().users().search("", first, 3);
- log.debugf("first=%s, results: %s", first, results.size());
- if (results.isEmpty()) {
- break;
- }
- first += results.size();
- queried.addAll(results);
- }
- Set<String> usernames = new HashSet<>();
- for (UserRepresentation user : queried) {
- usernames.add(user.getUsername());
- log.info(user.getUsername());
- }
- Assert.assertEquals(8, queried.size());
- Assert.assertTrue(usernames.contains("thor"));
- Assert.assertTrue(usernames.contains("zeus"));
- Assert.assertTrue(usernames.contains("apollo"));
- Assert.assertTrue(usernames.contains("perseus"));
- Assert.assertTrue(usernames.contains("tbrady"));
- Assert.assertTrue(usernames.contains("rob"));
- Assert.assertTrue(usernames.contains("jules"));
- Assert.assertTrue(usernames.contains("danny"));
-
- // test searchForUser
- List<UserRepresentation> users = testRealmResource().users().search("tbrady", 0, Integer.MAX_VALUE);
- Assert.assertTrue(users.size() == 1);
- Assert.assertTrue(users.get(0).getUsername().equals("tbrady"));
-
- // test getGroupMembers()
- GroupRepresentation g = new GroupRepresentation();
- g.setName("gods");
- String gid = ApiUtil.getCreatedId(testRealmResource().groups().add(g));
-
- UserRepresentation user = ApiUtil.findUserByUsername(testRealmResource(), "apollo");
- testRealmResource().users().get(user.getId()).joinGroup(gid);
- user = ApiUtil.findUserByUsername(testRealmResource(), "zeus");
- testRealmResource().users().get(user.getId()).joinGroup(gid);
- user = ApiUtil.findUserByUsername(testRealmResource(), "thor");
- testRealmResource().users().get(user.getId()).joinGroup(gid);
- queried.clear();
- usernames.clear();
-
- first = 0;
- while (queried.size() < 8) {
- List<UserRepresentation> results = testRealmResource().groups().group(gid).members(first, 1);
- log.debugf("first=%s, results: %s", first, results.size());
- if (results.isEmpty()) {
- break;
- }
- first += results.size();
- queried.addAll(results);
- }
- for (UserRepresentation u : queried) {
- usernames.add(u.getUsername());
- log.info(u.getUsername());
- }
- Assert.assertEquals(3, queried.size());
- Assert.assertTrue(usernames.contains("apollo"));
- Assert.assertTrue(usernames.contains("zeus"));
- Assert.assertTrue(usernames.contains("thor"));
-
- // search by single attribute
- // FIXME - no equivalent for model in REST
- }
-
- @Deployment
- public static WebArchive deploy() {
- return RunOnServerDeployment.create(UserResource.class)
- .addPackages(true, "org.keycloak.testsuite");
- }
-
- private void setDailyEvictionTime(int hour, int minutes) {
- if (hour < 0 || hour > 23) {
- throw new IllegalArgumentException("hour == " + hour);
- }
- if (minutes < 0 || minutes > 59) {
- throw new IllegalArgumentException("minutes == " + minutes);
- }
- ComponentRepresentation propProviderRW = testRealmResource().components().component(propProviderRWId).toRepresentation();
- propProviderRW.getConfig().putSingle(CACHE_POLICY, CachePolicy.EVICT_DAILY.name());
- propProviderRW.getConfig().putSingle(EVICTION_HOUR, String.valueOf(hour));
- propProviderRW.getConfig().putSingle(EVICTION_MINUTE, String.valueOf(minutes));
- testRealmResource().components().component(propProviderRWId).update(propProviderRW);
- }
-
-
- /**
- * Test daily eviction behaviour
- */
- @Test
- public void testDailyEviction() {
-
- // We need to test both cases: eviction the same day, and eviction the next day
- // Simplest is to take full control of the clock
-
- // set clock to 23:30 of current day
- setTimeOfDay(23, 30, 0);
-
- // test same day eviction behaviour
- // set eviction at 23:45
- setDailyEvictionTime(23, 45);
-
- // there are users in cache already from before-test import
- // and they didn't use any time offset clock so they may have timestamps in the 'future'
-
- // let's clear cache
- testingClient.server().run(session -> {
- session.userCache().clear();
- });
-
-
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("thor", realm);
- Assert.assertTrue(user instanceof CachedUserModel); // should be newly cached
- });
-
-
- setTimeOfDay(23, 40, 0);
-
- // lookup user again - make sure it's returned from cache
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("thor", realm);
- Assert.assertTrue(user instanceof CachedUserModel); // should be returned from cache
- });
-
-
- setTimeOfDay(23, 50, 0);
-
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("thor", realm);
- Assert.assertFalse(user instanceof CachedUserModel); // should have been invalidated
- });
-
-
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("thor", realm);
- Assert.assertTrue(user instanceof CachedUserModel); // should have been newly cached
- });
-
-
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("thor", realm);
- Assert.assertTrue(user instanceof CachedUserModel); // should be returned from cache
- });
-
-
- setTimeOfDay(23, 55, 0);
-
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("thor", realm);
- Assert.assertTrue(user instanceof CachedUserModel); // should be returned from cache
- });
-
-
- // at 00:30
- // it's next day now. the daily eviction time is now in the future
- setTimeOfDay(0, 30, 0, 24 * 60 * 60);
-
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("thor", realm);
- Assert.assertTrue(user instanceof CachedUserModel); // should be returned from cache - it's still good for almost the whole day
- });
-
-
- // at 23:30 next day
- setTimeOfDay(23, 30, 0, 24 * 60 * 60);
-
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("thor", realm);
- Assert.assertTrue(user instanceof CachedUserModel); // should be returned from cache - it's still good until 23:45
- });
+// package org.keycloak.testsuite.federation.storage;
+
+// import java.io.File;
+// import java.io.IOException;
+// import java.net.URISyntaxException;
+// import java.util.ArrayList;
+// import java.util.Arrays;
+// import java.util.Calendar;
+// import static java.util.Calendar.DAY_OF_WEEK;
+// import static java.util.Calendar.HOUR_OF_DAY;
+// import static java.util.Calendar.MINUTE;
+// import java.util.HashMap;
+// import java.util.HashSet;
+// import java.util.List;
+// import java.util.Set;
+// import javax.ws.rs.NotFoundException;
+// import javax.ws.rs.core.Response;
+
+// import org.apache.commons.io.FileUtils;
+// import org.jboss.arquillian.container.test.api.Deployment;
+// import org.jboss.shrinkwrap.api.spec.WebArchive;
+// import org.junit.After;
+// import org.junit.Assert;
+// import static org.junit.Assert.assertFalse;
+// import static org.junit.Assert.assertNotNull;
+// import static org.junit.Assert.assertTrue;
+// import static org.junit.Assert.fail;
+// import org.junit.Before;
+// import org.junit.Ignore;
+// import org.junit.Test;
+// import org.keycloak.admin.client.resource.UserResource;
+// import org.keycloak.common.util.MultivaluedHashMap;
+// import org.keycloak.models.RealmModel;
+// import org.keycloak.models.UserModel;
+// import static org.keycloak.models.UserModel.RequiredAction.UPDATE_PROFILE;
+// import org.keycloak.models.cache.CachedUserModel;
+// import org.keycloak.representations.idm.ComponentRepresentation;
+// import org.keycloak.representations.idm.GroupRepresentation;
+// import org.keycloak.representations.idm.RealmRepresentation;
+// import org.keycloak.representations.idm.RoleRepresentation;
+// import org.keycloak.representations.idm.UserRepresentation;
+// import org.keycloak.storage.UserStorageProvider;
+// import static org.keycloak.storage.UserStorageProviderModel.CACHE_POLICY;
+// import org.keycloak.storage.CacheableStorageProviderModel.CachePolicy;
+// import static org.keycloak.storage.UserStorageProviderModel.EVICTION_DAY;
+// import static org.keycloak.storage.UserStorageProviderModel.EVICTION_HOUR;
+// import static org.keycloak.storage.UserStorageProviderModel.EVICTION_MINUTE;
+// import static org.keycloak.storage.UserStorageProviderModel.MAX_LIFESPAN;
+// import org.keycloak.testsuite.AbstractAuthTest;
+// import org.keycloak.testsuite.admin.ApiUtil;
+// import org.keycloak.testsuite.federation.UserMapStorage;
+// import org.keycloak.testsuite.federation.UserMapStorageFactory;
+// import org.keycloak.testsuite.federation.UserPropertyFileStorageFactory;
+// import org.keycloak.testsuite.pages.LoginPage;
+// import org.keycloak.testsuite.pages.RegisterPage;
+// import org.keycloak.testsuite.pages.VerifyEmailPage;
+// import org.keycloak.testsuite.runonserver.RunOnServerDeployment;
+// import org.keycloak.testsuite.updaters.RealmAttributeUpdater;
+// import org.keycloak.testsuite.util.GreenMailRule;
+// import java.util.Map;
+// import javax.mail.internet.MimeMessage;
+// import org.jboss.arquillian.graphene.page.Page;
+// import org.junit.Rule;
+// import static org.keycloak.testsuite.actions.RequiredActionEmailVerificationTest.getPasswordResetEmailLink;
+// import static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlDoesntStartWith;
+// import static org.keycloak.testsuite.util.URLAssert.assertCurrentUrlStartsWith;
+
+// /**
+// *
+// * @author tkyjovsk
+// */
+// public class UserStorageTest extends AbstractAuthTest {
+
+// private String memProviderId;
+// private String propProviderROId;
+// private String propProviderRWId;
+
+// @Rule
+// public GreenMailRule greenMail = new GreenMailRule();
+
+// @Page
+// protected LoginPage loginPage;
+
+// @Page
+// protected RegisterPage registerPage;
+
+// @Page
+// protected VerifyEmailPage verifyEmailPage;
+
+// private static final File CONFIG_DIR = new File(System.getProperty("auth.server.config.dir", ""));
+
+// @Before
+// public void addProvidersBeforeTest() throws URISyntaxException, IOException {
+// ComponentRepresentation memProvider = new ComponentRepresentation();
+// memProvider.setName("memory");
+// memProvider.setProviderId(UserMapStorageFactory.PROVIDER_ID);
+// memProvider.setProviderType(UserStorageProvider.class.getName());
+// memProvider.setConfig(new MultivaluedHashMap<>());
+// memProvider.getConfig().putSingle("priority", Integer.toString(0));
+
+// memProviderId = addComponent(memProvider);
+
+// // copy files used by the following RO/RW user providers
+// File stResDir = new File(getClass().getResource("/storage-test").toURI());
+// if (stResDir.exists() && stResDir.isDirectory() && CONFIG_DIR.exists() && CONFIG_DIR.isDirectory()) {
+// for (File f : stResDir.listFiles()) {
+// log.infof("Copying %s to %s", f.getName(), CONFIG_DIR.getAbsolutePath());
+// FileUtils.copyFileToDirectory(f, CONFIG_DIR);
+// }
+// } else {
+// throw new RuntimeException("Property `auth.server.config.dir` must be set to run UserStorageTests.");
+// }
+
+// ComponentRepresentation propProviderRO = new ComponentRepresentation();
+// propProviderRO.setName("read-only-user-props");
+// propProviderRO.setProviderId(UserPropertyFileStorageFactory.PROVIDER_ID);
+// propProviderRO.setProviderType(UserStorageProvider.class.getName());
+// propProviderRO.setConfig(new MultivaluedHashMap<>());
+// propProviderRO.getConfig().putSingle("priority", Integer.toString(1));
+// propProviderRO.getConfig().putSingle("propertyFile",
+// CONFIG_DIR.getAbsolutePath() + File.separator + "read-only-user-password.properties");
+
+// propProviderROId = addComponent(propProviderRO);
+
+// propProviderRWId = addComponent(newPropProviderRW());
+
+// }
+
+// @After
+// public void removeTestUser() throws URISyntaxException, IOException {
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// if (realm == null) {
+// return;
+// }
+
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// if (user != null) {
+// session.userLocalStorage().removeUser(realm, user);
+// session.userCache().clear();
+// }
+// });
+// }
+
+// protected ComponentRepresentation newPropProviderRW() {
+// ComponentRepresentation propProviderRW = new ComponentRepresentation();
+// propProviderRW.setName("user-props");
+// propProviderRW.setProviderId(UserPropertyFileStorageFactory.PROVIDER_ID);
+// propProviderRW.setProviderType(UserStorageProvider.class.getName());
+// propProviderRW.setConfig(new MultivaluedHashMap<>());
+// propProviderRW.getConfig().putSingle("priority", Integer.toString(2));
+// propProviderRW.getConfig().putSingle("propertyFile", CONFIG_DIR.getAbsolutePath() + File.separator + "user-password.properties");
+// propProviderRW.getConfig().putSingle("federatedStorage", "true");
+// return propProviderRW;
+// }
+
+// protected String addComponent(ComponentRepresentation component) {
+// Response resp = testRealmResource().components().add(component);
+// resp.close();
+// String id = ApiUtil.getCreatedId(resp);
+// getCleanup().addComponentId(id);
+// return id;
+// }
+
+// private void loginSuccessAndLogout(String username, String password) {
+// testRealmAccountPage.navigateTo();
+// testRealmLoginPage.form().login(username, password);
+// assertCurrentUrlStartsWith(testRealmAccountPage);
+// testRealmAccountPage.logOut();
+// }
+
+// public void loginBadPassword(String username) {
+// testRealmAccountPage.navigateTo();
+// testRealmLoginPage.form().login(username, "badpassword");
+// assertCurrentUrlDoesntStartWith(testRealmAccountPage);
+// }
+
+// // @Test
+// public void listComponents() {
+// log.info("COMPONENTS:");
+// testRealmResource().components().query().forEach((c) -> {
+// log.infof("%s - %s - %s", c.getId(), c.getProviderType(), c.getName());
+// });
+// }
+
+// @Test
+// public void testLoginSuccess() {
+// loginSuccessAndLogout("tbrady", "goat");
+// loginSuccessAndLogout("thor", "hammer");
+// loginBadPassword("tbrady");
+// }
+
+// @Test
+// public void testUpdate() {
+// UserRepresentation thor = ApiUtil.findUserByUsername(testRealmResource(), "thor");
+
+// // update entity
+// thor.setFirstName("Stian");
+// thor.setLastName("Thorgersen");
+// thor.setEmailVerified(true);
+// long thorCreated = System.currentTimeMillis() - 100;
+// thor.setCreatedTimestamp(thorCreated);
+// thor.setEmail("thor@hammer.com");
+// thor.setAttributes(new HashMap<>());
+// thor.getAttributes().put("test-attribute", Arrays.asList("value"));
+// thor.setRequiredActions(new ArrayList<>());
+// thor.getRequiredActions().add(UPDATE_PROFILE.name());
+// testRealmResource().users().get(thor.getId()).update(thor);
+
+// // check entity
+// thor = ApiUtil.findUserByUsername(testRealmResource(), "thor");
+// Assert.assertEquals("Stian", thor.getFirstName());
+// Assert.assertEquals("Thorgersen", thor.getLastName());
+// Assert.assertEquals("thor@hammer.com", thor.getEmail());
+// Assert.assertTrue(thor.getAttributes().containsKey("test-attribute"));
+// Assert.assertEquals(1, thor.getAttributes().get("test-attribute").size());
+// Assert.assertEquals("value", thor.getAttributes().get("test-attribute").get(0));
+// Assert.assertTrue(thor.isEmailVerified());
+
+// // update group
+// GroupRepresentation g = new GroupRepresentation();
+// g.setName("my-group");
+// String gid = ApiUtil.getCreatedId(testRealmResource().groups().add(g));
+
+// testRealmResource().users().get(thor.getId()).joinGroup(gid);
+
+// // check group
+// boolean foundGroup = false;
+// for (GroupRepresentation ug : testRealmResource().users().get(thor.getId()).groups()) {
+// if (ug.getId().equals(gid)) {
+// foundGroup = true;
+// }
+// }
+// Assert.assertTrue(foundGroup);
+
+// // check required actions
+// assertTrue(thor.getRequiredActions().contains(UPDATE_PROFILE.name()));
+// // remove req. actions
+// thor.getRequiredActions().remove(UPDATE_PROFILE.name());
+// testRealmResource().users().get(thor.getId()).update(thor);
+
+// // change pass
+// ApiUtil.resetUserPassword(testRealmResource().users().get(thor.getId()), "lightning", false);
+// loginSuccessAndLogout("thor", "lightning");
+
+// // update role
+// RoleRepresentation r = new RoleRepresentation("foo-role", "foo role", false);
+// testRealmResource().roles().create(r);
+// ApiUtil.assignRealmRoles(testRealmResource(), thor.getId(), "foo-role");
+
+// // check role
+// boolean foundRole = false;
+// for (RoleRepresentation rr : user(thor.getId()).roles().getAll().getRealmMappings()) {
+// if ("foo-role".equals(rr.getName())) {
+// foundRole = true;
+// break;
+// }
+// }
+// assertTrue(foundRole);
+
+// // test removal of provider
+// testRealmResource().components().component(propProviderRWId).remove();
+// propProviderRWId = addComponent(newPropProviderRW());
+// loginSuccessAndLogout("thor", "hammer");
+
+// thor = ApiUtil.findUserByUsername(testRealmResource(), "thor");
+
+// Assert.assertNull(thor.getFirstName());
+// Assert.assertNull(thor.getLastName());
+// Assert.assertNull(thor.getEmail());
+// Assert.assertNull(thor.getAttributes());
+// Assert.assertFalse(thor.isEmailVerified());
+
+// foundGroup = false;
+// for (GroupRepresentation ug : testRealmResource().users().get(thor.getId()).groups()) {
+// if (ug.getId().equals(gid)) {
+// foundGroup = true;
+// }
+// }
+// Assert.assertFalse(foundGroup);
+
+// foundRole = false;
+// for (RoleRepresentation rr : user(thor.getId()).roles().getAll().getRealmMappings()) {
+// if ("foo-role".equals(rr.getName())) {
+// foundRole = true;
+// break;
+// }
+// }
+// assertFalse(foundRole);
+// }
+
+// @Test
+// public void testRegisterWithRequiredEmail() throws Exception {
+// try (AutoCloseable c = new RealmAttributeUpdater(testRealmResource())
+// .updateWith(r -> {
+// Map<String, String> config = new HashMap<>();
+// config.put("from", "auto@keycloak.org");
+// config.put("host", "0.0.0.0");
+// config.put("port", "3025");
+// r.setSmtpServer(config);
+// r.setRegistrationAllowed(true);
+// r.setVerifyEmail(true);
+// })
+// .update()) {
+
+// testRealmAccountPage.navigateTo();
+// loginPage.clickRegister();
+// registerPage.register("firstName", "lastName", "email@mail.com", "verifyEmail", "password", "password");
+
+// verifyEmailPage.assertCurrent();
+
+// Assert.assertEquals(1, greenMail.getReceivedMessages().length);
+
+// MimeMessage message = greenMail.getReceivedMessages()[0];
+
+// String verificationUrl = getPasswordResetEmailLink(message);
+
+// driver.navigate().to(verificationUrl.trim());
+
+// testRealmAccountPage.assertCurrent();
+// }
+// }
+
+// public UserResource user(String userId) {
+// return testRealmResource().users().get(userId);
+// }
+
+// @Test
+// public void testRegistration() {
+// UserRepresentation memuser = new UserRepresentation();
+// memuser.setUsername("memuser");
+// String uid = ApiUtil.createUserAndResetPasswordWithAdminClient(testRealmResource(), memuser, "password");
+// loginSuccessAndLogout("memuser", "password");
+// loginSuccessAndLogout("memuser", "password");
+// loginSuccessAndLogout("memuser", "password");
+
+// memuser = user(uid).toRepresentation();
+// assertNotNull(memuser);
+// assertNotNull(memuser.getOrigin());
+// ComponentRepresentation origin = testRealmResource().components().component(memuser.getOrigin()).toRepresentation();
+// Assert.assertEquals("memory", origin.getName());
+
+// testRealmResource().users().get(memuser.getId()).remove();
+// try {
+// user(uid).toRepresentation(); // provider doesn't implement UserQueryProvider --> have to lookup by uid
+// fail("`memuser` wasn't removed");
+// } catch (NotFoundException nfe) {
+// // expected
+// }
+// }
+
+// @Test
+// public void testQuery() {
+// Set<UserRepresentation> queried = new HashSet<>();
+// int first = 0;
+// while (queried.size() < 8) {
+// List<UserRepresentation> results = testRealmResource().users().search("", first, 3);
+// log.debugf("first=%s, results: %s", first, results.size());
+// if (results.isEmpty()) {
+// break;
+// }
+// first += results.size();
+// queried.addAll(results);
+// }
+// Set<String> usernames = new HashSet<>();
+// for (UserRepresentation user : queried) {
+// usernames.add(user.getUsername());
+// log.info(user.getUsername());
+// }
+// Assert.assertEquals(8, queried.size());
+// Assert.assertTrue(usernames.contains("thor"));
+// Assert.assertTrue(usernames.contains("zeus"));
+// Assert.assertTrue(usernames.contains("apollo"));
+// Assert.assertTrue(usernames.contains("perseus"));
+// Assert.assertTrue(usernames.contains("tbrady"));
+// Assert.assertTrue(usernames.contains("rob"));
+// Assert.assertTrue(usernames.contains("jules"));
+// Assert.assertTrue(usernames.contains("danny"));
+
+// // test searchForUser
+// List<UserRepresentation> users = testRealmResource().users().search("tbrady", 0, Integer.MAX_VALUE);
+// Assert.assertTrue(users.size() == 1);
+// Assert.assertTrue(users.get(0).getUsername().equals("tbrady"));
+
+// // test getGroupMembers()
+// GroupRepresentation g = new GroupRepresentation();
+// g.setName("gods");
+// String gid = ApiUtil.getCreatedId(testRealmResource().groups().add(g));
+
+// UserRepresentation user = ApiUtil.findUserByUsername(testRealmResource(), "apollo");
+// testRealmResource().users().get(user.getId()).joinGroup(gid);
+// user = ApiUtil.findUserByUsername(testRealmResource(), "zeus");
+// testRealmResource().users().get(user.getId()).joinGroup(gid);
+// user = ApiUtil.findUserByUsername(testRealmResource(), "thor");
+// testRealmResource().users().get(user.getId()).joinGroup(gid);
+// queried.clear();
+// usernames.clear();
+
+// first = 0;
+// while (queried.size() < 8) {
+// List<UserRepresentation> results = testRealmResource().groups().group(gid).members(first, 1);
+// log.debugf("first=%s, results: %s", first, results.size());
+// if (results.isEmpty()) {
+// break;
+// }
+// first += results.size();
+// queried.addAll(results);
+// }
+// for (UserRepresentation u : queried) {
+// usernames.add(u.getUsername());
+// log.info(u.getUsername());
+// }
+// Assert.assertEquals(3, queried.size());
+// Assert.assertTrue(usernames.contains("apollo"));
+// Assert.assertTrue(usernames.contains("zeus"));
+// Assert.assertTrue(usernames.contains("thor"));
+
+// // search by single attribute
+// // FIXME - no equivalent for model in REST
+// }
+
+// @Deployment
+// public static WebArchive deploy() {
+// return RunOnServerDeployment.create(UserResource.class)
+// .addPackages(true, "org.keycloak.testsuite");
+// }
+
+// private void setDailyEvictionTime(int hour, int minutes) {
+// if (hour < 0 || hour > 23) {
+// throw new IllegalArgumentException("hour == " + hour);
+// }
+// if (minutes < 0 || minutes > 59) {
+// throw new IllegalArgumentException("minutes == " + minutes);
+// }
+// ComponentRepresentation propProviderRW = testRealmResource().components().component(propProviderRWId).toRepresentation();
+// propProviderRW.getConfig().putSingle(CACHE_POLICY, CachePolicy.EVICT_DAILY.name());
+// propProviderRW.getConfig().putSingle(EVICTION_HOUR, String.valueOf(hour));
+// propProviderRW.getConfig().putSingle(EVICTION_MINUTE, String.valueOf(minutes));
+// testRealmResource().components().component(propProviderRWId).update(propProviderRW);
+// }
+
+
+// /**
+// * Test daily eviction behaviour
+// */
+// @Test
+// public void testDailyEviction() {
+
+// // We need to test both cases: eviction the same day, and eviction the next day
+// // Simplest is to take full control of the clock
+
+// // set clock to 23:30 of current day
+// setTimeOfDay(23, 30, 0);
+
+// // test same day eviction behaviour
+// // set eviction at 23:45
+// setDailyEvictionTime(23, 45);
+
+// // there are users in cache already from before-test import
+// // and they didn't use any time offset clock so they may have timestamps in the 'future'
+
+// // let's clear cache
+// testingClient.server().run(session -> {
+// session.userCache().clear();
+// });
+
+
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// Assert.assertTrue(user instanceof CachedUserModel); // should be newly cached
+// });
+
+
+// setTimeOfDay(23, 40, 0);
+
+// // lookup user again - make sure it's returned from cache
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// Assert.assertTrue(user instanceof CachedUserModel); // should be returned from cache
+// });
+
+
+// setTimeOfDay(23, 50, 0);
+
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// Assert.assertFalse(user instanceof CachedUserModel); // should have been invalidated
+// });
+
+
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// Assert.assertTrue(user instanceof CachedUserModel); // should have been newly cached
+// });
+
+
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// Assert.assertTrue(user instanceof CachedUserModel); // should be returned from cache
+// });
+
+
+// setTimeOfDay(23, 55, 0);
+
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// Assert.assertTrue(user instanceof CachedUserModel); // should be returned from cache
+// });
+
+
+// // at 00:30
+// // it's next day now. the daily eviction time is now in the future
+// setTimeOfDay(0, 30, 0, 24 * 60 * 60);
+
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// Assert.assertTrue(user instanceof CachedUserModel); // should be returned from cache - it's still good for almost the whole day
+// });
+
+
+// // at 23:30 next day
+// setTimeOfDay(23, 30, 0, 24 * 60 * 60);
+
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// Assert.assertTrue(user instanceof CachedUserModel); // should be returned from cache - it's still good until 23:45
+// });
- // at 23:50
- setTimeOfDay(23, 50, 0, 24 * 60 * 60);
+// // at 23:50
+// setTimeOfDay(23, 50, 0, 24 * 60 * 60);
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("thor", realm);
- Assert.assertFalse(user instanceof CachedUserModel); // should be invalidated
- });
-
- setTimeOfDay(23, 55, 0, 24 * 60 * 60);
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// Assert.assertFalse(user instanceof CachedUserModel); // should be invalidated
+// });
+
+// setTimeOfDay(23, 55, 0, 24 * 60 * 60);
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("thor", realm);
- Assert.assertTrue(user instanceof CachedUserModel); // should be newly cached
- });
-
-
- setTimeOfDay(23, 40, 0, 2 * 24 * 60 * 60);
-
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("thor", realm);
- Assert.assertTrue(user instanceof CachedUserModel); // should be returned from cache
- });
-
- setTimeOfDay(23, 50, 0, 2 * 24 * 60 * 60);
-
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("thor", realm);
- Assert.assertFalse(user instanceof CachedUserModel); // should be invalidated
- });
-
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("thor", realm);
- Assert.assertTrue(user instanceof CachedUserModel); // should be newly cached
- });
-
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("thor", realm);
- Assert.assertTrue(user instanceof CachedUserModel); // should be returned from cache
- });
- }
-
- @Test
- public void testWeeklyEviction() {
- ApiUtil.findUserByUsername(testRealmResource(), "thor");
-
- // set eviction to 4 days from now
- Calendar eviction = Calendar.getInstance();
- eviction.add(Calendar.HOUR, 4 * 24);
- ComponentRepresentation propProviderRW = testRealmResource().components().component(propProviderRWId).toRepresentation();
- propProviderRW.getConfig().putSingle(CACHE_POLICY, CachePolicy.EVICT_WEEKLY.name());
- propProviderRW.getConfig().putSingle(EVICTION_DAY, Integer.toString(eviction.get(DAY_OF_WEEK)));
- propProviderRW.getConfig().putSingle(EVICTION_HOUR, Integer.toString(eviction.get(HOUR_OF_DAY)));
- propProviderRW.getConfig().putSingle(EVICTION_MINUTE, Integer.toString(eviction.get(MINUTE)));
- testRealmResource().components().component(propProviderRWId).update(propProviderRW);
-
- // now
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("thor", realm);
- System.out.println("User class: " + user.getClass());
- Assert.assertTrue(user instanceof CachedUserModel); // should still be cached
- });
-
- setTimeOffset(2 * 24 * 60 * 60); // 2 days in future
-
- // now
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("thor", realm);
- System.out.println("User class: " + user.getClass());
- Assert.assertTrue(user instanceof CachedUserModel); // should still be cached
- });
-
- setTimeOffset(5 * 24 * 60 * 60); // 5 days in future
-
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("thor", realm);
- System.out.println("User class: " + user.getClass());
- Assert.assertFalse(user instanceof CachedUserModel); // should be evicted
- });
-
- }
-
- @Test
- public void testMaxLifespan() {
- ApiUtil.findUserByUsername(testRealmResource(), "thor");
-
- // set eviction to 1 hour from now
- ComponentRepresentation propProviderRW = testRealmResource().components().component(propProviderRWId).toRepresentation();
- propProviderRW.getConfig().putSingle(CACHE_POLICY, CachePolicy.MAX_LIFESPAN.name());
- propProviderRW.getConfig().putSingle(MAX_LIFESPAN, Long.toString(1 * 60 * 60 * 1000)); // 1 hour in milliseconds
- testRealmResource().components().component(propProviderRWId).update(propProviderRW);
-
- // now
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("thor", realm);
- System.out.println("User class: " + user.getClass());
- Assert.assertTrue(user instanceof CachedUserModel); // should still be cached
- });
-
- setTimeOffset(1/2 * 60 * 60); // 1/2 hour in future
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// Assert.assertTrue(user instanceof CachedUserModel); // should be newly cached
+// });
+
+
+// setTimeOfDay(23, 40, 0, 2 * 24 * 60 * 60);
+
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// Assert.assertTrue(user instanceof CachedUserModel); // should be returned from cache
+// });
+
+// setTimeOfDay(23, 50, 0, 2 * 24 * 60 * 60);
+
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// Assert.assertFalse(user instanceof CachedUserModel); // should be invalidated
+// });
+
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// Assert.assertTrue(user instanceof CachedUserModel); // should be newly cached
+// });
+
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// Assert.assertTrue(user instanceof CachedUserModel); // should be returned from cache
+// });
+// }
+
+// @Test
+// public void testWeeklyEviction() {
+// ApiUtil.findUserByUsername(testRealmResource(), "thor");
+
+// // set eviction to 4 days from now
+// Calendar eviction = Calendar.getInstance();
+// eviction.add(Calendar.HOUR, 4 * 24);
+// ComponentRepresentation propProviderRW = testRealmResource().components().component(propProviderRWId).toRepresentation();
+// propProviderRW.getConfig().putSingle(CACHE_POLICY, CachePolicy.EVICT_WEEKLY.name());
+// propProviderRW.getConfig().putSingle(EVICTION_DAY, Integer.toString(eviction.get(DAY_OF_WEEK)));
+// propProviderRW.getConfig().putSingle(EVICTION_HOUR, Integer.toString(eviction.get(HOUR_OF_DAY)));
+// propProviderRW.getConfig().putSingle(EVICTION_MINUTE, Integer.toString(eviction.get(MINUTE)));
+// testRealmResource().components().component(propProviderRWId).update(propProviderRW);
+
+// // now
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// System.out.println("User class: " + user.getClass());
+// Assert.assertTrue(user instanceof CachedUserModel); // should still be cached
+// });
+
+// setTimeOffset(2 * 24 * 60 * 60); // 2 days in future
+
+// // now
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// System.out.println("User class: " + user.getClass());
+// Assert.assertTrue(user instanceof CachedUserModel); // should still be cached
+// });
+
+// setTimeOffset(5 * 24 * 60 * 60); // 5 days in future
+
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// System.out.println("User class: " + user.getClass());
+// Assert.assertFalse(user instanceof CachedUserModel); // should be evicted
+// });
+
+// }
+
+// @Test
+// public void testMaxLifespan() {
+// ApiUtil.findUserByUsername(testRealmResource(), "thor");
+
+// // set eviction to 1 hour from now
+// ComponentRepresentation propProviderRW = testRealmResource().components().component(propProviderRWId).toRepresentation();
+// propProviderRW.getConfig().putSingle(CACHE_POLICY, CachePolicy.MAX_LIFESPAN.name());
+// propProviderRW.getConfig().putSingle(MAX_LIFESPAN, Long.toString(1 * 60 * 60 * 1000)); // 1 hour in milliseconds
+// testRealmResource().components().component(propProviderRWId).update(propProviderRW);
+
+// // now
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// System.out.println("User class: " + user.getClass());
+// Assert.assertTrue(user instanceof CachedUserModel); // should still be cached
+// });
+
+// setTimeOffset(1/2 * 60 * 60); // 1/2 hour in future
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("thor", realm);
- System.out.println("User class: " + user.getClass());
- Assert.assertTrue(user instanceof CachedUserModel); // should still be cached
- });
-
- setTimeOffset(2 * 60 * 60); // 2 hours in future
-
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("thor", realm);
- System.out.println("User class: " + user.getClass());
- Assert.assertFalse(user instanceof CachedUserModel); // should be evicted
- });
-
- }
-
- @Test
- public void testNoCache() {
- ApiUtil.findUserByUsername(testRealmResource(), "thor");
-
- // set NO_CACHE policy
- ComponentRepresentation propProviderRW = testRealmResource().components().component(propProviderRWId).toRepresentation();
- propProviderRW.getConfig().putSingle(CACHE_POLICY, CachePolicy.NO_CACHE.name());
- testRealmResource().components().component(propProviderRWId).update(propProviderRW);
-
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("thor", realm);
- System.out.println("User class: " + user.getClass());
- Assert.assertFalse(user instanceof CachedUserModel); // should be evicted
- });
- }
-
- @Test
- public void testLifecycle() {
-
- testingClient.server().run(session -> {
- UserMapStorage.allocations.set(0);
- UserMapStorage.closings.set(0);
-
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().addUser(realm, "memuser");
- Assert.assertNotNull(user);
- user = session.users().getUserByUsername("nonexistent", realm);
- Assert.assertNull(user);
-
- Assert.assertEquals(1, UserMapStorage.allocations.get());
- Assert.assertEquals(0, UserMapStorage.closings.get());
- });
-
- testingClient.server().run(session -> {
- Assert.assertEquals(1, UserMapStorage.allocations.get());
- Assert.assertEquals(1, UserMapStorage.closings.get());
- });
-
- }
-
- @Test
- public void testEntityRemovalHooks() {
- testingClient.server().run(session -> {
- UserMapStorage.realmRemovals.set(0);
- UserMapStorage.groupRemovals.set(0);
- UserMapStorage.roleRemovals.set(0);
- });
-
- // remove group
- GroupRepresentation g1 = new GroupRepresentation();
- g1.setName("group1");
- GroupRepresentation g2 = new GroupRepresentation();
- g2.setName("group2");
- String gid1 = ApiUtil.getCreatedId(testRealmResource().groups().add(g1));
- String gid2 = ApiUtil.getCreatedId(testRealmResource().groups().add(g2));
- testRealmResource().groups().group(gid1).remove();
- testRealmResource().groups().group(gid2).remove();
- testingClient.server().run(session -> {
- Assert.assertEquals(2, UserMapStorage.groupRemovals.get());
- UserMapStorage.realmRemovals.set(0);
- });
-
- // remove role
- RoleRepresentation role1 = new RoleRepresentation();
- role1.setName("role1");
- RoleRepresentation role2 = new RoleRepresentation();
- role2.setName("role2");
- testRealmResource().roles().create(role1);
- testRealmResource().roles().create(role2);
- testRealmResource().roles().get("role1").remove();
- testRealmResource().roles().get("role2").remove();
- testingClient.server().run(session -> {
- Assert.assertEquals(2, UserMapStorage.roleRemovals.get());
- UserMapStorage.realmRemovals.set(0);
- });
-
- // remove realm
- RealmRepresentation testRealmRepresentation = testRealmResource().toRepresentation();
- testRealmResource().remove();
- testingClient.server().run(session -> {
- Assert.assertEquals(1, UserMapStorage.realmRemovals.get());
- UserMapStorage.realmRemovals.set(0);
- });
-
- // Re-create realm
- RealmRepresentation repOrig = testContext.getTestRealmReps().get(0);
- adminClient.realms().create(repOrig);
- }
-
- @Test
- @Ignore
- public void testEntityRemovalHooksCascade() {
- testingClient.server().run(session -> {
- UserMapStorage.realmRemovals.set(0);
- UserMapStorage.groupRemovals.set(0);
- UserMapStorage.roleRemovals.set(0);
- });
-
- GroupRepresentation g1 = new GroupRepresentation();
- g1.setName("group1");
- GroupRepresentation g2 = new GroupRepresentation();
- g2.setName("group2");
- String gid1 = ApiUtil.getCreatedId(testRealmResource().groups().add(g1));
- String gid2 = ApiUtil.getCreatedId(testRealmResource().groups().add(g2));
-
- RoleRepresentation role1 = new RoleRepresentation();
- role1.setName("role1");
- RoleRepresentation role2 = new RoleRepresentation();
- role2.setName("role2");
- testRealmResource().roles().create(role1);
- testRealmResource().roles().create(role2);
-
- // remove realm with groups and roles in it
- testRealmResource().remove();
- testingClient.server().run(session -> {
- Assert.assertEquals(1, UserMapStorage.realmRemovals.get());
- Assert.assertEquals(2, UserMapStorage.groupRemovals.get()); // check if group removal hooks were called
- Assert.assertEquals(2, UserMapStorage.roleRemovals.get()); // check if role removal hooks were called
- });
-
- }
-
-}
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// System.out.println("User class: " + user.getClass());
+// Assert.assertTrue(user instanceof CachedUserModel); // should still be cached
+// });
+
+// setTimeOffset(2 * 60 * 60); // 2 hours in future
+
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// System.out.println("User class: " + user.getClass());
+// Assert.assertFalse(user instanceof CachedUserModel); // should be evicted
+// });
+
+// }
+
+// @Test
+// public void testNoCache() {
+// ApiUtil.findUserByUsername(testRealmResource(), "thor");
+
+// // set NO_CACHE policy
+// ComponentRepresentation propProviderRW = testRealmResource().components().component(propProviderRWId).toRepresentation();
+// propProviderRW.getConfig().putSingle(CACHE_POLICY, CachePolicy.NO_CACHE.name());
+// testRealmResource().components().component(propProviderRWId).update(propProviderRW);
+
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("thor", realm);
+// System.out.println("User class: " + user.getClass());
+// Assert.assertFalse(user instanceof CachedUserModel); // should be evicted
+// });
+// }
+
+// @Test
+// public void testLifecycle() {
+
+// testingClient.server().run(session -> {
+// UserMapStorage.allocations.set(0);
+// UserMapStorage.closings.set(0);
+
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().addUser(realm, "memuser");
+// Assert.assertNotNull(user);
+// user = session.users().getUserByUsername("nonexistent", realm);
+// Assert.assertNull(user);
+
+// Assert.assertEquals(1, UserMapStorage.allocations.get());
+// Assert.assertEquals(0, UserMapStorage.closings.get());
+// });
+
+// testingClient.server().run(session -> {
+// Assert.assertEquals(1, UserMapStorage.allocations.get());
+// Assert.assertEquals(1, UserMapStorage.closings.get());
+// });
+
+// }
+
+// @Test
+// public void testEntityRemovalHooks() {
+// testingClient.server().run(session -> {
+// UserMapStorage.realmRemovals.set(0);
+// UserMapStorage.groupRemovals.set(0);
+// UserMapStorage.roleRemovals.set(0);
+// });
+
+// // remove group
+// GroupRepresentation g1 = new GroupRepresentation();
+// g1.setName("group1");
+// GroupRepresentation g2 = new GroupRepresentation();
+// g2.setName("group2");
+// String gid1 = ApiUtil.getCreatedId(testRealmResource().groups().add(g1));
+// String gid2 = ApiUtil.getCreatedId(testRealmResource().groups().add(g2));
+// testRealmResource().groups().group(gid1).remove();
+// testRealmResource().groups().group(gid2).remove();
+// testingClient.server().run(session -> {
+// Assert.assertEquals(2, UserMapStorage.groupRemovals.get());
+// UserMapStorage.realmRemovals.set(0);
+// });
+
+// // remove role
+// RoleRepresentation role1 = new RoleRepresentation();
+// role1.setName("role1");
+// RoleRepresentation role2 = new RoleRepresentation();
+// role2.setName("role2");
+// testRealmResource().roles().create(role1);
+// testRealmResource().roles().create(role2);
+// testRealmResource().roles().get("role1").remove();
+// testRealmResource().roles().get("role2").remove();
+// testingClient.server().run(session -> {
+// Assert.assertEquals(2, UserMapStorage.roleRemovals.get());
+// UserMapStorage.realmRemovals.set(0);
+// });
+
+// // remove realm
+// RealmRepresentation testRealmRepresentation = testRealmResource().toRepresentation();
+// testRealmResource().remove();
+// testingClient.server().run(session -> {
+// Assert.assertEquals(1, UserMapStorage.realmRemovals.get());
+// UserMapStorage.realmRemovals.set(0);
+// });
+
+// // Re-create realm
+// RealmRepresentation repOrig = testContext.getTestRealmReps().get(0);
+// adminClient.realms().create(repOrig);
+// }
+
+// @Test
+// @Ignore
+// public void testEntityRemovalHooksCascade() {
+// testingClient.server().run(session -> {
+// UserMapStorage.realmRemovals.set(0);
+// UserMapStorage.groupRemovals.set(0);
+// UserMapStorage.roleRemovals.set(0);
+// });
+
+// GroupRepresentation g1 = new GroupRepresentation();
+// g1.setName("group1");
+// GroupRepresentation g2 = new GroupRepresentation();
+// g2.setName("group2");
+// String gid1 = ApiUtil.getCreatedId(testRealmResource().groups().add(g1));
+// String gid2 = ApiUtil.getCreatedId(testRealmResource().groups().add(g2));
+
+// RoleRepresentation role1 = new RoleRepresentation();
+// role1.setName("role1");
+// RoleRepresentation role2 = new RoleRepresentation();
+// role2.setName("role2");
+// testRealmResource().roles().create(role1);
+// testRealmResource().roles().create(role2);
+
+// // remove realm with groups and roles in it
+// testRealmResource().remove();
+// testingClient.server().run(session -> {
+// Assert.assertEquals(1, UserMapStorage.realmRemovals.get());
+// Assert.assertEquals(2, UserMapStorage.groupRemovals.get()); // check if group removal hooks were called
+// Assert.assertEquals(2, UserMapStorage.roleRemovals.get()); // check if role removal hooks were called
+// });
+
+// }
+
+// }
diff --git a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CacheTest.java b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CacheTest.java
index 5270039..bf0a6b4 100755
--- a/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CacheTest.java
+++ b/testsuite/integration-arquillian/tests/base/src/test/java/org/keycloak/testsuite/model/CacheTest.java
@@ -1,193 +1,193 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.keycloak.testsuite.model;
-
-
-import org.jboss.arquillian.container.test.api.Deployment;
-import org.jboss.arquillian.container.test.api.TargetsContainer;
-import org.jboss.shrinkwrap.api.spec.WebArchive;
-import org.junit.ClassRule;
-import org.junit.Test;
-import org.keycloak.admin.client.resource.UserResource;
-import org.keycloak.models.ClientModel;
-import org.keycloak.models.KeycloakSession;
-import org.keycloak.models.RealmModel;
-import org.keycloak.models.RoleModel;
-import org.keycloak.models.UserModel;
-import org.keycloak.models.UserSessionModel;
-import org.keycloak.models.cache.infinispan.ClientAdapter;
-import org.keycloak.models.cache.infinispan.RealmAdapter;
-import org.keycloak.testsuite.federation.ldap.AbstractLDAPTest;
-import org.keycloak.testsuite.pages.AppPage;
-import org.keycloak.testsuite.runonserver.RunOnServerDeployment;
-
-import java.util.List;
-import java.util.List;
-import java.util.Set;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.keycloak.testsuite.arquillian.DeploymentTargetModifier.AUTH_SERVER_CURRENT;
-
-
-import org.keycloak.testsuite.AbstractTestRealmKeycloakTest;
-import org.keycloak.testsuite.Assert;
-import org.keycloak.models.utils.ModelToRepresentation;
-import org.keycloak.representations.idm.RealmRepresentation;
-import org.keycloak.testsuite.client.KeycloakTestingClient;
-import org.keycloak.testsuite.arquillian.TestContext;
-
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-
-public class CacheTest extends AbstractTestRealmKeycloakTest {
-
- @Deployment
- @TargetsContainer(AUTH_SERVER_CURRENT)
- public static WebArchive deploy() {
- return RunOnServerDeployment.create(UserResource.class, CacheTest.class)
- .addPackages(true,
- "org.keycloak.testsuite",
- "org.keycloak.testsuite.model");
- }
-
-
- private ClientModel testApp = null;
- private int grantedRolesCount=0;
- private RealmModel realm = null;
- private UserModel user = null;
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+
+// package org.keycloak.testsuite.model;
+
+
+// import org.jboss.arquillian.container.test.api.Deployment;
+// import org.jboss.arquillian.container.test.api.TargetsContainer;
+// import org.jboss.shrinkwrap.api.spec.WebArchive;
+// import org.junit.ClassRule;
+// import org.junit.Test;
+// import org.keycloak.admin.client.resource.UserResource;
+// import org.keycloak.models.ClientModel;
+// import org.keycloak.models.KeycloakSession;
+// import org.keycloak.models.RealmModel;
+// import org.keycloak.models.RoleModel;
+// import org.keycloak.models.UserModel;
+// import org.keycloak.models.UserSessionModel;
+// import org.keycloak.models.cache.infinispan.ClientAdapter;
+// import org.keycloak.models.cache.infinispan.RealmAdapter;
+// import org.keycloak.testsuite.federation.ldap.AbstractLDAPTest;
+// import org.keycloak.testsuite.pages.AppPage;
+// import org.keycloak.testsuite.runonserver.RunOnServerDeployment;
+
+// import java.util.List;
+// import java.util.List;
+// import java.util.Set;
+
+// import static org.junit.Assert.assertNotNull;
+// import static org.junit.Assert.assertTrue;
+// import static org.keycloak.testsuite.arquillian.DeploymentTargetModifier.AUTH_SERVER_CURRENT;
+
+
+// import org.keycloak.testsuite.AbstractTestRealmKeycloakTest;
+// import org.keycloak.testsuite.Assert;
+// import org.keycloak.models.utils.ModelToRepresentation;
+// import org.keycloak.representations.idm.RealmRepresentation;
+// import org.keycloak.testsuite.client.KeycloakTestingClient;
+// import org.keycloak.testsuite.arquillian.TestContext;
+
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+
+// public class CacheTest extends AbstractTestRealmKeycloakTest {
+
+// @Deployment
+// @TargetsContainer(AUTH_SERVER_CURRENT)
+// public static WebArchive deploy() {
+// return RunOnServerDeployment.create(UserResource.class, CacheTest.class)
+// .addPackages(true,
+// "org.keycloak.testsuite",
+// "org.keycloak.testsuite.model");
+// }
+
+
+// private ClientModel testApp = null;
+// private int grantedRolesCount=0;
+// private RealmModel realm = null;
+// private UserModel user = null;
- @Override
- public void configureTestRealm(RealmRepresentation testRealm) {
- }
-
- @Test
- public void testStaleCache() throws Exception {
- testingClient.server().run(session -> {
- String appId = null;
- {
- // load up cache
-
- RealmModel realm = session.realms().getRealmByName("test");
- assertTrue(realm instanceof RealmAdapter);
- ClientModel testApp = realm.getClientByClientId("test-app");
- assertTrue(testApp instanceof ClientAdapter);
- assertNotNull(testApp);
- appId = testApp.getId();
- assertTrue(testApp.isEnabled());
+// @Override
+// public void configureTestRealm(RealmRepresentation testRealm) {
+// }
+
+// @Test
+// public void testStaleCache() throws Exception {
+// testingClient.server().run(session -> {
+// String appId = null;
+// {
+// // load up cache
+
+// RealmModel realm = session.realms().getRealmByName("test");
+// assertTrue(realm instanceof RealmAdapter);
+// ClientModel testApp = realm.getClientByClientId("test-app");
+// assertTrue(testApp instanceof ClientAdapter);
+// assertNotNull(testApp);
+// appId = testApp.getId();
+// assertTrue(testApp.isEnabled());
- // update realm, then get an AppModel and change it. The AppModel would not be a cache adapter
+// // update realm, then get an AppModel and change it. The AppModel would not be a cache adapter
- // KEYCLOAK-1240 - obtain the realm via session.realms().getRealms()
- realm = null;
- List<RealmModel> realms = session.realms().getRealms();
+// // KEYCLOAK-1240 - obtain the realm via session.realms().getRealms()
+// realm = null;
+// List<RealmModel> realms = session.realms().getRealms();
- for (RealmModel current : realms) {
- assertTrue(current instanceof RealmAdapter);
- if ("test".equals(current.getName())) {
- realm = current;
- break;
- }
- }
+// for (RealmModel current : realms) {
+// assertTrue(current instanceof RealmAdapter);
+// if ("test".equals(current.getName())) {
+// realm = current;
+// break;
+// }
+// }
- realm.setAccessCodeLifespanLogin(200);
- testApp = realm.getClientByClientId("test-app");
+// realm.setAccessCodeLifespanLogin(200);
+// testApp = realm.getClientByClientId("test-app");
- assertNotNull(testApp);
- testApp.setEnabled(false);
+// assertNotNull(testApp);
+// testApp.setEnabled(false);
- // make sure that app cache was flushed and enabled changed
+// // make sure that app cache was flushed and enabled changed
- realm = session.realms().getRealmByName("test");
- Assert.assertEquals(200, realm.getAccessCodeLifespanLogin());
- testApp = session.realms().getClientById(appId, realm);
- Assert.assertFalse(testApp.isEnabled());
+// realm = session.realms().getRealmByName("test");
+// Assert.assertEquals(200, realm.getAccessCodeLifespanLogin());
+// testApp = session.realms().getClientById(appId, realm);
+// Assert.assertFalse(testApp.isEnabled());
- }
- });
- }
- @Test
- public void testAddUserNotAddedToCache() {
-
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
-
- UserModel user = session.users().addUser(realm, "testAddUserNotAddedToCache");
- user.setFirstName("firstName");
- user.addRequiredAction(UserModel.RequiredAction.CONFIGURE_TOTP);
+// }
+// });
+// }
+// @Test
+// public void testAddUserNotAddedToCache() {
+
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+
+// UserModel user = session.users().addUser(realm, "testAddUserNotAddedToCache");
+// user.setFirstName("firstName");
+// user.addRequiredAction(UserModel.RequiredAction.CONFIGURE_TOTP);
- UserSessionModel userSession = session.sessions().createUserSession("123", realm, user, "testAddUserNotAddedToCache", "127.0.0.1", "auth", false, null, null);
- user = userSession.getUser();
+// UserSessionModel userSession = session.sessions().createUserSession("123", realm, user, "testAddUserNotAddedToCache", "127.0.0.1", "auth", false, null, null);
+// user = userSession.getUser();
- user.setLastName("lastName");
+// user.setLastName("lastName");
- assertNotNull(user.getLastName());
- });
+// assertNotNull(user.getLastName());
+// });
- }
+// }
- // KEYCLOAK-1842
- @Test
- public void testRoleMappingsInvalidatedWhenClientRemoved() {
+// // KEYCLOAK-1842
+// @Test
+// public void testRoleMappingsInvalidatedWhenClientRemoved() {
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().addUser(realm, "joel");
- ClientModel client = realm.addClient("foo");
- RoleModel fooRole = client.addRole("foo-role");
- user.grantRole(fooRole);
- });
+// UserModel user = session.users().addUser(realm, "joel");
+// ClientModel client = realm.addClient("foo");
+// RoleModel fooRole = client.addRole("foo-role");
+// user.grantRole(fooRole);
+// });
- int gRolesCount=0;
+// int gRolesCount=0;
- testingClient.server().run(session -> {
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().getUserByUsername("joel", realm);
- int grantedRolesCount = user.getRoleMappings().size();
+// testingClient.server().run(session -> {
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().getUserByUsername("joel", realm);
+// int grantedRolesCount = user.getRoleMappings().size();
- ClientModel client = realm.getClientByClientId("foo");
- realm.removeClient(client.getId());
+// ClientModel client = realm.getClientByClientId("foo");
+// realm.removeClient(client.getId());
- realm = session.realms().getRealmByName("test");
- user = session.users().getUserByUsername("joel", realm);
+// realm = session.realms().getRealmByName("test");
+// user = session.users().getUserByUsername("joel", realm);
- Set<RoleModel> roles = user.getRoleMappings();
- for (RoleModel role : roles) {
- Assert.assertNotNull(role.getContainer());
- }
+// Set<RoleModel> roles = user.getRoleMappings();
+// for (RoleModel role : roles) {
+// Assert.assertNotNull(role.getContainer());
+// }
- Assert.assertEquals(roles.size(), grantedRolesCount - 1);
- });
+// Assert.assertEquals(roles.size(), grantedRolesCount - 1);
+// });
- }
+// }
-}
+// }
diff --git a/testsuite/integration-deprecated/src/test/java/org/keycloak/testsuite/federation/storage/BrokenUserStorageTest.java b/testsuite/integration-deprecated/src/test/java/org/keycloak/testsuite/federation/storage/BrokenUserStorageTest.java
index 6d7ea34..2f012d1 100644
--- a/testsuite/integration-deprecated/src/test/java/org/keycloak/testsuite/federation/storage/BrokenUserStorageTest.java
+++ b/testsuite/integration-deprecated/src/test/java/org/keycloak/testsuite/federation/storage/BrokenUserStorageTest.java
@@ -1,139 +1,139 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.keycloak.testsuite.federation.storage;
-
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.ClassRule;
-import org.junit.Rule;
-import org.junit.Test;
-import org.keycloak.OAuth2Constants;
-import org.keycloak.admin.client.Keycloak;
-import org.keycloak.admin.client.resource.RealmResource;
-import org.keycloak.common.util.Time;
-import org.keycloak.component.ComponentModel;
-import org.keycloak.models.Constants;
-import org.keycloak.models.GroupModel;
-import org.keycloak.models.KeycloakSession;
-import org.keycloak.models.RealmModel;
-import org.keycloak.models.RoleModel;
-import org.keycloak.models.UserCredentialModel;
-import org.keycloak.models.UserModel;
-import org.keycloak.models.cache.CachedUserModel;
-import org.keycloak.models.cache.infinispan.UserAdapter;
-import org.keycloak.models.jpa.RealmAdapter;
-import org.keycloak.representations.idm.ComponentRepresentation;
-import org.keycloak.services.managers.RealmManager;
-import org.keycloak.storage.StorageId;
-import org.keycloak.storage.UserStorageProvider;
-import org.keycloak.storage.UserStorageProviderModel;
-import org.keycloak.testsuite.ApplicationServlet;
-import org.keycloak.testsuite.OAuthClient;
-import org.keycloak.testsuite.pages.AppPage;
-import org.keycloak.testsuite.pages.LoginPage;
-import org.keycloak.testsuite.rule.KeycloakRule;
-import org.keycloak.testsuite.rule.WebResource;
-import org.keycloak.testsuite.rule.WebRule;
-import org.openqa.selenium.WebDriver;
-
-import java.util.Calendar;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * KEYCLOAK-3903 and KEYCLOAK-3620
- *
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class BrokenUserStorageTest {
- @ClassRule
- public static KeycloakRule keycloakRule = new KeycloakRule();
-
- @Rule
- public WebRule webRule = new WebRule(this);
-
- @WebResource
- protected OAuthClient oauth;
-
- @WebResource
- protected WebDriver driver;
-
- @WebResource
- protected AppPage appPage;
-
- @WebResource
- protected LoginPage loginPage;
-
- private void loginSuccessAndLogout(String username, String password) {
- loginPage.open();
- loginPage.login(username, password);
- Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
- Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
- oauth.openLogout();
- }
- protected String AUTH_SERVER_URL = "http://localhost:8081/auth";
-
- @Test
- public void testBootWithBadProviderId() throws Exception {
- KeycloakSession session = keycloakRule.startSession();
- // set this system property
- System.setProperty(RealmAdapter.COMPONENT_PROVIDER_EXISTS_DISABLED, "true");
- RealmModel realm = session.realms().getRealmByName("master");
- String masterId = realm.getId();
- UserStorageProviderModel model;
- model = new UserStorageProviderModel();
- model.setName("bad-provider-id");
- model.setPriority(2);
- model.setParentId(realm.getId());
- model.setProviderId("error");
- ComponentModel component = realm.importComponentModel(model);
-
- keycloakRule.stopSession(session, true);
-
- keycloakRule.restartServer();
- keycloakRule.deployServlet("app", "/app", ApplicationServlet.class);
-
- loginSuccessAndLogout("test-user@localhost", "password");
-
- // make sure we can list components and delete provider as this is an admin console operation
-
- Keycloak keycloakAdmin = Keycloak.getInstance(AUTH_SERVER_URL, "master", "admin", "admin", Constants.ADMIN_CLI_CLIENT_ID);
- RealmResource master = keycloakAdmin.realms().realm("master");
- List<ComponentRepresentation> components = master.components().query(masterId, UserStorageProvider.class.getName());
- boolean found = false;
- for (ComponentRepresentation rep : components) {
- if (rep.getName().equals("bad-provider-id")) {
- found = true;
- }
- }
- Assert.assertTrue(found);
-
- master.components().component(component.getId()).remove();
-
- List<ComponentRepresentation> components2 = master.components().query(masterId, UserStorageProvider.class.getName());
- Assert.assertEquals(components.size() - 1, components2.size());
- }
-
- @After
- public void resetTimeoffset() {
- Time.setOffset(0);
-
- }
-
- }
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+// package org.keycloak.testsuite.federation.storage;
+
+// import org.junit.After;
+// import org.junit.Assert;
+// import org.junit.ClassRule;
+// import org.junit.Rule;
+// import org.junit.Test;
+// import org.keycloak.OAuth2Constants;
+// import org.keycloak.admin.client.Keycloak;
+// import org.keycloak.admin.client.resource.RealmResource;
+// import org.keycloak.common.util.Time;
+// import org.keycloak.component.ComponentModel;
+// import org.keycloak.models.Constants;
+// import org.keycloak.models.GroupModel;
+// import org.keycloak.models.KeycloakSession;
+// import org.keycloak.models.RealmModel;
+// import org.keycloak.models.RoleModel;
+// import org.keycloak.models.UserCredentialModel;
+// import org.keycloak.models.UserModel;
+// import org.keycloak.models.cache.CachedUserModel;
+// import org.keycloak.models.cache.infinispan.UserAdapter;
+// import org.keycloak.models.jpa.RealmAdapter;
+// import org.keycloak.representations.idm.ComponentRepresentation;
+// import org.keycloak.services.managers.RealmManager;
+// import org.keycloak.storage.StorageId;
+// import org.keycloak.storage.UserStorageProvider;
+// import org.keycloak.storage.UserStorageProviderModel;
+// import org.keycloak.testsuite.ApplicationServlet;
+// import org.keycloak.testsuite.OAuthClient;
+// import org.keycloak.testsuite.pages.AppPage;
+// import org.keycloak.testsuite.pages.LoginPage;
+// import org.keycloak.testsuite.rule.KeycloakRule;
+// import org.keycloak.testsuite.rule.WebResource;
+// import org.keycloak.testsuite.rule.WebRule;
+// import org.openqa.selenium.WebDriver;
+
+// import java.util.Calendar;
+// import java.util.HashSet;
+// import java.util.List;
+// import java.util.Set;
+
+// /**
+// * KEYCLOAK-3903 and KEYCLOAK-3620
+// *
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public class BrokenUserStorageTest {
+// @ClassRule
+// public static KeycloakRule keycloakRule = new KeycloakRule();
+
+// @Rule
+// public WebRule webRule = new WebRule(this);
+
+// @WebResource
+// protected OAuthClient oauth;
+
+// @WebResource
+// protected WebDriver driver;
+
+// @WebResource
+// protected AppPage appPage;
+
+// @WebResource
+// protected LoginPage loginPage;
+
+// private void loginSuccessAndLogout(String username, String password) {
+// loginPage.open();
+// loginPage.login(username, password);
+// Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
+// Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
+// oauth.openLogout();
+// }
+// protected String AUTH_SERVER_URL = "http://localhost:8081/auth";
+
+// @Test
+// public void testBootWithBadProviderId() throws Exception {
+// KeycloakSession session = keycloakRule.startSession();
+// // set this system property
+// System.setProperty(RealmAdapter.COMPONENT_PROVIDER_EXISTS_DISABLED, "true");
+// RealmModel realm = session.realms().getRealmByName("master");
+// String masterId = realm.getId();
+// UserStorageProviderModel model;
+// model = new UserStorageProviderModel();
+// model.setName("bad-provider-id");
+// model.setPriority(2);
+// model.setParentId(realm.getId());
+// model.setProviderId("error");
+// ComponentModel component = realm.importComponentModel(model);
+
+// keycloakRule.stopSession(session, true);
+
+// keycloakRule.restartServer();
+// keycloakRule.deployServlet("app", "/app", ApplicationServlet.class);
+
+// loginSuccessAndLogout("test-user@localhost", "password");
+
+// // make sure we can list components and delete provider as this is an admin console operation
+
+// Keycloak keycloakAdmin = Keycloak.getInstance(AUTH_SERVER_URL, "master", "admin", "admin", Constants.ADMIN_CLI_CLIENT_ID);
+// RealmResource master = keycloakAdmin.realms().realm("master");
+// List<ComponentRepresentation> components = master.components().query(masterId, UserStorageProvider.class.getName());
+// boolean found = false;
+// for (ComponentRepresentation rep : components) {
+// if (rep.getName().equals("bad-provider-id")) {
+// found = true;
+// }
+// }
+// Assert.assertTrue(found);
+
+// master.components().component(component.getId()).remove();
+
+// List<ComponentRepresentation> components2 = master.components().query(masterId, UserStorageProvider.class.getName());
+// Assert.assertEquals(components.size() - 1, components2.size());
+// }
+
+// @After
+// public void resetTimeoffset() {
+// Time.setOffset(0);
+
+// }
+
+// }
diff --git a/testsuite/integration-deprecated/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageFailureTest.java b/testsuite/integration-deprecated/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageFailureTest.java
index 277a164..86e9ebb 100644
--- a/testsuite/integration-deprecated/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageFailureTest.java
+++ b/testsuite/integration-deprecated/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageFailureTest.java
@@ -1,371 +1,371 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.keycloak.testsuite.federation.storage;
-
-import org.junit.Assert;
-import org.junit.ClassRule;
-import org.junit.Rule;
-import org.junit.Test;
-import org.keycloak.OAuth2Constants;
-import org.keycloak.common.constants.ServiceAccountConstants;
-import org.keycloak.component.ComponentModel;
-import org.keycloak.events.Details;
-import org.keycloak.events.Event;
-import org.keycloak.models.ClientModel;
-import org.keycloak.models.KeycloakSession;
-import org.keycloak.models.RealmModel;
-import org.keycloak.models.RoleModel;
-import org.keycloak.models.UserModel;
-import org.keycloak.models.cache.CachedUserModel;
-import org.keycloak.protocol.oidc.OIDCLoginProtocol;
-import org.keycloak.representations.AccessToken;
-import org.keycloak.representations.RefreshToken;
-import org.keycloak.services.managers.RealmManager;
-import org.keycloak.storage.UserStorageProviderModel;
-import org.keycloak.testsuite.ApplicationServlet;
-import org.keycloak.testsuite.AssertEvents;
-import org.keycloak.testsuite.Constants;
-import org.keycloak.testsuite.OAuthClient;
-import org.keycloak.testsuite.pages.AppPage;
-import org.keycloak.testsuite.pages.LoginPage;
-import org.keycloak.testsuite.rule.KeycloakRule;
-import org.keycloak.testsuite.rule.WebResource;
-import org.keycloak.testsuite.rule.WebRule;
-import org.openqa.selenium.WebDriver;
-
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class UserStorageFailureTest {
- public static ComponentModel memoryProvider = null;
- public static String realmName;
- public static final String LOCAL_USER = "localUser";
- @ClassRule
- public static KeycloakRule keycloakRule = new KeycloakRule(new KeycloakRule.KeycloakSetup() {
-
- @Override
- public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
- UserStorageProviderModel model = new UserStorageProviderModel();
- model.setName("failure");
- model.setPriority(0);
- model.setProviderId(FailableHardcodedStorageProviderFactory.PROVIDER_ID);
- model.setParentId(appRealm.getId());
- memoryProvider = appRealm.addComponentModel(model);
- realmName = appRealm.getName();
-
- ClientModel offlineClient = appRealm.addClient("offline-client");
- offlineClient.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
- offlineClient.setEnabled(true);
- offlineClient.setDirectAccessGrantsEnabled(true);
- offlineClient.setSecret("secret");
- HashSet<String> redirects = new HashSet<>();
- redirects.add(Constants.AUTH_SERVER_ROOT + "/offline-client");
- offlineClient.setRedirectUris(redirects);
- offlineClient.setServiceAccountsEnabled(true);
- offlineClient.setFullScopeAllowed(true);
-
- UserModel serviceAccount = manager.getSession().users().addUser(appRealm, ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + offlineClient.getClientId());
- serviceAccount.setEnabled(true);
- RoleModel role = appRealm.getRole("offline_access");
- Assert.assertNotNull(role);
- serviceAccount.grantRole(role);
- serviceAccount.setServiceAccountClientLink(offlineClient.getClientId());
-
- UserModel localUser = manager.getSession().userLocalStorage().addUser(appRealm, LOCAL_USER);
- localUser.setEnabled(true);
-
-
- }
- });
-
- @Rule
- public WebRule webRule = new WebRule(this);
-
- @WebResource
- protected OAuthClient oauth;
-
- @WebResource
- protected WebDriver driver;
-
- @WebResource
- protected AppPage appPage;
-
- @WebResource
- protected LoginPage loginPage;
-
- @Rule
- public AssertEvents events = new AssertEvents(keycloakRule);
-
-
- // this is a hack so that UserModel doesn't have to be available when offline token is imported.
- // see related JIRA - KEYCLOAK-5350 and corresponding test
-
- /**
- * KEYCLOAK-5350
- */
- @Test
- public void testKeycloak5350() {
- oauth.scope(OAuth2Constants.OFFLINE_ACCESS);
- oauth.clientId("offline-client");
- oauth.redirectUri(Constants.AUTH_SERVER_ROOT + "/offline-client");
- oauth.doLogin(FailableHardcodedStorageProvider.username, "password");
-
- Event loginEvent = events.expectLogin()
- .client("offline-client")
- .detail(Details.REDIRECT_URI, Constants.AUTH_SERVER_ROOT + "/offline-client")
- .event();
-
- final String sessionId = loginEvent.getSessionId();
- String codeId = loginEvent.getDetails().get(Details.CODE_ID);
-
- String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
-
- OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "secret");
- AccessToken token = oauth.verifyToken(tokenResponse.getAccessToken());
- String offlineTokenString = tokenResponse.getRefreshToken();
- RefreshToken offlineToken = oauth.parseRefreshToken(offlineTokenString);
- events.clear();
-
- evictUser(FailableHardcodedStorageProvider.username);
-
- KeycloakSession session;
- RealmModel realm;
- UserModel user;
-
- toggleForceFail(true);
-
- // make sure failure is turned on
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName(realmName);
- try {
- user = session.users().getUserByUsername(FailableHardcodedStorageProvider.username, realm);
- Assert.fail();
- } catch (Exception e) {
- Assert.assertEquals("FORCED FAILURE", e.getMessage());
-
- }
- keycloakRule.stopSession(session, false);
-
- // restart server to make sure we can still boot if user storage is down
- keycloakRule.restartServer();
- keycloakRule.deployServlet("app", "/app", ApplicationServlet.class);
-
- toggleForceFail(false);
-
-
- // test that once user storage provider is available again we can still access the token.
- tokenResponse = oauth.doRefreshTokenRequest(offlineTokenString, "secret");
- Assert.assertNotNull(tokenResponse.getAccessToken());
- token = oauth.verifyToken(tokenResponse.getAccessToken());
- offlineTokenString = tokenResponse.getRefreshToken();
- offlineToken = oauth.parseRefreshToken(offlineTokenString);
- events.clear();
-
-
- }
-
- protected void evictUser(String username) {
- KeycloakSession session = keycloakRule.startSession();
- RealmModel realm = session.realms().getRealmByName(realmName);
- UserModel user = session.users().getUserByUsername(username, realm);
- session.userCache().evict(realm, user);
- keycloakRule.stopSession(session, true);
- }
-
- protected void toggleForceFail(boolean toggle) {
- KeycloakSession session;
- RealmModel realm;
- session = keycloakRule.startSession();
- memoryProvider.getConfig().putSingle("fail", Boolean.toString(toggle));
- realm = session.realms().getRealmByName(realmName);
- realm.updateComponent(memoryProvider);
- keycloakRule.stopSession(session, true);
- }
-
- protected void toggleProviderEnabled(boolean toggle) {
- KeycloakSession session;
- RealmModel realm;
- session = keycloakRule.startSession();
- UserStorageProviderModel model = new UserStorageProviderModel(memoryProvider);
- model.setEnabled(toggle);
- realm = session.realms().getRealmByName(realmName);
- realm.updateComponent(model);
- keycloakRule.stopSession(session, true);
- }
-
- private void loginSuccessAndLogout(String username, String password) {
- loginPage.open();
- loginPage.login(username, password);
- System.out.println(driver.getCurrentUrl());
- System.out.println(driver.getPageSource());
- Assert.assertTrue(appPage.isCurrent());
- Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
- Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
- oauth.openLogout();
- }
-
- @Test
- public void testKeycloak5926() {
-
- // make sure local copy is deleted
- {
- KeycloakSession session = keycloakRule.startSession();
- RealmModel realm = session.realms().getRealmByName(realmName);
- UserModel user = session.userLocalStorage().getUserByUsername(FailableHardcodedStorageProvider.username, realm);
- if (user != null) {
- session.userLocalStorage().removeUser(realm, user);
- }
- keycloakRule.stopSession(session, true);
- }
-
- // query user to make sure its imported
- {
- KeycloakSession session = keycloakRule.startSession();
- RealmModel realm = session.realms().getRealmByName(realmName);
- UserModel user = session.users().getUserByUsername(FailableHardcodedStorageProvider.username, realm);
- Assert.assertNotNull(user);
- keycloakRule.stopSession(session, true);
- }
-
-
-
- evictUser(FailableHardcodedStorageProvider.username);
- evictUser(LOCAL_USER);
-
- toggleForceFail(true);
- {
- KeycloakSession session = keycloakRule.startSession();
- // make sure we can still query local users
- RealmModel realm = session.realms().getRealmByName(realmName);
- UserModel local = session.users().getUserByUsername(LOCAL_USER, realm);
- Assert.assertNotNull(local);
- // assert that lookup of user storage user fails
- try {
- UserModel user = session.users().getUserByUsername(FailableHardcodedStorageProvider.username, realm);
- Assert.fail();
- } catch (Exception e) {
- Assert.assertEquals("FORCED FAILURE", e.getMessage());
-
- }
-
- keycloakRule.stopSession(session, true);
- }
- // test that we can still login to a user
- loginSuccessAndLogout("test-user@localhost", "password");
-
- toggleProviderEnabled(false);
- {
- KeycloakSession session = keycloakRule.startSession();
- // make sure we can still query local users
- RealmModel realm = session.realms().getRealmByName(realmName);
- UserModel local = session.users().getUserByUsername(LOCAL_USER, realm);
- Assert.assertNotNull(local);
- List<UserModel> result;
- result = session.users().searchForUser(LOCAL_USER, realm);
- Assert.assertEquals(1, result.size());
- session.users().searchForUser(FailableHardcodedStorageProvider.username, realm);
- Assert.assertEquals(1, result.size());
- session.users().searchForUser(LOCAL_USER, realm, 0, 2);
- Assert.assertEquals(1, result.size());
- session.users().searchForUser(FailableHardcodedStorageProvider.username, realm, 0, 2);
- Assert.assertEquals(1, result.size());
- Map<String, String> localParam = new HashMap<>();
- localParam.put("username", LOCAL_USER);
- Map<String, String> hardcodedParam = new HashMap<>();
- hardcodedParam.put("username", FailableHardcodedStorageProvider.username);
-
- result = session.users().searchForUser(localParam, realm);
- Assert.assertEquals(1, result.size());
- session.users().searchForUser(hardcodedParam, realm);
- Assert.assertEquals(1, result.size());
- session.users().searchForUser(localParam, realm, 0, 2);
- Assert.assertEquals(1, result.size());
- session.users().searchForUser(hardcodedParam, realm, 0, 2);
- Assert.assertEquals(1, result.size());
-
- session.users().getUsers(realm);
- session.users().getUsersCount(realm);
-
-
-
- UserModel user = session.users().getUserByUsername(FailableHardcodedStorageProvider.username, realm);
- Assert.assertFalse(user instanceof CachedUserModel);
- Assert.assertEquals(FailableHardcodedStorageProvider.username, user.getUsername());
- Assert.assertEquals(FailableHardcodedStorageProvider.email, user.getEmail());
- Assert.assertFalse(user.isEnabled());
- try {
- user.setEmail("error@error.com");
- Assert.fail();
- } catch (Exception ex) {
-
- }
- keycloakRule.stopSession(session, true);
- }
- // make sure user isn't cached as provider is disabled
- {
- KeycloakSession session = keycloakRule.startSession();
- RealmModel realm = session.realms().getRealmByName(realmName);
- UserModel user = session.users().getUserByUsername(FailableHardcodedStorageProvider.username, realm);
- Assert.assertFalse(user instanceof CachedUserModel);
- Assert.assertEquals(FailableHardcodedStorageProvider.username, user.getUsername());
- Assert.assertEquals(FailableHardcodedStorageProvider.email, user.getEmail());
- keycloakRule.stopSession(session, true);
- }
-
- // make ABSOLUTELY sure user isn't cached as provider is disabled
- {
- KeycloakSession session = keycloakRule.startSession();
- RealmModel realm = session.realms().getRealmByName(realmName);
- UserModel user = session.users().getUserByUsername(FailableHardcodedStorageProvider.username, realm);
- Assert.assertFalse(user instanceof CachedUserModel);
- Assert.assertEquals(FailableHardcodedStorageProvider.username, user.getUsername());
- Assert.assertEquals(FailableHardcodedStorageProvider.email, user.getEmail());
- keycloakRule.stopSession(session, true);
- }
-
-
-
- toggleProviderEnabled(true);
- toggleForceFail(false);
-
- // user should be cachable now
- {
- KeycloakSession session = keycloakRule.startSession();
- RealmModel realm = session.realms().getRealmByName(realmName);
- UserModel user = session.users().getUserByUsername(FailableHardcodedStorageProvider.username, realm);
- Assert.assertTrue(user instanceof CachedUserModel);
- Assert.assertEquals(FailableHardcodedStorageProvider.username, user.getUsername());
- Assert.assertEquals(FailableHardcodedStorageProvider.email, user.getEmail());
- keycloakRule.stopSession(session, true);
- }
-
- events.clear();
- }
-
-
- //@Test
- public void testIDE() throws Exception {
- Thread.sleep(100000000);
- }
-
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+// package org.keycloak.testsuite.federation.storage;
+
+// import org.junit.Assert;
+// import org.junit.ClassRule;
+// import org.junit.Rule;
+// import org.junit.Test;
+// import org.keycloak.OAuth2Constants;
+// import org.keycloak.common.constants.ServiceAccountConstants;
+// import org.keycloak.component.ComponentModel;
+// import org.keycloak.events.Details;
+// import org.keycloak.events.Event;
+// import org.keycloak.models.ClientModel;
+// import org.keycloak.models.KeycloakSession;
+// import org.keycloak.models.RealmModel;
+// import org.keycloak.models.RoleModel;
+// import org.keycloak.models.UserModel;
+// import org.keycloak.models.cache.CachedUserModel;
+// import org.keycloak.protocol.oidc.OIDCLoginProtocol;
+// import org.keycloak.representations.AccessToken;
+// import org.keycloak.representations.RefreshToken;
+// import org.keycloak.services.managers.RealmManager;
+// import org.keycloak.storage.UserStorageProviderModel;
+// import org.keycloak.testsuite.ApplicationServlet;
+// import org.keycloak.testsuite.AssertEvents;
+// import org.keycloak.testsuite.Constants;
+// import org.keycloak.testsuite.OAuthClient;
+// import org.keycloak.testsuite.pages.AppPage;
+// import org.keycloak.testsuite.pages.LoginPage;
+// import org.keycloak.testsuite.rule.KeycloakRule;
+// import org.keycloak.testsuite.rule.WebResource;
+// import org.keycloak.testsuite.rule.WebRule;
+// import org.openqa.selenium.WebDriver;
+
+// import java.util.HashMap;
+// import java.util.HashSet;
+// import java.util.List;
+// import java.util.Map;
+
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public class UserStorageFailureTest {
+// public static ComponentModel memoryProvider = null;
+// public static String realmName;
+// public static final String LOCAL_USER = "localUser";
+// @ClassRule
+// public static KeycloakRule keycloakRule = new KeycloakRule(new KeycloakRule.KeycloakSetup() {
+
+// @Override
+// public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
+// UserStorageProviderModel model = new UserStorageProviderModel();
+// model.setName("failure");
+// model.setPriority(0);
+// model.setProviderId(FailableHardcodedStorageProviderFactory.PROVIDER_ID);
+// model.setParentId(appRealm.getId());
+// memoryProvider = appRealm.addComponentModel(model);
+// realmName = appRealm.getName();
+
+// ClientModel offlineClient = appRealm.addClient("offline-client");
+// offlineClient.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
+// offlineClient.setEnabled(true);
+// offlineClient.setDirectAccessGrantsEnabled(true);
+// offlineClient.setSecret("secret");
+// HashSet<String> redirects = new HashSet<>();
+// redirects.add(Constants.AUTH_SERVER_ROOT + "/offline-client");
+// offlineClient.setRedirectUris(redirects);
+// offlineClient.setServiceAccountsEnabled(true);
+// offlineClient.setFullScopeAllowed(true);
+
+// UserModel serviceAccount = manager.getSession().users().addUser(appRealm, ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + offlineClient.getClientId());
+// serviceAccount.setEnabled(true);
+// RoleModel role = appRealm.getRole("offline_access");
+// Assert.assertNotNull(role);
+// serviceAccount.grantRole(role);
+// serviceAccount.setServiceAccountClientLink(offlineClient.getClientId());
+
+// UserModel localUser = manager.getSession().userLocalStorage().addUser(appRealm, LOCAL_USER);
+// localUser.setEnabled(true);
+
+
+// }
+// });
+
+// @Rule
+// public WebRule webRule = new WebRule(this);
+
+// @WebResource
+// protected OAuthClient oauth;
+
+// @WebResource
+// protected WebDriver driver;
+
+// @WebResource
+// protected AppPage appPage;
+
+// @WebResource
+// protected LoginPage loginPage;
+
+// @Rule
+// public AssertEvents events = new AssertEvents(keycloakRule);
+
+
+// // this is a hack so that UserModel doesn't have to be available when offline token is imported.
+// // see related JIRA - KEYCLOAK-5350 and corresponding test
+
+// /**
+// * KEYCLOAK-5350
+// */
+// @Test
+// public void testKeycloak5350() {
+// oauth.scope(OAuth2Constants.OFFLINE_ACCESS);
+// oauth.clientId("offline-client");
+// oauth.redirectUri(Constants.AUTH_SERVER_ROOT + "/offline-client");
+// oauth.doLogin(FailableHardcodedStorageProvider.username, "password");
+
+// Event loginEvent = events.expectLogin()
+// .client("offline-client")
+// .detail(Details.REDIRECT_URI, Constants.AUTH_SERVER_ROOT + "/offline-client")
+// .event();
+
+// final String sessionId = loginEvent.getSessionId();
+// String codeId = loginEvent.getDetails().get(Details.CODE_ID);
+
+// String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
+
+// OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "secret");
+// AccessToken token = oauth.verifyToken(tokenResponse.getAccessToken());
+// String offlineTokenString = tokenResponse.getRefreshToken();
+// RefreshToken offlineToken = oauth.parseRefreshToken(offlineTokenString);
+// events.clear();
+
+// evictUser(FailableHardcodedStorageProvider.username);
+
+// KeycloakSession session;
+// RealmModel realm;
+// UserModel user;
+
+// toggleForceFail(true);
+
+// // make sure failure is turned on
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName(realmName);
+// try {
+// user = session.users().getUserByUsername(FailableHardcodedStorageProvider.username, realm);
+// Assert.fail();
+// } catch (Exception e) {
+// Assert.assertEquals("FORCED FAILURE", e.getMessage());
+
+// }
+// keycloakRule.stopSession(session, false);
+
+// // restart server to make sure we can still boot if user storage is down
+// keycloakRule.restartServer();
+// keycloakRule.deployServlet("app", "/app", ApplicationServlet.class);
+
+// toggleForceFail(false);
+
+
+// // test that once user storage provider is available again we can still access the token.
+// tokenResponse = oauth.doRefreshTokenRequest(offlineTokenString, "secret");
+// Assert.assertNotNull(tokenResponse.getAccessToken());
+// token = oauth.verifyToken(tokenResponse.getAccessToken());
+// offlineTokenString = tokenResponse.getRefreshToken();
+// offlineToken = oauth.parseRefreshToken(offlineTokenString);
+// events.clear();
+
+
+// }
+
+// protected void evictUser(String username) {
+// KeycloakSession session = keycloakRule.startSession();
+// RealmModel realm = session.realms().getRealmByName(realmName);
+// UserModel user = session.users().getUserByUsername(username, realm);
+// session.userCache().evict(realm, user);
+// keycloakRule.stopSession(session, true);
+// }
+
+// protected void toggleForceFail(boolean toggle) {
+// KeycloakSession session;
+// RealmModel realm;
+// session = keycloakRule.startSession();
+// memoryProvider.getConfig().putSingle("fail", Boolean.toString(toggle));
+// realm = session.realms().getRealmByName(realmName);
+// realm.updateComponent(memoryProvider);
+// keycloakRule.stopSession(session, true);
+// }
+
+// protected void toggleProviderEnabled(boolean toggle) {
+// KeycloakSession session;
+// RealmModel realm;
+// session = keycloakRule.startSession();
+// UserStorageProviderModel model = new UserStorageProviderModel(memoryProvider);
+// model.setEnabled(toggle);
+// realm = session.realms().getRealmByName(realmName);
+// realm.updateComponent(model);
+// keycloakRule.stopSession(session, true);
+// }
+
+// private void loginSuccessAndLogout(String username, String password) {
+// loginPage.open();
+// loginPage.login(username, password);
+// System.out.println(driver.getCurrentUrl());
+// System.out.println(driver.getPageSource());
+// Assert.assertTrue(appPage.isCurrent());
+// Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
+// Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
+// oauth.openLogout();
+// }
+
+// @Test
+// public void testKeycloak5926() {
+
+// // make sure local copy is deleted
+// {
+// KeycloakSession session = keycloakRule.startSession();
+// RealmModel realm = session.realms().getRealmByName(realmName);
+// UserModel user = session.userLocalStorage().getUserByUsername(FailableHardcodedStorageProvider.username, realm);
+// if (user != null) {
+// session.userLocalStorage().removeUser(realm, user);
+// }
+// keycloakRule.stopSession(session, true);
+// }
+
+// // query user to make sure its imported
+// {
+// KeycloakSession session = keycloakRule.startSession();
+// RealmModel realm = session.realms().getRealmByName(realmName);
+// UserModel user = session.users().getUserByUsername(FailableHardcodedStorageProvider.username, realm);
+// Assert.assertNotNull(user);
+// keycloakRule.stopSession(session, true);
+// }
+
+
+
+// evictUser(FailableHardcodedStorageProvider.username);
+// evictUser(LOCAL_USER);
+
+// toggleForceFail(true);
+// {
+// KeycloakSession session = keycloakRule.startSession();
+// // make sure we can still query local users
+// RealmModel realm = session.realms().getRealmByName(realmName);
+// UserModel local = session.users().getUserByUsername(LOCAL_USER, realm);
+// Assert.assertNotNull(local);
+// // assert that lookup of user storage user fails
+// try {
+// UserModel user = session.users().getUserByUsername(FailableHardcodedStorageProvider.username, realm);
+// Assert.fail();
+// } catch (Exception e) {
+// Assert.assertEquals("FORCED FAILURE", e.getMessage());
+
+// }
+
+// keycloakRule.stopSession(session, true);
+// }
+// // test that we can still login to a user
+// loginSuccessAndLogout("test-user@localhost", "password");
+
+// toggleProviderEnabled(false);
+// {
+// KeycloakSession session = keycloakRule.startSession();
+// // make sure we can still query local users
+// RealmModel realm = session.realms().getRealmByName(realmName);
+// UserModel local = session.users().getUserByUsername(LOCAL_USER, realm);
+// Assert.assertNotNull(local);
+// List<UserModel> result;
+// result = session.users().searchForUser(LOCAL_USER, realm);
+// Assert.assertEquals(1, result.size());
+// session.users().searchForUser(FailableHardcodedStorageProvider.username, realm);
+// Assert.assertEquals(1, result.size());
+// session.users().searchForUser(LOCAL_USER, realm, 0, 2);
+// Assert.assertEquals(1, result.size());
+// session.users().searchForUser(FailableHardcodedStorageProvider.username, realm, 0, 2);
+// Assert.assertEquals(1, result.size());
+// Map<String, String> localParam = new HashMap<>();
+// localParam.put("username", LOCAL_USER);
+// Map<String, String> hardcodedParam = new HashMap<>();
+// hardcodedParam.put("username", FailableHardcodedStorageProvider.username);
+
+// result = session.users().searchForUser(localParam, realm);
+// Assert.assertEquals(1, result.size());
+// session.users().searchForUser(hardcodedParam, realm);
+// Assert.assertEquals(1, result.size());
+// session.users().searchForUser(localParam, realm, 0, 2);
+// Assert.assertEquals(1, result.size());
+// session.users().searchForUser(hardcodedParam, realm, 0, 2);
+// Assert.assertEquals(1, result.size());
+
+// session.users().getUsers(realm);
+// session.users().getUsersCount(realm);
+
+
+
+// UserModel user = session.users().getUserByUsername(FailableHardcodedStorageProvider.username, realm);
+// Assert.assertFalse(user instanceof CachedUserModel);
+// Assert.assertEquals(FailableHardcodedStorageProvider.username, user.getUsername());
+// Assert.assertEquals(FailableHardcodedStorageProvider.email, user.getEmail());
+// Assert.assertFalse(user.isEnabled());
+// try {
+// user.setEmail("error@error.com");
+// Assert.fail();
+// } catch (Exception ex) {
+
+// }
+// keycloakRule.stopSession(session, true);
+// }
+// // make sure user isn't cached as provider is disabled
+// {
+// KeycloakSession session = keycloakRule.startSession();
+// RealmModel realm = session.realms().getRealmByName(realmName);
+// UserModel user = session.users().getUserByUsername(FailableHardcodedStorageProvider.username, realm);
+// Assert.assertFalse(user instanceof CachedUserModel);
+// Assert.assertEquals(FailableHardcodedStorageProvider.username, user.getUsername());
+// Assert.assertEquals(FailableHardcodedStorageProvider.email, user.getEmail());
+// keycloakRule.stopSession(session, true);
+// }
+
+// // make ABSOLUTELY sure user isn't cached as provider is disabled
+// {
+// KeycloakSession session = keycloakRule.startSession();
+// RealmModel realm = session.realms().getRealmByName(realmName);
+// UserModel user = session.users().getUserByUsername(FailableHardcodedStorageProvider.username, realm);
+// Assert.assertFalse(user instanceof CachedUserModel);
+// Assert.assertEquals(FailableHardcodedStorageProvider.username, user.getUsername());
+// Assert.assertEquals(FailableHardcodedStorageProvider.email, user.getEmail());
+// keycloakRule.stopSession(session, true);
+// }
+
+
+
+// toggleProviderEnabled(true);
+// toggleForceFail(false);
+
+// // user should be cachable now
+// {
+// KeycloakSession session = keycloakRule.startSession();
+// RealmModel realm = session.realms().getRealmByName(realmName);
+// UserModel user = session.users().getUserByUsername(FailableHardcodedStorageProvider.username, realm);
+// Assert.assertTrue(user instanceof CachedUserModel);
+// Assert.assertEquals(FailableHardcodedStorageProvider.username, user.getUsername());
+// Assert.assertEquals(FailableHardcodedStorageProvider.email, user.getEmail());
+// keycloakRule.stopSession(session, true);
+// }
+
+// events.clear();
+// }
+
+
+// //@Test
+// public void testIDE() throws Exception {
+// Thread.sleep(100000000);
+// }
+
+// }
diff --git a/testsuite/integration-deprecated/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageTest.java b/testsuite/integration-deprecated/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageTest.java
index d446985..ca37032 100644
--- a/testsuite/integration-deprecated/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageTest.java
+++ b/testsuite/integration-deprecated/src/test/java/org/keycloak/testsuite/federation/storage/UserStorageTest.java
@@ -1,570 +1,570 @@
-/*
- * Copyright 2016 Red Hat, Inc. and/or its affiliates
- * and other contributors as indicated by the @author tags.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.keycloak.testsuite.federation.storage;
-
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.ClassRule;
-import org.junit.Rule;
-import org.junit.Test;
-import org.keycloak.OAuth2Constants;
-import org.keycloak.common.util.Time;
-import org.keycloak.component.ComponentModel;
-import org.keycloak.credential.CredentialAuthentication;
-import org.keycloak.credential.UserCredentialStoreManager;
-import org.keycloak.models.GroupModel;
-import org.keycloak.models.KeycloakSession;
-import org.keycloak.models.RealmModel;
-import org.keycloak.models.RoleModel;
-import org.keycloak.models.UserCredentialModel;
-import org.keycloak.models.UserModel;
-import org.keycloak.models.cache.CachedUserModel;
-import org.keycloak.models.cache.infinispan.UserAdapter;
-import org.keycloak.services.managers.RealmManager;
-import org.keycloak.storage.StorageId;
-import org.keycloak.storage.UserStorageProviderModel;
-import org.keycloak.testsuite.OAuthClient;
-import org.keycloak.testsuite.pages.AppPage;
-import org.keycloak.testsuite.pages.LoginPage;
-import org.keycloak.testsuite.rule.KeycloakRule;
-import org.keycloak.testsuite.rule.WebResource;
-import org.keycloak.testsuite.rule.WebRule;
-import org.openqa.selenium.WebDriver;
-
-import java.util.Calendar;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
- * @version $Revision: 1 $
- */
-public class UserStorageTest {
- public static ComponentModel memoryProvider = null;
- public static ComponentModel writableProvider = null;
- @ClassRule
- public static KeycloakRule keycloakRule = new KeycloakRule(new KeycloakRule.KeycloakSetup() {
-
- @Override
- public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
- UserStorageProviderModel model = new UserStorageProviderModel();
- model.setName("memory");
- model.setPriority(0);
- model.setProviderId(UserMapStorageFactory.PROVIDER_ID);
- model.setParentId(appRealm.getId());
- memoryProvider = appRealm.addComponentModel(model);
-
- model = new UserStorageProviderModel();
- model.setName("read-only-user-props");
- model.setPriority(1);
- model.setProviderId(UserPropertyFileStorageFactory.PROVIDER_ID);
- model.setParentId(appRealm.getId());
- model.getConfig().putSingle("propertyFile", "/storage-test/read-only-user-password.properties");
- appRealm.addComponentModel(model);
- createUserPropModel(appRealm);
- }
- });
-
- private static void createUserPropModel(RealmModel appRealm) {
- UserStorageProviderModel model;
- model = new UserStorageProviderModel();
- model.setName("user-props");
- model.setPriority(2);
- model.setParentId(appRealm.getId());
- model.setProviderId(UserPropertyFileStorageFactory.PROVIDER_ID);
- model.getConfig().putSingle("propertyFile", "/storage-test/user-password.properties");
- model.getConfig().putSingle("federatedStorage", "true");
- writableProvider = appRealm.addComponentModel(model);
- }
-
- @Rule
- public WebRule webRule = new WebRule(this);
-
- @WebResource
- protected OAuthClient oauth;
-
- @WebResource
- protected WebDriver driver;
-
- @WebResource
- protected AppPage appPage;
-
- @WebResource
- protected LoginPage loginPage;
-
- private void loginSuccessAndLogout(String username, String password) {
- loginPage.open();
- loginPage.login(username, password);
- Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
- Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
- oauth.openLogout();
- }
-
- public void loginBadPassword(String username) {
- loginPage.open();
- loginPage.login("username", "badpassword");
- Assert.assertEquals("Invalid username or password.", loginPage.getError());
- }
-
- @Test
- public void testLoginSuccess() {
- loginSuccessAndLogout("tbrady", "goat");
- loginSuccessAndLogout("thor", "hammer");
- loginBadPassword("tbrady");
- }
-
- @After
- public void resetTimeoffset() {
- Time.setOffset(0);
-
- }
-
- //@Test
- public void testIDE() throws Exception {
- Thread.sleep(100000000);
- }
-
- /**
- * KEYCLOAK-4013
- *
- * @throws Exception
- */
- @Test
- public void testCast() throws Exception {
- KeycloakSession session = keycloakRule.startSession();
- List<CredentialAuthentication> list = UserCredentialStoreManager.getCredentialProviders(session, null, CredentialAuthentication.class);
- keycloakRule.stopSession(session, true);
-
- }
-
- @Test
- public void testDailyEviction() {
- Calendar cal = Calendar.getInstance();
- cal.add(Calendar.HOUR, 1);
- int hour = cal.get(Calendar.HOUR_OF_DAY);
- int min = cal.get(Calendar.MINUTE);
-
- UserStorageProviderModel model = new UserStorageProviderModel(writableProvider);
- model.setCachePolicy(UserStorageProviderModel.CachePolicy.EVICT_DAILY);
- model.setEvictionHour(cal.get(Calendar.HOUR_OF_DAY));
- model.setEvictionMinute(cal.get(Calendar.MINUTE));
-
- KeycloakSession session = keycloakRule.startSession();
- RealmModel realm = session.realms().getRealmByName("test");
- CachedUserModel thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
- long lastTimestamp = thor.getCacheTimestamp();
- realm.updateComponent(model);
- keycloakRule.stopSession(session, true);
-
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
- thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
- lastTimestamp = thor.getCacheTimestamp();
- realm.updateComponent(model);
- keycloakRule.stopSession(session, true);
-
- // test is cached
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
- thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
- // thor should be evicted because we changed the model
- Assert.assertTrue(thor.getCacheTimestamp() > lastTimestamp);
- lastTimestamp = thor.getCacheTimestamp();
- keycloakRule.stopSession(session, true);
-
-
- Time.setOffset(60 * 2 * 60); // 2 hours
-
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
- UserModel thor2 = session.users().getUserByUsername("thor", realm);
- // thor should be evicted because we put it 2 hours in the future
- if (thor2 instanceof CachedUserModel) {
- Assert.assertTrue(((CachedUserModel)thor2).getCacheTimestamp() > lastTimestamp);
- }
- model.getConfig().remove("cachePolicy");
- model.getConfig().remove("evictionHour");
- model.getConfig().remove("evictionMinute");
- realm.updateComponent(model);
- keycloakRule.stopSession(session, true);
- }
-
- @Test
- public void testWeeklyEviction() {
- Calendar cal = Calendar.getInstance();
-
- // sets day of the week to 4 days from now
- cal.add(Calendar.HOUR, 4 * 24);
-
- UserStorageProviderModel model = new UserStorageProviderModel(writableProvider);
- model.setCachePolicy(UserStorageProviderModel.CachePolicy.EVICT_WEEKLY);
- model.setEvictionDay(cal.get(Calendar.DAY_OF_WEEK));
- model.setEvictionHour(cal.get(Calendar.HOUR_OF_DAY));
- model.setEvictionMinute(cal.get(Calendar.MINUTE));
-
- KeycloakSession session = keycloakRule.startSession();
- RealmModel realm = session.realms().getRealmByName("test");
- realm.updateComponent(model);
- keycloakRule.stopSession(session, true);
-
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
- CachedUserModel thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
- long lastTimestamp = thor.getCacheTimestamp();
- keycloakRule.stopSession(session, true);
-
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
- thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
- lastTimestamp = thor.getCacheTimestamp();
- keycloakRule.stopSession(session, true);
-
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
- thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
- lastTimestamp = thor.getCacheTimestamp();
- keycloakRule.stopSession(session, true);
-
- Time.setOffset(60 * 60 * 24 * 2); // 2 days in future, should be cached still
-
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
- // test still
- thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
- Assert.assertEquals(thor.getCacheTimestamp(), lastTimestamp);
- lastTimestamp = thor.getCacheTimestamp();
- keycloakRule.stopSession(session, true);
-
- Time.setOffset(Time.getOffset() + 60 * 60 * 24 * 3); // 3 days into future, cache will be invalidated
-
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
- UserModel thor2 = session.users().getUserByUsername("thor", realm);
- // thor should be evicted because we put it 2 hours in the future
- if (thor2 instanceof CachedUserModel) {
- Assert.assertTrue(((CachedUserModel)thor2).getCacheTimestamp() > lastTimestamp);
- }
- model.getConfig().remove("cachePolicy");
- model.getConfig().remove("evictionHour");
- model.getConfig().remove("evictionMinute");
- model.getConfig().remove("evictionDay");
- realm.updateComponent(model);
- keycloakRule.stopSession(session, true);
- }
-
- @Test
- public void testMaxLifespanEviction() {
- UserStorageProviderModel model = new UserStorageProviderModel(writableProvider);
- model.setCachePolicy(UserStorageProviderModel.CachePolicy.MAX_LIFESPAN);
- model.setMaxLifespan(600000); // Lifetime is 10 minutes
-
- KeycloakSession session = keycloakRule.startSession();
- RealmModel realm = session.realms().getRealmByName("test");
- realm.updateComponent(model);
- keycloakRule.stopSession(session, true);
-
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
- CachedUserModel thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
- long lastTimestamp = thor.getCacheTimestamp();
- keycloakRule.stopSession(session, true);
-
-
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
- thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
- lastTimestamp = thor.getCacheTimestamp();
- keycloakRule.stopSession(session, true);
-
-
- Time.setOffset(60 * 5); // 5 minutes in future, should be cached still
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
- thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
- Assert.assertEquals(thor.getCacheTimestamp(), lastTimestamp);
- lastTimestamp = thor.getCacheTimestamp();
- keycloakRule.stopSession(session, true);
-
- Time.setOffset(60 * 20); // 20 minutes into future, cache will be invalidated
-
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
- UserModel thor2 = session.users().getUserByUsername("thor", realm);
- // thor should be evicted because we put it 2 hours in the future
- if (thor2 instanceof CachedUserModel) {
- Assert.assertTrue(((CachedUserModel)thor2).getCacheTimestamp() > lastTimestamp);
- }
- keycloakRule.stopSession(session, true);
-
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
- model.getConfig().remove("cachePolicy");
- model.getConfig().remove("maxLifespan");
- realm.updateComponent(model);
- keycloakRule.stopSession(session, true);
- }
-
- @Test
- public void testNoCache() {
- UserStorageProviderModel model = new UserStorageProviderModel(writableProvider);
- model.setCachePolicy(UserStorageProviderModel.CachePolicy.NO_CACHE);
- KeycloakSession session = keycloakRule.startSession();
- RealmModel realm = session.realms().getRealmByName("test");
- CachedUserModel thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
- realm.updateComponent(model);
- keycloakRule.stopSession(session, true);
-
-
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
- // test still
- UserModel thor2 = session.users().getUserByUsername("thor", realm);
- Assert.assertFalse(thor2 instanceof CachedUserModel);
- keycloakRule.stopSession(session, true);
-
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
- thor2 = session.users().getUserByUsername("thor", realm);
- Assert.assertFalse(thor2 instanceof CachedUserModel);
- model.getConfig().remove("cachePolicy");
- model.getConfig().remove("evictionHour");
- model.getConfig().remove("evictionMinute");
- model.getConfig().remove("evictionDay");
- realm.updateComponent(model);
- keycloakRule.stopSession(session, true);
-
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
- thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
- keycloakRule.stopSession(session, true);
-
- }
-
- @Test
- public void testUpdate() {
- KeycloakSession session = keycloakRule.startSession();
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel thor = session.users().getUserByUsername("thor", realm);
- thor.setFirstName("Stian");
- thor.setLastName("Thorgersen");
- thor.setEmailVerified(true);
- long thorCreated = System.currentTimeMillis() - 100;
- thor.setCreatedTimestamp(thorCreated);
- thor.setEmail("thor@hammer.com");
- thor.setSingleAttribute("test-attribute", "value");
- RoleModel role = realm.addRole("foo-role");
- thor.grantRole(role);
- GroupModel group = realm.createGroup("my-group");
- thor.joinGroup(group);
- thor.addRequiredAction("POOP");
- keycloakRule.stopSession(session, true);
-
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
- thor = session.users().getUserByUsername("thor", realm);
- Assert.assertEquals("Stian", thor.getFirstName());
- Assert.assertEquals("Thorgersen", thor.getLastName());
- Assert.assertEquals("thor@hammer.com", thor.getEmail());
- Assert.assertEquals("value", thor.getFirstAttribute("test-attribute"));
- Assert.assertTrue(thor.isEmailVerified());
- Assert.assertTrue(thor instanceof UserAdapter);
- Set<RoleModel> roles = thor.getRoleMappings();
- System.out.println("num roles " + roles.size());
- Assert.assertTrue(roles.size() > 1);
- role = realm.getRole("foo-role");
- Assert.assertTrue(thor.hasRole(role));
-
- Set<GroupModel> groups = thor.getGroups();
- boolean foundGroup = false;
- for (GroupModel g : groups) {
- if (g.getName().equals("my-group")) foundGroup = true;
-
- }
- Assert.assertTrue(foundGroup);
- System.out.println("num groups " + groups.size());
- Assert.assertTrue(thor.getRequiredActions().iterator().next().equals("POOP"));
- thor.removeRequiredAction("POOP");
- session.userCredentialManager().updateCredential(realm, thor, UserCredentialModel.password("lightning"));
- keycloakRule.stopSession(session, true);
- loginSuccessAndLogout("thor", "lightning");
-
- // test removal of provider
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
- realm.removeComponent(writableProvider);
- keycloakRule.stopSession(session, true);
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
- createUserPropModel(realm);
- keycloakRule.stopSession(session, true);
-
- loginSuccessAndLogout("thor", "hammer");
-
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
-
- thor = session.users().getUserByUsername("thor", realm);
- Assert.assertNull(thor.getFirstName());
- Assert.assertNull(thor.getLastName());
- Assert.assertNull(thor.getEmail());
- Assert.assertNull(thor.getFirstAttribute("test-attribute"));
- Assert.assertFalse(thor.isEmailVerified());
- role = realm.getRole("foo-role");
- Assert.assertFalse(thor.hasRole(role));
-
- groups = thor.getGroups();
- foundGroup = false;
- for (GroupModel g : groups) {
- if (g.getName().equals("my-group")) foundGroup = true;
-
- }
- Assert.assertFalse(foundGroup);
-
-
- }
-
- @Test
- public void testQuery() {
- KeycloakSession session = keycloakRule.startSession();
- RealmModel realm = session.realms().getRealmByName("test");
-
- // Test paging
- List<UserModel> localUsers = session.userLocalStorage().getUsers(realm, false);
- Set<UserModel> queried = new HashSet<>();
- // tests assumes that local storage is queried first
- int first = localUsers.size();
- while (queried.size() < 8) {
- List<UserModel> results = session.users().getUsers(realm, first, 3);
- if (results.size() == 0) break;
- first += results.size();
- queried.addAll(results);
-
- }
- Set<String> usernames = new HashSet<>();
- for (UserModel user : queried) {
- usernames.add(user.getUsername());
- System.out.println(user.getUsername());
-
- }
- Assert.assertEquals(8, queried.size());
- Assert.assertTrue(usernames.contains("thor"));
- Assert.assertTrue(usernames.contains("zeus"));
- Assert.assertTrue(usernames.contains("apollo"));
- Assert.assertTrue(usernames.contains("perseus"));
- Assert.assertTrue(usernames.contains("tbrady"));
- Assert.assertTrue(usernames.contains("rob"));
- Assert.assertTrue(usernames.contains("jules"));
- Assert.assertTrue(usernames.contains("danny"));
-
- // test searchForUser
- List<UserModel> users = session.users().searchForUser("tbrady", realm);
- Assert.assertTrue(users.size() == 1);
- Assert.assertTrue(users.get(0).getUsername().equals("tbrady"));
-
- // test getGroupMembers()
- GroupModel gods = realm.createGroup("gods");
- UserModel user = null;
- user = session.users().getUserByUsername("apollo", realm);
- user.joinGroup(gods);
- user = session.users().getUserByUsername("zeus", realm);
- user.joinGroup(gods);
- user = session.users().getUserByUsername("thor", realm);
- user.joinGroup(gods);
- queried.clear();
- usernames.clear();
-
- first = 0;
- while (queried.size() < 8) {
- List<UserModel> results = session.users().getGroupMembers(realm, gods, first, 1);
- if (results.size() == 0) break;
- first += results.size();
- queried.addAll(results);
-
- }
- for (UserModel u : queried) {
- usernames.add(u.getUsername());
- System.out.println(u.getUsername());
-
- }
- Assert.assertEquals(3, queried.size());
- Assert.assertTrue(usernames.contains("apollo"));
- Assert.assertTrue(usernames.contains("zeus"));
- Assert.assertTrue(usernames.contains("thor"));
-
- // search by single attribute
- System.out.println("search by single attribute");
- user = session.users().getUserByUsername("thor", realm);
- user.setSingleAttribute("weapon", "hammer");
-
- users = session.users().searchForUserByUserAttribute("weapon", "hammer", realm);
- for (UserModel u : users) {
- System.out.println(u.getUsername());
-
- }
- Assert.assertEquals(1, users.size());
- Assert.assertEquals("thor", users.get(0).getUsername());
-
-
- keycloakRule.stopSession(session, true);
- }
-
- @Test
- public void testRegistration() {
- KeycloakSession session = keycloakRule.startSession();
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().addUser(realm, "memuser");
- session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password("password"));
- keycloakRule.stopSession(session, true);
- loginSuccessAndLogout("memuser", "password");
- loginSuccessAndLogout("memuser", "password");
- loginSuccessAndLogout("memuser", "password");
-
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
- user = session.users().getUserByUsername("memuser", realm);
- Assert.assertEquals(memoryProvider.getId(), StorageId.resolveProviderId(user));
- session.users().removeUser(realm, user);
- Assert.assertNull(session.users().getUserByUsername("memuser", realm));
- keycloakRule.stopSession(session, true);
-
- }
-
- @Test
- public void testLifecycle() {
- UserMapStorage.allocations.set(0);
- UserMapStorage.closings.set(0);
- KeycloakSession session = keycloakRule.startSession();
- RealmModel realm = session.realms().getRealmByName("test");
- UserModel user = session.users().addUser(realm, "memuser");
- Assert.assertNotNull(user);
- user = session.users().getUserByUsername("nonexistent", realm);
- Assert.assertNull(user);
- keycloakRule.stopSession(session, true);
- Assert.assertEquals(1, UserMapStorage.allocations.get());
- Assert.assertEquals(1, UserMapStorage.closings.get());
-
- session = keycloakRule.startSession();
- realm = session.realms().getRealmByName("test");
- user = session.users().getUserByUsername("memuser", realm);
- session.users().removeUser(realm, user);
- Assert.assertNull(session.users().getUserByUsername("memuser", realm));
- keycloakRule.stopSession(session, true);
-
- }
-
-}
+// /*
+// * Copyright 2016 Red Hat, Inc. and/or its affiliates
+// * and other contributors as indicated by the @author tags.
+// *
+// * Licensed under the Apache License, Version 2.0 (the "License");
+// * you may not use this file except in compliance with the License.
+// * You may obtain a copy of the License at
+// *
+// * http://www.apache.org/licenses/LICENSE-2.0
+// *
+// * Unless required by applicable law or agreed to in writing, software
+// * distributed under the License is distributed on an "AS IS" BASIS,
+// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// * See the License for the specific language governing permissions and
+// * limitations under the License.
+// */
+// package org.keycloak.testsuite.federation.storage;
+
+// import org.junit.After;
+// import org.junit.Assert;
+// import org.junit.ClassRule;
+// import org.junit.Rule;
+// import org.junit.Test;
+// import org.keycloak.OAuth2Constants;
+// import org.keycloak.common.util.Time;
+// import org.keycloak.component.ComponentModel;
+// import org.keycloak.credential.CredentialAuthentication;
+// import org.keycloak.credential.UserCredentialStoreManager;
+// import org.keycloak.models.GroupModel;
+// import org.keycloak.models.KeycloakSession;
+// import org.keycloak.models.RealmModel;
+// import org.keycloak.models.RoleModel;
+// import org.keycloak.models.UserCredentialModel;
+// import org.keycloak.models.UserModel;
+// import org.keycloak.models.cache.CachedUserModel;
+// import org.keycloak.models.cache.infinispan.UserAdapter;
+// import org.keycloak.services.managers.RealmManager;
+// import org.keycloak.storage.StorageId;
+// import org.keycloak.storage.UserStorageProviderModel;
+// import org.keycloak.testsuite.OAuthClient;
+// import org.keycloak.testsuite.pages.AppPage;
+// import org.keycloak.testsuite.pages.LoginPage;
+// import org.keycloak.testsuite.rule.KeycloakRule;
+// import org.keycloak.testsuite.rule.WebResource;
+// import org.keycloak.testsuite.rule.WebRule;
+// import org.openqa.selenium.WebDriver;
+
+// import java.util.Calendar;
+// import java.util.HashSet;
+// import java.util.List;
+// import java.util.Set;
+
+// /**
+// * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
+// * @version $Revision: 1 $
+// */
+// public class UserStorageTest {
+// public static ComponentModel memoryProvider = null;
+// public static ComponentModel writableProvider = null;
+// @ClassRule
+// public static KeycloakRule keycloakRule = new KeycloakRule(new KeycloakRule.KeycloakSetup() {
+
+// @Override
+// public void config(RealmManager manager, RealmModel adminstrationRealm, RealmModel appRealm) {
+// UserStorageProviderModel model = new UserStorageProviderModel();
+// model.setName("memory");
+// model.setPriority(0);
+// model.setProviderId(UserMapStorageFactory.PROVIDER_ID);
+// model.setParentId(appRealm.getId());
+// memoryProvider = appRealm.addComponentModel(model);
+
+// model = new UserStorageProviderModel();
+// model.setName("read-only-user-props");
+// model.setPriority(1);
+// model.setProviderId(UserPropertyFileStorageFactory.PROVIDER_ID);
+// model.setParentId(appRealm.getId());
+// model.getConfig().putSingle("propertyFile", "/storage-test/read-only-user-password.properties");
+// appRealm.addComponentModel(model);
+// createUserPropModel(appRealm);
+// }
+// });
+
+// private static void createUserPropModel(RealmModel appRealm) {
+// UserStorageProviderModel model;
+// model = new UserStorageProviderModel();
+// model.setName("user-props");
+// model.setPriority(2);
+// model.setParentId(appRealm.getId());
+// model.setProviderId(UserPropertyFileStorageFactory.PROVIDER_ID);
+// model.getConfig().putSingle("propertyFile", "/storage-test/user-password.properties");
+// model.getConfig().putSingle("federatedStorage", "true");
+// writableProvider = appRealm.addComponentModel(model);
+// }
+
+// @Rule
+// public WebRule webRule = new WebRule(this);
+
+// @WebResource
+// protected OAuthClient oauth;
+
+// @WebResource
+// protected WebDriver driver;
+
+// @WebResource
+// protected AppPage appPage;
+
+// @WebResource
+// protected LoginPage loginPage;
+
+// private void loginSuccessAndLogout(String username, String password) {
+// loginPage.open();
+// loginPage.login(username, password);
+// Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
+// Assert.assertNotNull(oauth.getCurrentQuery().get(OAuth2Constants.CODE));
+// oauth.openLogout();
+// }
+
+// public void loginBadPassword(String username) {
+// loginPage.open();
+// loginPage.login("username", "badpassword");
+// Assert.assertEquals("Invalid username or password.", loginPage.getError());
+// }
+
+// @Test
+// public void testLoginSuccess() {
+// loginSuccessAndLogout("tbrady", "goat");
+// loginSuccessAndLogout("thor", "hammer");
+// loginBadPassword("tbrady");
+// }
+
+// @After
+// public void resetTimeoffset() {
+// Time.setOffset(0);
+
+// }
+
+// //@Test
+// public void testIDE() throws Exception {
+// Thread.sleep(100000000);
+// }
+
+// /**
+// * KEYCLOAK-4013
+// *
+// * @throws Exception
+// */
+// @Test
+// public void testCast() throws Exception {
+// KeycloakSession session = keycloakRule.startSession();
+// List<CredentialAuthentication> list = UserCredentialStoreManager.getCredentialProviders(session, null, CredentialAuthentication.class);
+// keycloakRule.stopSession(session, true);
+
+// }
+
+// @Test
+// public void testDailyEviction() {
+// Calendar cal = Calendar.getInstance();
+// cal.add(Calendar.HOUR, 1);
+// int hour = cal.get(Calendar.HOUR_OF_DAY);
+// int min = cal.get(Calendar.MINUTE);
+
+// UserStorageProviderModel model = new UserStorageProviderModel(writableProvider);
+// model.setCachePolicy(UserStorageProviderModel.CachePolicy.EVICT_DAILY);
+// model.setEvictionHour(cal.get(Calendar.HOUR_OF_DAY));
+// model.setEvictionMinute(cal.get(Calendar.MINUTE));
+
+// KeycloakSession session = keycloakRule.startSession();
+// RealmModel realm = session.realms().getRealmByName("test");
+// CachedUserModel thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
+// long lastTimestamp = thor.getCacheTimestamp();
+// realm.updateComponent(model);
+// keycloakRule.stopSession(session, true);
+
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+// thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
+// lastTimestamp = thor.getCacheTimestamp();
+// realm.updateComponent(model);
+// keycloakRule.stopSession(session, true);
+
+// // test is cached
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+// thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
+// // thor should be evicted because we changed the model
+// Assert.assertTrue(thor.getCacheTimestamp() > lastTimestamp);
+// lastTimestamp = thor.getCacheTimestamp();
+// keycloakRule.stopSession(session, true);
+
+
+// Time.setOffset(60 * 2 * 60); // 2 hours
+
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+// UserModel thor2 = session.users().getUserByUsername("thor", realm);
+// // thor should be evicted because we put it 2 hours in the future
+// if (thor2 instanceof CachedUserModel) {
+// Assert.assertTrue(((CachedUserModel)thor2).getCacheTimestamp() > lastTimestamp);
+// }
+// model.getConfig().remove("cachePolicy");
+// model.getConfig().remove("evictionHour");
+// model.getConfig().remove("evictionMinute");
+// realm.updateComponent(model);
+// keycloakRule.stopSession(session, true);
+// }
+
+// @Test
+// public void testWeeklyEviction() {
+// Calendar cal = Calendar.getInstance();
+
+// // sets day of the week to 4 days from now
+// cal.add(Calendar.HOUR, 4 * 24);
+
+// UserStorageProviderModel model = new UserStorageProviderModel(writableProvider);
+// model.setCachePolicy(UserStorageProviderModel.CachePolicy.EVICT_WEEKLY);
+// model.setEvictionDay(cal.get(Calendar.DAY_OF_WEEK));
+// model.setEvictionHour(cal.get(Calendar.HOUR_OF_DAY));
+// model.setEvictionMinute(cal.get(Calendar.MINUTE));
+
+// KeycloakSession session = keycloakRule.startSession();
+// RealmModel realm = session.realms().getRealmByName("test");
+// realm.updateComponent(model);
+// keycloakRule.stopSession(session, true);
+
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+// CachedUserModel thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
+// long lastTimestamp = thor.getCacheTimestamp();
+// keycloakRule.stopSession(session, true);
+
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+// thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
+// lastTimestamp = thor.getCacheTimestamp();
+// keycloakRule.stopSession(session, true);
+
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+// thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
+// lastTimestamp = thor.getCacheTimestamp();
+// keycloakRule.stopSession(session, true);
+
+// Time.setOffset(60 * 60 * 24 * 2); // 2 days in future, should be cached still
+
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+// // test still
+// thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
+// Assert.assertEquals(thor.getCacheTimestamp(), lastTimestamp);
+// lastTimestamp = thor.getCacheTimestamp();
+// keycloakRule.stopSession(session, true);
+
+// Time.setOffset(Time.getOffset() + 60 * 60 * 24 * 3); // 3 days into future, cache will be invalidated
+
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+// UserModel thor2 = session.users().getUserByUsername("thor", realm);
+// // thor should be evicted because we put it 2 hours in the future
+// if (thor2 instanceof CachedUserModel) {
+// Assert.assertTrue(((CachedUserModel)thor2).getCacheTimestamp() > lastTimestamp);
+// }
+// model.getConfig().remove("cachePolicy");
+// model.getConfig().remove("evictionHour");
+// model.getConfig().remove("evictionMinute");
+// model.getConfig().remove("evictionDay");
+// realm.updateComponent(model);
+// keycloakRule.stopSession(session, true);
+// }
+
+// @Test
+// public void testMaxLifespanEviction() {
+// UserStorageProviderModel model = new UserStorageProviderModel(writableProvider);
+// model.setCachePolicy(UserStorageProviderModel.CachePolicy.MAX_LIFESPAN);
+// model.setMaxLifespan(600000); // Lifetime is 10 minutes
+
+// KeycloakSession session = keycloakRule.startSession();
+// RealmModel realm = session.realms().getRealmByName("test");
+// realm.updateComponent(model);
+// keycloakRule.stopSession(session, true);
+
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+// CachedUserModel thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
+// long lastTimestamp = thor.getCacheTimestamp();
+// keycloakRule.stopSession(session, true);
+
+
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+// thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
+// lastTimestamp = thor.getCacheTimestamp();
+// keycloakRule.stopSession(session, true);
+
+
+// Time.setOffset(60 * 5); // 5 minutes in future, should be cached still
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+// thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
+// Assert.assertEquals(thor.getCacheTimestamp(), lastTimestamp);
+// lastTimestamp = thor.getCacheTimestamp();
+// keycloakRule.stopSession(session, true);
+
+// Time.setOffset(60 * 20); // 20 minutes into future, cache will be invalidated
+
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+// UserModel thor2 = session.users().getUserByUsername("thor", realm);
+// // thor should be evicted because we put it 2 hours in the future
+// if (thor2 instanceof CachedUserModel) {
+// Assert.assertTrue(((CachedUserModel)thor2).getCacheTimestamp() > lastTimestamp);
+// }
+// keycloakRule.stopSession(session, true);
+
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+// model.getConfig().remove("cachePolicy");
+// model.getConfig().remove("maxLifespan");
+// realm.updateComponent(model);
+// keycloakRule.stopSession(session, true);
+// }
+
+// @Test
+// public void testNoCache() {
+// UserStorageProviderModel model = new UserStorageProviderModel(writableProvider);
+// model.setCachePolicy(UserStorageProviderModel.CachePolicy.NO_CACHE);
+// KeycloakSession session = keycloakRule.startSession();
+// RealmModel realm = session.realms().getRealmByName("test");
+// CachedUserModel thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
+// realm.updateComponent(model);
+// keycloakRule.stopSession(session, true);
+
+
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+// // test still
+// UserModel thor2 = session.users().getUserByUsername("thor", realm);
+// Assert.assertFalse(thor2 instanceof CachedUserModel);
+// keycloakRule.stopSession(session, true);
+
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+// thor2 = session.users().getUserByUsername("thor", realm);
+// Assert.assertFalse(thor2 instanceof CachedUserModel);
+// model.getConfig().remove("cachePolicy");
+// model.getConfig().remove("evictionHour");
+// model.getConfig().remove("evictionMinute");
+// model.getConfig().remove("evictionDay");
+// realm.updateComponent(model);
+// keycloakRule.stopSession(session, true);
+
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+// thor = (CachedUserModel)session.users().getUserByUsername("thor", realm);
+// keycloakRule.stopSession(session, true);
+
+// }
+
+// @Test
+// public void testUpdate() {
+// KeycloakSession session = keycloakRule.startSession();
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel thor = session.users().getUserByUsername("thor", realm);
+// thor.setFirstName("Stian");
+// thor.setLastName("Thorgersen");
+// thor.setEmailVerified(true);
+// long thorCreated = System.currentTimeMillis() - 100;
+// thor.setCreatedTimestamp(thorCreated);
+// thor.setEmail("thor@hammer.com");
+// thor.setSingleAttribute("test-attribute", "value");
+// RoleModel role = realm.addRole("foo-role");
+// thor.grantRole(role);
+// GroupModel group = realm.createGroup("my-group");
+// thor.joinGroup(group);
+// thor.addRequiredAction("POOP");
+// keycloakRule.stopSession(session, true);
+
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+// thor = session.users().getUserByUsername("thor", realm);
+// Assert.assertEquals("Stian", thor.getFirstName());
+// Assert.assertEquals("Thorgersen", thor.getLastName());
+// Assert.assertEquals("thor@hammer.com", thor.getEmail());
+// Assert.assertEquals("value", thor.getFirstAttribute("test-attribute"));
+// Assert.assertTrue(thor.isEmailVerified());
+// Assert.assertTrue(thor instanceof UserAdapter);
+// Set<RoleModel> roles = thor.getRoleMappings();
+// System.out.println("num roles " + roles.size());
+// Assert.assertTrue(roles.size() > 1);
+// role = realm.getRole("foo-role");
+// Assert.assertTrue(thor.hasRole(role));
+
+// Set<GroupModel> groups = thor.getGroups();
+// boolean foundGroup = false;
+// for (GroupModel g : groups) {
+// if (g.getName().equals("my-group")) foundGroup = true;
+
+// }
+// Assert.assertTrue(foundGroup);
+// System.out.println("num groups " + groups.size());
+// Assert.assertTrue(thor.getRequiredActions().iterator().next().equals("POOP"));
+// thor.removeRequiredAction("POOP");
+// session.userCredentialManager().updateCredential(realm, thor, UserCredentialModel.password("lightning"));
+// keycloakRule.stopSession(session, true);
+// loginSuccessAndLogout("thor", "lightning");
+
+// // test removal of provider
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+// realm.removeComponent(writableProvider);
+// keycloakRule.stopSession(session, true);
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+// createUserPropModel(realm);
+// keycloakRule.stopSession(session, true);
+
+// loginSuccessAndLogout("thor", "hammer");
+
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+
+// thor = session.users().getUserByUsername("thor", realm);
+// Assert.assertNull(thor.getFirstName());
+// Assert.assertNull(thor.getLastName());
+// Assert.assertNull(thor.getEmail());
+// Assert.assertNull(thor.getFirstAttribute("test-attribute"));
+// Assert.assertFalse(thor.isEmailVerified());
+// role = realm.getRole("foo-role");
+// Assert.assertFalse(thor.hasRole(role));
+
+// groups = thor.getGroups();
+// foundGroup = false;
+// for (GroupModel g : groups) {
+// if (g.getName().equals("my-group")) foundGroup = true;
+
+// }
+// Assert.assertFalse(foundGroup);
+
+
+// }
+
+// @Test
+// public void testQuery() {
+// KeycloakSession session = keycloakRule.startSession();
+// RealmModel realm = session.realms().getRealmByName("test");
+
+// // Test paging
+// List<UserModel> localUsers = session.userLocalStorage().getUsers(realm, false);
+// Set<UserModel> queried = new HashSet<>();
+// // tests assumes that local storage is queried first
+// int first = localUsers.size();
+// while (queried.size() < 8) {
+// List<UserModel> results = session.users().getUsers(realm, first, 3);
+// if (results.size() == 0) break;
+// first += results.size();
+// queried.addAll(results);
+
+// }
+// Set<String> usernames = new HashSet<>();
+// for (UserModel user : queried) {
+// usernames.add(user.getUsername());
+// System.out.println(user.getUsername());
+
+// }
+// Assert.assertEquals(8, queried.size());
+// Assert.assertTrue(usernames.contains("thor"));
+// Assert.assertTrue(usernames.contains("zeus"));
+// Assert.assertTrue(usernames.contains("apollo"));
+// Assert.assertTrue(usernames.contains("perseus"));
+// Assert.assertTrue(usernames.contains("tbrady"));
+// Assert.assertTrue(usernames.contains("rob"));
+// Assert.assertTrue(usernames.contains("jules"));
+// Assert.assertTrue(usernames.contains("danny"));
+
+// // test searchForUser
+// List<UserModel> users = session.users().searchForUser("tbrady", realm);
+// Assert.assertTrue(users.size() == 1);
+// Assert.assertTrue(users.get(0).getUsername().equals("tbrady"));
+
+// // test getGroupMembers()
+// GroupModel gods = realm.createGroup("gods");
+// UserModel user = null;
+// user = session.users().getUserByUsername("apollo", realm);
+// user.joinGroup(gods);
+// user = session.users().getUserByUsername("zeus", realm);
+// user.joinGroup(gods);
+// user = session.users().getUserByUsername("thor", realm);
+// user.joinGroup(gods);
+// queried.clear();
+// usernames.clear();
+
+// first = 0;
+// while (queried.size() < 8) {
+// List<UserModel> results = session.users().getGroupMembers(realm, gods, first, 1);
+// if (results.size() == 0) break;
+// first += results.size();
+// queried.addAll(results);
+
+// }
+// for (UserModel u : queried) {
+// usernames.add(u.getUsername());
+// System.out.println(u.getUsername());
+
+// }
+// Assert.assertEquals(3, queried.size());
+// Assert.assertTrue(usernames.contains("apollo"));
+// Assert.assertTrue(usernames.contains("zeus"));
+// Assert.assertTrue(usernames.contains("thor"));
+
+// // search by single attribute
+// System.out.println("search by single attribute");
+// user = session.users().getUserByUsername("thor", realm);
+// user.setSingleAttribute("weapon", "hammer");
+
+// users = session.users().searchForUserByUserAttribute("weapon", "hammer", realm);
+// for (UserModel u : users) {
+// System.out.println(u.getUsername());
+
+// }
+// Assert.assertEquals(1, users.size());
+// Assert.assertEquals("thor", users.get(0).getUsername());
+
+
+// keycloakRule.stopSession(session, true);
+// }
+
+// @Test
+// public void testRegistration() {
+// KeycloakSession session = keycloakRule.startSession();
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().addUser(realm, "memuser");
+// session.userCredentialManager().updateCredential(realm, user, UserCredentialModel.password("password"));
+// keycloakRule.stopSession(session, true);
+// loginSuccessAndLogout("memuser", "password");
+// loginSuccessAndLogout("memuser", "password");
+// loginSuccessAndLogout("memuser", "password");
+
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+// user = session.users().getUserByUsername("memuser", realm);
+// Assert.assertEquals(memoryProvider.getId(), StorageId.resolveProviderId(user));
+// session.users().removeUser(realm, user);
+// Assert.assertNull(session.users().getUserByUsername("memuser", realm));
+// keycloakRule.stopSession(session, true);
+
+// }
+
+// @Test
+// public void testLifecycle() {
+// UserMapStorage.allocations.set(0);
+// UserMapStorage.closings.set(0);
+// KeycloakSession session = keycloakRule.startSession();
+// RealmModel realm = session.realms().getRealmByName("test");
+// UserModel user = session.users().addUser(realm, "memuser");
+// Assert.assertNotNull(user);
+// user = session.users().getUserByUsername("nonexistent", realm);
+// Assert.assertNull(user);
+// keycloakRule.stopSession(session, true);
+// Assert.assertEquals(1, UserMapStorage.allocations.get());
+// Assert.assertEquals(1, UserMapStorage.closings.get());
+
+// session = keycloakRule.startSession();
+// realm = session.realms().getRealmByName("test");
+// user = session.users().getUserByUsername("memuser", realm);
+// session.users().removeUser(realm, user);
+// Assert.assertNull(session.users().getUserByUsername("memuser", realm));
+// keycloakRule.stopSession(session, true);
+
+// }
+
+// }