Java Code Examples for org.keycloak.models.KeycloakSession#close()

The following examples show how to use org.keycloak.models.KeycloakSession#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EmbeddedKeycloakApplication.java    From spring-security-oauth with MIT License 6 votes vote down vote up
private void createBaeldungRealm() {
	KeycloakSession session = getSessionFactory().create();

	try {
		session.getTransactionManager().begin();

		RealmManager manager = new RealmManager(session);
		Resource lessonRealmImportFile = new ClassPathResource(keycloakServerProperties.getRealmImportFile());

		manager.importRealm(
				JsonSerialization.readValue(lessonRealmImportFile.getInputStream(), RealmRepresentation.class));

		session.getTransactionManager().commit();
	} catch (Exception ex) {
		LOG.warn("Failed to import Realm json file: {}", ex.getMessage());
		session.getTransactionManager().rollback();
	}

	session.close();
}
 
Example 2
Source File: EmbeddedKeycloakApplication.java    From spring-security-oauth with MIT License 6 votes vote down vote up
private void createMasterRealmAdminUser() {

        KeycloakSession session = getSessionFactory().create();

        ApplianceBootstrap applianceBootstrap = new ApplianceBootstrap(session);

        AdminUser admin = keycloakServerProperties.getAdminUser();

        try {
            session.getTransactionManager()
                .begin();
            applianceBootstrap.createMasterRealmUser(admin.getUsername(), admin.getPassword());
            session.getTransactionManager()
                .commit();
        } catch (Exception ex) {
            LOG.warn("Couldn't create keycloak master admin user: {}", ex.getMessage());
            session.getTransactionManager()
                .rollback();
        }

        session.close();
    }
 
Example 3
Source File: EmbeddedKeycloakApplication.java    From spring-security-oauth with MIT License 6 votes vote down vote up
private void createBaeldungRealm() {
    KeycloakSession session = getSessionFactory().create();

    try {
        session.getTransactionManager()
            .begin();

        RealmManager manager = new RealmManager(session);
        Resource lessonRealmImportFile = new ClassPathResource(keycloakServerProperties.getRealmImportFile());

        manager.importRealm(JsonSerialization.readValue(lessonRealmImportFile.getInputStream(), RealmRepresentation.class));

        session.getTransactionManager()
            .commit();
    } catch (Exception ex) {
        LOG.warn("Failed to import Realm json file: {}", ex.getMessage());
        session.getTransactionManager()
            .rollback();
    }

    session.close();
}
 
Example 4
Source File: EmbeddedKeycloakApplication.java    From spring-security-oauth with MIT License 6 votes vote down vote up
private void createMasterRealmAdminUser() {

		KeycloakSession session = getSessionFactory().create();

		ApplianceBootstrap applianceBootstrap = new ApplianceBootstrap(session);

		AdminUser admin = keycloakServerProperties.getAdminUser();

		try {
			session.getTransactionManager().begin();
			applianceBootstrap.createMasterRealmUser(admin.getUsername(), admin.getPassword());
			session.getTransactionManager().commit();
		} catch (Exception ex) {
			LOG.warn("Couldn't create keycloak master admin user: {}", ex.getMessage());
			session.getTransactionManager().rollback();
		}

		session.close();
	}
 
Example 5
Source File: EmbeddedKeycloakApplication.java    From spring-security-oauth with MIT License 6 votes vote down vote up
private void createBaeldungRealm() {
	KeycloakSession session = getSessionFactory().create();

	try {
		session.getTransactionManager().begin();

		RealmManager manager = new RealmManager(session);
		Resource lessonRealmImportFile = new ClassPathResource(keycloakServerProperties.getRealmImportFile());

		manager.importRealm(
				JsonSerialization.readValue(lessonRealmImportFile.getInputStream(), RealmRepresentation.class));

		session.getTransactionManager().commit();
	} catch (Exception ex) {
		LOG.warn("Failed to import Realm json file: {}", ex.getMessage());
		session.getTransactionManager().rollback();
	}

	session.close();
}
 
Example 6
Source File: EmbeddedKeycloakApplication.java    From spring-boot-keycloak-server-example with Apache License 2.0 6 votes vote down vote up
private void tryCreateMasterRealmAdminUser() {

        KeycloakSession session = getSessionFactory().create();

        ApplianceBootstrap applianceBootstrap = new ApplianceBootstrap(session);

        AdminUser admin = customProperties.getAdminUser();

        try {
            session.getTransactionManager().begin();
            applianceBootstrap.createMasterRealmUser(admin.getUsername(), admin.getPassword());
            session.getTransactionManager().commit();
        } catch (Exception ex) {
            LOG.warn("Couldn't create keycloak master admin user: {}", ex.getMessage());
            session.getTransactionManager().rollback();
        }

        session.close();
    }
 
Example 7
Source File: EmbeddedKeycloakApplication.java    From spring-security-oauth with MIT License 6 votes vote down vote up
private void createMasterRealmAdminUser() {

		KeycloakSession session = getSessionFactory().create();

		ApplianceBootstrap applianceBootstrap = new ApplianceBootstrap(session);

		AdminUser admin = keycloakServerProperties.getAdminUser();

		try {
			session.getTransactionManager().begin();
			applianceBootstrap.createMasterRealmUser(admin.getUsername(), admin.getPassword());
			session.getTransactionManager().commit();
		} catch (Exception ex) {
			LOG.warn("Couldn't create keycloak master admin user: {}", ex.getMessage());
			session.getTransactionManager().rollback();
		}

		session.close();
	}
 
Example 8
Source File: KeycloakModelUtils.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Wrap given runnable job into KeycloakTransaction.
 *
 * @param factory
 * @param task
 */
public static void runJobInTransaction(KeycloakSessionFactory factory, KeycloakSessionTask task) {
    KeycloakSession session = factory.create();
    KeycloakTransaction tx = session.getTransactionManager();
    try {
        tx.begin();
        task.run(session);

        if (tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            } else {
                tx.commit();
            }
        }
    } catch (RuntimeException re) {
        if (tx.isActive()) {
            tx.rollback();
        }
        throw re;
    } finally {
        session.close();
    }
}
 
Example 9
Source File: QuarkusLifecycleObserver.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void createAdminUser() {
    String adminUserName = System.getenv(KEYCLOAK_ADMIN_ENV_VAR);
    String adminPassword = System.getenv(KEYCLOAK_ADMIN_PASSWORD_ENV_VAR);

    if ((adminUserName == null || adminUserName.trim().length() == 0)
            || (adminPassword == null || adminPassword.trim().length() == 0)) {
        return;
    }

    KeycloakSessionFactory sessionFactory = application.getSessionFactory();
    KeycloakSession session = sessionFactory.create();
    KeycloakTransactionManager transaction = session.getTransactionManager();

    try {
        transaction.begin();

        new ApplianceBootstrap(session).createMasterRealmUser(adminUserName, adminPassword);
        ServicesLogger.LOGGER.addUserSuccess(adminUserName, Config.getAdminRealm());

        transaction.commit();
    } catch (IllegalStateException e) {
        session.getTransactionManager().rollback();
        ServicesLogger.LOGGER.addUserFailedUserExists(adminUserName, Config.getAdminRealm());
    } catch (Throwable t) {
        session.getTransactionManager().rollback();
        ServicesLogger.LOGGER.addUserFailed(t, adminUserName, Config.getAdminRealm());
    } finally {
        session.close();
    }
}
 
Example 10
Source File: QuarkusJpaConnectionProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void importRealm(RealmRepresentation rep, String from) {
    KeycloakSession session = factory.create();
    boolean exists = false;
    try {
        session.getTransactionManager().begin();

        try {
            RealmManager manager = new RealmManager(session);

            if (rep.getId() != null && manager.getRealm(rep.getId()) != null) {
                ServicesLogger.LOGGER.realmExists(rep.getRealm(), from);
                exists = true;
            }

            if (manager.getRealmByName(rep.getRealm()) != null) {
                ServicesLogger.LOGGER.realmExists(rep.getRealm(), from);
                exists = true;
            }
            if (!exists) {
                RealmModel realm = manager.importRealm(rep);
                ServicesLogger.LOGGER.importedRealm(realm.getName(), from);
            }
            session.getTransactionManager().commit();
        } catch (Throwable t) {
            session.getTransactionManager().rollback();
            if (!exists) {
                ServicesLogger.LOGGER.unableToImportRealm(t, rep.getRealm(), from);
            }
        }
    } finally {
        session.close();
    }
}
 
Example 11
Source File: KeycloakSessionServletFilter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void closeSession(KeycloakSession session) {
    // KeycloakTransactionCommitter is responsible for committing the transaction, but if an exception is thrown it's not invoked and transaction
    // should be rolled back
    if (session.getTransactionManager() != null && session.getTransactionManager().isActive()) {
        session.getTransactionManager().rollback();
    }

    session.close();
    Resteasy.clearContextData();
}
 
Example 12
Source File: KeycloakApplication.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void importRealm(RealmRepresentation rep, String from) {
    KeycloakSession session = sessionFactory.create();
    boolean exists = false;
    try {
        session.getTransactionManager().begin();

        try {
            RealmManager manager = new RealmManager(session);

            if (rep.getId() != null && manager.getRealm(rep.getId()) != null) {
                ServicesLogger.LOGGER.realmExists(rep.getRealm(), from);
                exists = true;
            }

            if (manager.getRealmByName(rep.getRealm()) != null) {
                ServicesLogger.LOGGER.realmExists(rep.getRealm(), from);
                exists = true;
            }
            if (!exists) {
                RealmModel realm = manager.importRealm(rep);
                ServicesLogger.LOGGER.importedRealm(realm.getName(), from);
            }
            session.getTransactionManager().commit();
        } catch (Throwable t) {
            session.getTransactionManager().rollback();
            if (!exists) {
                ServicesLogger.LOGGER.unableToImportRealm(t, rep.getRealm(), from);
            }
        }
    } finally {
        session.close();
    }
}
 
Example 13
Source File: KeycloakApplication.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static void setupScheduledTasks(final KeycloakSessionFactory sessionFactory) {
    long interval = Config.scope("scheduled").getLong("interval", 900L) * 1000;

    KeycloakSession session = sessionFactory.create();
    try {
        TimerProvider timer = session.getProvider(TimerProvider.class);
        timer.schedule(new ClusterAwareScheduledTaskRunner(sessionFactory, new ClearExpiredEvents(), interval), interval, "ClearExpiredEvents");
        timer.schedule(new ClusterAwareScheduledTaskRunner(sessionFactory, new ClearExpiredClientInitialAccessTokens(), interval), interval, "ClearExpiredClientInitialAccessTokens");
        timer.schedule(new ScheduledTaskRunner(sessionFactory, new ClearExpiredUserSessions()), interval, ClearExpiredUserSessions.TASK_NAME);
        new UserStorageSyncManager().bootstrapPeriodic(sessionFactory, timer);
    } finally {
        session.close();
    }
}
 
Example 14
Source File: KeycloakApplication.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void migrateModel() {
    KeycloakSession session = sessionFactory.create();
    try {
        session.getTransactionManager().begin();
        MigrationModelManager.migrate(session);
        session.getTransactionManager().commit();
    } catch (Exception e) {
        session.getTransactionManager().rollback();
        throw e;
    } finally {
        session.close();
    }
}
 
Example 15
Source File: KeycloakSessionServletFilter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void closeSession(KeycloakSession session) {
    // KeycloakTransactionCommitter is responsible for committing the transaction, but if an exception is thrown it's not invoked and transaction
    // should be rolled back
    if (session.getTransactionManager() != null && session.getTransactionManager().isActive()) {
        session.getTransactionManager().rollback();
    }

    session.close();
    Resteasy.clearContextData();
}
 
Example 16
Source File: KeycloakServer.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void setupDevConfig() {
    if (System.getProperty("keycloak.createAdminUser", "true").equals("true")) {
        KeycloakSession session = sessionFactory.create();
        try {
            session.getTransactionManager().begin();
            if (new ApplianceBootstrap(session).isNoMasterUser()) {
                new ApplianceBootstrap(session).createMasterRealmUser("admin", "admin");
                log.info("Created master user with credentials admin:admin");
            }
            session.getTransactionManager().commit();
        } finally {
            session.close();
        }
    }
}
 
Example 17
Source File: QuarkusFilter.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException {
    //End the session and clear context
    KeycloakSession session = Resteasy.getContextData(KeycloakSession.class);

    // KeycloakTransactionCommitter is responsible for committing the transaction, but if an exception is thrown it's not invoked and transaction
    // should be rolled back
    if (session.getTransactionManager() != null && session.getTransactionManager().isActive()) {
        session.getTransactionManager().rollback();
    }

    session.close();
    Resteasy.clearContextData();
}
 
Example 18
Source File: KeycloakOnUndertow.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void setupDevConfig() {
    KeycloakSession session = sessionFactory.create();
    try {
        session.getTransactionManager().begin();
        if (new ApplianceBootstrap(session).isNoMasterUser()) {
            new ApplianceBootstrap(session).createMasterRealmUser("admin", "admin");
        }
        session.getTransactionManager().commit();
    } finally {
        session.close();
    }
}
 
Example 19
Source File: EmbeddedKeycloakApplication.java    From spring-boot-keycloak-server-example with Apache License 2.0 5 votes vote down vote up
private void tryImportRealm() {

        KeycloakCustomProperties.Migration imex = customProperties.getMigration();
        Resource importLocation = imex.getImportLocation();

        if (!importLocation.exists()) {
            LOG.info("Could not find keycloak import file %s", importLocation);
            return;
        }

        File file;
        try {
            file = importLocation.getFile();
        } catch (IOException e) {
            LOG.error("Could not read keycloak import file %s", importLocation, e);
            return;
        }

        LOG.info("Starting Keycloak realm configuration import from location: %s", importLocation);

        KeycloakSession session = getSessionFactory().create();

        ExportImportConfig.setAction("import");
        ExportImportConfig.setProvider(imex.getImportProvider());
        ExportImportConfig.setFile(file.getAbsolutePath());

        ExportImportManager manager = new ExportImportManager(session);
        manager.runImport();

        session.close();

        LOG.info("Keycloak realm configuration import finished.");
    }
 
Example 20
Source File: KeycloakApplication.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected ExportImportManager migrateAndBootstrap() {
    ExportImportManager exportImportManager;
    logger.debug("Calling migrateModel");
    migrateModel();

    logger.debug("bootstrap");
    KeycloakSession session = sessionFactory.create();
    try {
        session.getTransactionManager().begin();
        JtaTransactionManagerLookup lookup = (JtaTransactionManagerLookup) sessionFactory.getProviderFactory(JtaTransactionManagerLookup.class);
        if (lookup != null) {
            if (lookup.getTransactionManager() != null) {
                try {
                    Transaction transaction = lookup.getTransactionManager().getTransaction();
                    logger.debugv("bootstrap current transaction? {0}", transaction != null);
                    if (transaction != null) {
                        logger.debugv("bootstrap current transaction status? {0}", transaction.getStatus());
                    }
                } catch (SystemException e) {
                    throw new RuntimeException(e);
                }
            }
        }


        ApplianceBootstrap applianceBootstrap = new ApplianceBootstrap(session);
        exportImportManager = new ExportImportManager(session);

        boolean createMasterRealm = applianceBootstrap.isNewInstall();
        if (exportImportManager.isRunImport() && exportImportManager.isImportMasterIncluded()) {
            createMasterRealm = false;
        }

        if (createMasterRealm) {
            applianceBootstrap.createMasterRealm();
        }
        session.getTransactionManager().commit();
    } catch (RuntimeException re) {
        if (session.getTransactionManager().isActive()) {
            session.getTransactionManager().rollback();
        }
        throw re;
    } finally {
        session.close();
    }

    if (exportImportManager.isRunImport()) {
        exportImportManager.runImport();
    } else {
        importRealms();
    }

    importAddUser();

    return exportImportManager;
}