8000 Added ModelIllegalStateException to handle lazy loading exception. by ahus1 · Pull Request #9761 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* Copyright 2022. 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.map.storage.jpa;

import org.keycloak.models.ModelIllegalStateException;
import org.keycloak.models.map.common.AbstractEntity;

/**
* Base class for all delegate providers for the JPA storage.
*
* Wraps the delegate so that it can be safely updated during lazy loading.
*/
public abstract class JpaDelegateProvider<T extends JpaRootEntity & AbstractEntity> {
private T delegate;

protected JpaDelegateProvider(T delegate) {
this.delegate = delegate;
}

protected T getDelegate() {
return delegate;
}

/**
* Validates the new entity.
*
* Will throw {@link ModelIllegalStateException} if the entity has been deleted or changed in the meantime.
*/
protected void setDelegate(T newDelegate) {
if (newDelegate == null) {
throw new ModelIllegalStateException("Unable to retrieve entity: " + delegate.getClass().getName() + "#" + delegate.getId());
}
if (newDelegate.getVersion() != delegate.getVersion()) {
throw new ModelIllegalStateException("Version of entity changed between two loads: " + delegate.getClass().getName() + "#" + delegate.getId());
}
this.delegate = newDelegate;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
* Copyright 2022 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.map.storage.jpa;

/**
* Interface for all root entities in the JPA storage.
*/
public interface JpaRootEntity {

/**
* Version of the JPA entity used for optimistic locking
*/
int getVersion();
Comment thread
ahus1 marked this conversation as resolved.
Resolved
}
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,9 @@ public Stream<MapClientEntity> read(QueryParameters<ClientModel> queryParameters
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<JpaClientEntity> query = cb.createQuery(JpaClientEntity.class);
Root<JpaClientEntity> root = query.from(JpaClientEntity.class);
query.select(cb.construct(JpaClientEntity.class,
root.get("id"),
query.select(cb.construct(JpaClientEntity.class,
root.get("id"),
root.get("version"),
root.get("entityVersion"),
root.get("realmId"),
root.get("clientId"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,21 +28,21 @@
import org.keycloak.models.map.client.MapClientEntityFields;
import org.keycloak.models.map.common.EntityField;
import org.keycloak.models.map.common.delegate.DelegateProvider;
import org.keycloak.models.map.storage.jpa.JpaDelegateProvider;
import org.keycloak.models.map.storage.jpa.client.entity.JpaClientEntity;

public class JpaClientDelegateProvider implements DelegateProvider<MapClientEntity> {
public class JpaClientDelegateProvider extends JpaDelegateProvider<JpaClientEntity> implements DelegateProvider<MapClientEntity> {

private JpaClientEntity delegate;
private final EntityManager em;

public JpaClientDelegateProvider(JpaClientEntity delegate, EntityManager em) {
this.delegate = delegate;
super(delegate);
this.em = em;
}

@Override
public MapClientEntity getDelegate(boolean isRead, Enum<? extends EntityField<MapClientEntity>> field, Object... parameters) {
if (delegate.isMetadataInitialized()) return delegate;
if (getDelegate().isMetadataInitialized()) return getDelegate();
if (isRead) {
if (field instanceof MapClientEntityFields) {
switch ((MapClientEntityFields) field) {
Expand All @@ -51,26 +51,26 @@ public MapClientEntity getDelegate(boolean isRead, Enum<? extends EntityField<Ma
case CLIENT_ID:
case PROTOCOL:
case ENABLED:
return delegate;
return getDelegate();

case ATTRIBUTES:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<JpaClientEntity> query = cb.createQuery(JpaClientEntity.class);
Root<JpaClientEntity> root = query.from(JpaClientEntity.class);
root.fetch("attributes", JoinType.INNER);
query.select(root).where(cb.equal(root.get("id"), UUID.fromString(delegate.getId())));
query.select(root).where(cb.equal(root.get("id"), UUID.fromString(getDelegate().getId())));

delegate = em.createQuery(query).getSingleResult();
setDelegate(em.createQuery(query).getSingleResult());
break;

default:
delegate = em.find(JpaClientEntity.class, UUID.fromString(delegate.getId()));
setDelegate(em.find(JpaClientEntity.class, UUID.fromString(getDelegate().getId())));
}
} else throw new IllegalStateException("Not a valid client field: " + field);
} else {
delegate = em.find(JpaClientEntity.class, UUID.fromString(delegate.getId()));
setDelegate(em.find(JpaClientEntity.class, UUID.fromString(getDelegate().getId())));
}
return delegate;
return getDelegate();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@
import org.keycloak.models.map.client.MapProtocolMapperEntity;
import org.keycloak.models.map.common.DeepCloner;
import static org.keycloak.models.map.storage.jpa.Constants.SUPPORTED_VERSION_CLIENT;

import org.keycloak.models.map.storage.jpa.JpaRootEntity;
import org.keycloak.models.map.storage.jpa.hibernate.jsonb.JsonbType;

/**
Expand All @@ -60,7 +62,7 @@
)
})
@TypeDefs({@TypeDef(name = "jsonb", typeClass = JsonbType.class)})
public class JpaClientEntity extends AbstractClientEntity implements Serializable {
public class JpaClientEntity extends AbstractClientEntity implements Serializable, JpaRootEntity {

@Id
@Column
Expand Down Expand Up @@ -113,9 +115,10 @@ public JpaClientEntity(DeepCloner cloner) {
* Used by hibernate when calling cb.construct from read(QueryParameters) method.
* It is used to select client without metadata(json) field.
*/
public JpaClientEntity(UUID id, Integer entityVersion, String realmId, String clientId,
public JpaClientEntity(UUID id, int version, Integer entityVersion, String realmId, String clientId,
String protocol, Boolean enabled) {
this.id = id;
this.version = version;
this.entityVersion = entityVersion;
this.realmId = realmId;
this.clientId = clientId;
Expand Down Expand Up @@ -148,6 +151,7 @@ public void setEntityVersion(Integer entityVersion) {
metadata.setEntityVersion(entityVersion);
}

@Override
public int getVersion() {
return version;
}
Expand Down
Original file line number Diff line number Diff line change Expand Up @@ -75,7 +75,8 @@ public Stream<MapRoleEntity> read(QueryParameters<RoleModel> queryParameters) { CriteriaQuery<JpaRoleEntity> query = cb.createQuery(JpaRoleEntity.class); Root<JpaRoleEntity> root = query.from(JpaRoleEntity.class); query.select(cb.construct(JpaRoleEntity.class, root.get("id"), root.get("id"), root.get("version"), root.get("entityVersion"), root.get("realmId"), root.get("clientId"), Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,21 +26,21 @@
import org.keycloak.models.map.common.delegate.DelegateProvider;
import org.keycloak.models.map.role.MapRoleEntity;
import org.keycloak.models.map.role.MapRoleEntityFields;
import org.keycloak.models.map.storage.jpa.JpaDelegateProvider;
import org.keycloak.models.map.storage.jpa.role.entity.JpaRoleEntity;

public class JpaRoleDelegateProvider implements DelegateProvider<MapRoleEntity> {
public class JpaRoleDelegateProvider extends JpaDelegateProvider<JpaRoleEntity> implements DelegateProvider<MapRoleEntity> {

private JpaRoleEntity delegate;
private final EntityManager em;

public JpaRoleDelegateProvider(JpaRoleEntity delegate, EntityManager em) {
this.delegate = delegate;
super(delegate);
this.em = em;
}

@Override
public JpaRoleEntity getDelegate(boolean isRead, Enum<? extends EntityField<MapRoleEntity>> field, Object... parameters) {
if (delegate.isMetadataInitialized()) return delegate;
if (getDelegate().isMetadataInitialized()) return getDelegate();
if (isRead) {
if (field instanceof MapRoleEntityFields) {
switch ((MapRoleEntityFields) field) {
Expand All @@ -49,26 +49,26 @@ public JpaRoleEntity getDelegate(boolean isRead, Enum<? extends EntityField<MapR
case CLIENT_ID:
case NAME:
case DESCRIPTION:
return delegate;
return getDelegate();

case ATTRIBUTES:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<JpaRoleEntity> query = cb.createQuery(JpaRoleEntity.class);
Root<JpaRoleEntity> root = query.from(JpaRoleEntity.class);
root.fetch("attributes", JoinType.INNER);
query.select(root).where(cb.equal(root.get("id"), UUID.fromString(delegate.getId())));
query.select(root).where(cb.equal(root.get("id"), UUID.fromString(getDelegate().getId())));

delegate = em.createQuery(query).getSingleResult();
setDelegate(em.createQuery(query).getSingleResult());
break;

default:
delegate = em.find(JpaRoleEntity.class, UUID.fromString(delegate.getId()));
setDelegate(em.find(JpaRoleEntity.class, UUID.fromString(getDelegate().getId())));
}
} else throw new IllegalStateException("Not a valid role field: " + field);
} else {
delegate = em.find(JpaRoleEntity.class, UUID.fromString(delegate.getId()));
setDelegate(em.find(JpaRoleEntity.class, UUID.fromString(getDelegate().getId())));
}
return delegate;
return getDelegate();
}

}
10BC8
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@
import org.keycloak.models.map.common.DeepCloner;
import org.keycloak.models.map.role.MapRoleEntity.AbstractRoleEntity;
import static org.keycloak.models.map.storage.jpa.Constants.SUPPORTED_VERSION_ROLE;

import org.keycloak.models.map.storage.jpa.JpaRootEntity;
import org.keycloak.models.map.storage.jpa.hibernate.jsonb.JsonbType;

/**
Expand All @@ -53,7 +55,7 @@
@Entity
@Table(name = "role", uniqueConstraints = {@UniqueConstraint(columnNames = {"realmId", "clientId", "name"})})
@TypeDefs({@TypeDef(name = "jsonb", typeClass = JsonbType.class)})
public class JpaRoleEntity extends AbstractRoleEntity implements Serializable {
public class JpaRoleEntity extends AbstractRoleEntity implements Serializable, JpaRootEntity {

@Id
@Column
Expand Down Expand Up @@ -106,8 +108,9 @@ public JpaRoleEntity(DeepCloner cloner) {
* Used by hibernate when calling cb.construct from read(QueryParameters) method.
* It is used to select role without metadata(json) field.
*/
public JpaRoleEntity(UUID id, Integer entityVersion, String realmId, String clientId, String name, String description) {
public JpaRoleEntity(UUID id, int version, Integer entityVersion, String realmId, String clientId, String name, String description) {
this.id = id;
this.version = version;
this.entityVersion = entityVersion;
this.realmId = realmId;
this.clientId = clientId;
Expand Down Expand Up @@ -140,6 +143,7 @@ public void setEntityVersion(Integer entityVersion) {
metadata.setEntityVersion(entityVersion);
}

@Override
public int getVersion() {
return version;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import org.keycloak.models.ClientModel;
import org.keycloak.models.ClientScopeModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.ModelIllegalStateException;
import org.keycloak.models.ProtocolMapperModel;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
Expand Down Expand Up @@ -83,7 +84,7 @@ private ClientModel getDelegate() {
}
ClientModel ref = delegate.getReference();
if (ref == null) {
throw new IllegalStateException("Invalid delegate obtained");
throw new ModelIllegalStateException("Invalid delegate obtained");
}
return ref;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

package org.keycloak.models.utils;

import org.jboss.logging.Logger;
import org.keycloak.authorization.AuthorizationProvider;
import org.keycloak.authorization.model.PermissionTicket;
import org.keycloak.authorization.model.Policy;
Expand Down Expand Up @@ -46,8 +47,10 @@
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

Expand Down Expand Up @@ -101,6 +104,7 @@ public class ModelToRepresentation {
REALM_EXCLUDED_ATTRIBUTES.add(Constants.CLIENT_PROFILES);
}

private static final Logger LOG = Logger.getLogger(ModelToRepresentation.class);

public static void buildGroupPath(StringBuilder sb, GroupModel group) {
if (group.getParent() != null) {
Expand Down Expand Up @@ -554,6 +558,25 @@ public static RealmEventsConfigRepresentation toEventsConfigReprensetation(Realm
return rep;
}

/**
* Handles exceptions that occur when transforming the model to a representation and will remove
* all null objects from the stream.
*
* Entities that have been removed from the store or where a lazy loading exception occurs will not show up
* in the output stream.
*/
public static <M, R> Stream<R> filterValidRepresentations(Stream<M> models, Function<M, R> transformer) {
return models.map(m -> {
try {
return transformer.apply(m);
} catch (ModelIllegalStateException e) {
LOG.warn("unable to retrieve model information, skipping entity", e);
return null;
}
})
.filter(Objects::nonNull);
}

public static CredentialRepresentation toRepresentation(UserCredentialModel cred) {
CredentialRepresentation rep = new CredentialRepresentation();
rep.setType(CredentialRepresentation.SECRET);
Expand Down
Loading
0