KEYCLOAK-2235 Fix transaction leaks

This commit is contained in:
mposolda 2016-02-01 18:13:15 +01:00
parent 77a7b5a130
commit 732256eceb
2 changed files with 34 additions and 28 deletions

View file

@ -1,6 +1,7 @@
package org.keycloak.models;
import org.jboss.logging.Logger;
import org.keycloak.models.utils.KeycloakModelUtils;
import java.util.ArrayList;
import java.util.Arrays;
@ -104,19 +105,19 @@ public class UserFederationManager implements UserProvider {
}
protected void deleteInvalidUser(RealmModel realm, UserModel user) {
KeycloakSession tx = session.getKeycloakSessionFactory().create();
try {
tx.getTransaction().begin();
RealmModel realmModel = tx.realms().getRealm(realm.getId());
protected void deleteInvalidUser(final RealmModel realm, final UserModel user) {
KeycloakModelUtils.runJobInTransaction(session.getKeycloakSessionFactory(), new KeycloakSessionTask() {
@Override
public void run(KeycloakSession session) {
RealmModel realmModel = session.realms().getRealm(realm.getId());
if (realmModel == null) return;
UserModel deletedUser = tx.userStorage().getUserById(user.getId(), realmModel);
tx.userStorage().removeUser(realmModel, deletedUser);
UserModel deletedUser = session.userStorage().getUserById(user.getId(), realmModel);
session.userStorage().removeUser(realmModel, deletedUser);
logger.debugf("Removed invalid user '%s'", user.getUsername());
tx.getTransaction().commit();
} finally {
tx.close();
}
});
}

View file

@ -258,29 +258,34 @@ public class KeycloakApplication extends Application {
public void importRealm(RealmRepresentation rep, String from) {
KeycloakSession session = sessionFactory.create();
boolean exists = false;
try {
session.getTransaction().begin();
try {
RealmManager manager = new RealmManager(session);
manager.setContextPath(getContextPath());
if (rep.getId() != null && manager.getRealm(rep.getId()) != null) {
logger.realmExists(rep.getRealm(), from);
return;
exists = true;
}
if (manager.getRealmByName(rep.getRealm()) != null) {
logger.realmExists(rep.getRealm(), from);
return;
exists = true;
}
try {
if (!exists) {
RealmModel realm = manager.importRealm(rep);
session.getTransaction().commit();
logger.importedRealm(realm.getName(), from);
}
session.getTransaction().commit();
} catch (Throwable t) {
session.getTransaction().rollback();
if (!exists) {
logger.unableToImportRealm(t, rep.getRealm(), from);
}
}
} finally {
session.close();
}