Search in sources :

Example 11 with RowMapper

use of org.springframework.jdbc.core.RowMapper in project perun by CESNET.

the class RegistrarManagerImpl method approveApplicationInternal.

/**
	 * Process application approval in 1 transaction
	 * !! WITHOUT members validation !!
	 *
	 * @param sess session for authz
	 * @param appId application ID to approve
	 * @return updated application
	 * @throws PerunException
	 */
@Transactional(rollbackFor = Exception.class)
public Application approveApplicationInternal(PerunSession sess, int appId) throws PerunException {
    Application app = getApplicationById(appId);
    Member member = null;
    // authz
    if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, app.getVo())) {
        if (app.getGroup() != null) {
            if (!AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, app.getGroup())) {
                throw new PrivilegeException(sess, "approveApplication");
            }
        } else {
            throw new PrivilegeException(sess, "approveApplication");
        }
    }
    // only VERIFIED applications can be approved
    if (!AppState.VERIFIED.equals(app.getState())) {
        if (AppState.APPROVED.equals(app.getState()))
            throw new RegistrarException("Application is already approved. Try to refresh the view to see changes.");
        if (AppState.REJECTED.equals(app.getState()))
            throw new RegistrarException("Rejected application cant' be approved. Try to refresh the view to see changes.");
        throw new RegistrarException("User didn't verify his email address yet. Please wait until application will be in a 'Submitted' state. You can send mail verification notification to user again if you wish.");
    }
    // get registrar module
    RegistrarModule module;
    if (app.getGroup() != null) {
        module = getRegistrarModule(getFormForGroup(app.getGroup()));
    } else {
        module = getRegistrarModule(getFormForVo(app.getVo()));
    }
    if (module != null) {
        // call custom logic before approving
        module.beforeApprove(sess, app);
    }
    // mark as APPROVED
    int result = jdbc.update("update application set state=?, modified_by=?, modified_at=? where id=?", AppState.APPROVED.toString(), sess.getPerunPrincipal().getActor(), new Date(), appId);
    if (result == 0) {
        throw new RegistrarException("Application with ID=" + appId + " not found.");
    } else if (result > 1) {
        throw new ConsistencyErrorException("More than one application is stored under ID=" + appId + ".");
    }
    // set back as approved
    app.setState(AppState.APPROVED);
    log.info("Application {} marked as APPROVED", appId);
    // Try to get reservedLogin and reservedNamespace before deletion, it will be used for creating userExtSources
    List<Pair<String, String>> logins;
    try {
        logins = jdbc.query("select namespace,login from application_reserved_logins where app_id=?", new RowMapper<Pair<String, String>>() {

            @Override
            public Pair<String, String> mapRow(ResultSet rs, int arg1) throws SQLException {
                return new Pair<String, String>(rs.getString("namespace"), rs.getString("login"));
            }
        }, appId);
    } catch (EmptyResultDataAccessException e) {
        // set empty logins
        logins = new ArrayList<Pair<String, String>>();
    }
    // FOR INITIAL APPLICATION
    if (AppType.INITIAL.equals(app.getType())) {
        if (app.getGroup() != null) {
            // free reserved logins so they can be set as attributes
            jdbc.update("delete from application_reserved_logins where app_id=?", appId);
            if (app.getUser() == null) {
                // application for group doesn't have user set, but it can exists in perun (joined identities after submission)
                User u = usersManager.getUserByExtSourceNameAndExtLogin(registrarSession, app.getExtSourceName(), app.getCreatedBy());
                // put user back to application
                app.setUser(u);
                // store user_id in DB
                int result2 = jdbc.update("update application set user_id=? where id=?", u.getId(), appId);
                if (result2 == 0) {
                    throw new RegistrarException("Application with ID=" + appId + " not found.");
                } else if (result2 > 1) {
                    throw new ConsistencyErrorException("More than one application is stored under ID=" + appId + ".");
                }
            }
            // add new member of VO as member of group (for group applications)
            // !! MUST BE MEMBER OF VO !!
            member = membersManager.getMemberByUser(registrarSession, app.getVo(), app.getUser());
            // meaning, user should submit membership extension application first !!
            if (!Arrays.asList(Status.VALID, Status.INVALID).contains(member.getStatus())) {
                throw new CantBeApprovedException("Application of member with membership status: " + member.getStatus() + " can't be approved. Please wait until member extends/re-validate own membership in a VO.");
            }
            // store all attributes (but not logins)
            storeApplicationAttributes(app);
            // cancel reservation of new duplicate logins and get purely new logins back
            logins = unreserveNewLoginsFromSameNamespace(logins, app.getUser());
            // store purely new logins to user
            storeApplicationLoginAttributes(app);
            for (Pair<String, String> pair : logins) {
                // LOGIN IN NAMESPACE IS PURELY NEW => VALIDATE ENTRY IN KDC
                // left = namespace, right = login
                perun.getUsersManagerBl().validatePasswordAndSetExtSources(registrarSession, app.getUser(), pair.getRight(), pair.getLeft());
            }
            // update titles before/after users name if part of application !! USER MUST EXISTS !!
            updateUserNameTitles(app);
            perun.getGroupsManager().addMember(registrarSession, app.getGroup(), member);
            log.debug("[REGISTRAR] Member {} added to Group {}.", member, app.getGroup());
        } else {
            // put application data into Candidate
            final Map<String, String> attributes = new HashMap<String, String>();
            jdbc.query("select dst_attr,value from application_data d, application_form_items i where d.item_id=i.id " + "and i.dst_attr is not null and d.value is not null and app_id=?", new RowMapper<Object>() {

                @Override
                public Object mapRow(ResultSet rs, int i) throws SQLException {
                    attributes.put(rs.getString("dst_attr"), rs.getString("value"));
                    return null;
                }
            }, appId);
            // DO NOT STORE LOGINS THROUGH CANDIDATE
            // we do not set logins by candidate object to prevent accidental overwrite while joining identities in process
            Iterator<Map.Entry<String, String>> iter = attributes.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry<String, String> entry = iter.next();
                if (entry.getKey().contains("urn:perun:user:attribute-def:def:login-namespace:")) {
                    iter.remove();
                }
            }
            Candidate candidate = new Candidate();
            candidate.setAttributes(attributes);
            log.debug("[REGISTRAR] Retrieved candidate from DB {}", candidate);
            // first try to parse display_name if not null and not empty
            if (attributes.containsKey(URN_USER_DISPLAY_NAME) && attributes.get(URN_USER_DISPLAY_NAME) != null && !attributes.get(URN_USER_DISPLAY_NAME).isEmpty()) {
                // parse
                Map<String, String> commonName = Utils.parseCommonName(attributes.get(URN_USER_DISPLAY_NAME));
                if (commonName.get("titleBefore") != null && !commonName.get("titleBefore").isEmpty()) {
                    candidate.setTitleBefore(commonName.get("titleBefore"));
                }
                if (commonName.get("firstName") != null && !commonName.get("firstName").isEmpty()) {
                    candidate.setFirstName(commonName.get("firstName"));
                }
                // FIXME - ? there is no middleName in Utils.parseCommonName() implementation
                if (commonName.get("middleName") != null && !commonName.get("middleName").isEmpty()) {
                    candidate.setMiddleName(commonName.get("middleName"));
                }
                if (commonName.get("lastName") != null && !commonName.get("lastName").isEmpty()) {
                    candidate.setLastName(commonName.get("lastName"));
                }
                if (commonName.get("titleAfter") != null && !commonName.get("titleAfter").isEmpty()) {
                    candidate.setTitleAfter(commonName.get("titleAfter"));
                }
            }
            // if names are separated, used them after
            for (String attrName : attributes.keySet()) {
                // if value not null or empty - set to candidate
                if (attributes.get(attrName) != null && !attributes.get(attrName).isEmpty()) {
                    if (URN_USER_TITLE_BEFORE.equals(attrName)) {
                        candidate.setTitleBefore(attributes.get(attrName));
                    } else if (URN_USER_TITLE_AFTER.equals(attrName)) {
                        candidate.setTitleAfter(attributes.get(attrName));
                    } else if (URN_USER_FIRST_NAME.equals(attrName)) {
                        candidate.setFirstName(attributes.get(attrName));
                    } else if (URN_USER_LAST_NAME.equals(attrName)) {
                        candidate.setLastName(attributes.get(attrName));
                    } else if (URN_USER_MIDDLE_NAME.equals(attrName)) {
                        candidate.setMiddleName(attributes.get(attrName));
                    }
                }
            }
            // free reserved logins so they can be set as attributes
            jdbc.update("delete from application_reserved_logins where app_id=?", appId);
            // create member and user
            log.debug("[REGISTRAR] Trying to make member from candidate {}", candidate);
            member = membersManager.createMember(sess, app.getVo(), app.getExtSourceName(), app.getExtSourceType(), app.getExtSourceLoa(), app.getCreatedBy(), candidate);
            User u = usersManager.getUserById(registrarSession, member.getUserId());
            if (app.getUser() != null) {
                // if user was already known to perun, createMember() will set attributes
                // via setAttributes() method so core attributes are skipped
                // ==> updateNameTitles() in case of change in appForm.
                updateUserNameTitles(app);
            }
            // set NEW user id back to application
            app.setUser(u);
            result = jdbc.update("update application set user_id=? where id=?", member.getUserId(), appId);
            if (result == 0) {
                throw new RegistrarException("User ID hasn't been associated with the application " + appId + ", because the application was not found!");
            } else if (result > 1) {
                throw new ConsistencyErrorException("User ID hasn't been associated with the application " + appId + ", because more than one application exists under the same ID.");
            }
            log.info("Member " + member.getId() + " created for: " + app.getCreatedBy() + " / " + app.getExtSourceName());
            // unreserve new login if user already have login in same namespace
            // also get back purely new logins
            logins = unreserveNewLoginsFromSameNamespace(logins, u);
            // store purely new logins to user
            storeApplicationLoginAttributes(app);
            for (Pair<String, String> pair : logins) {
                // LOGIN IN NAMESPACE IS PURELY NEW => VALIDATE ENTRY IN KDC
                // left = namespace, right = login
                perun.getUsersManagerBl().validatePasswordAndSetExtSources(registrarSession, u, pair.getRight(), pair.getLeft());
            }
            // log
            perun.getAuditer().log(sess, "{} created for approved {}.", member, app);
        }
    // FOR EXTENSION APPLICATION
    } else if (AppType.EXTENSION.equals(app.getType())) {
        // free reserved logins so they can be set as attributes
        jdbc.update("delete from application_reserved_logins where app_id=?", app.getId());
        member = membersManager.getMemberByUser(registrarSession, app.getVo(), app.getUser());
        storeApplicationAttributes(app);
        // extend user's membership
        membersManager.extendMembership(registrarSession, member);
        // unreserve new logins, if user already have login in same namespace
        // also get back logins, which are purely new
        logins = unreserveNewLoginsFromSameNamespace(logins, app.getUser());
        // store purely new logins from application
        storeApplicationLoginAttributes(app);
        // validate purely new logins in KDC
        for (Pair<String, String> pair : logins) {
            // left = namespace, right = login
            perun.getUsersManagerBl().validatePasswordAndSetExtSources(registrarSession, app.getUser(), pair.getRight(), pair.getLeft());
        }
        // update titles before/after users name if part of application !! USER MUST EXISTS !!
        updateUserNameTitles(app);
        // log
        perun.getAuditer().log(sess, "Membership extended for {} in {} for approved {}.", member, app.getVo(), app);
    }
    if (module != null) {
        module.approveApplication(sess, app);
    }
    getMailManager().sendMessage(app, MailType.APP_APPROVED_USER, null, null);
    // return updated application
    return app;
}
Also used : SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) SingleColumnRowMapper(org.springframework.jdbc.core.SingleColumnRowMapper) RowMapper(org.springframework.jdbc.core.RowMapper) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) RegistrarModule(cz.metacentrum.perun.registrar.RegistrarModule) Application(cz.metacentrum.perun.registrar.model.Application) Transactional(org.springframework.transaction.annotation.Transactional)

Example 12 with RowMapper

use of org.springframework.jdbc.core.RowMapper in project perun by CESNET.

the class MailManagerImpl method getMailByParams.

/**
	 * Retrieve mail definition from db by params.
	 * Mail contains all texts.
	 * If mail not exists, or no texts exists null is returned.
	 *
	 * @param formId relation to VO form
	 * @param appType application type
	 * @param mailType mail type
	 * @return mail if definition exists or null
	 */
private ApplicationMail getMailByParams(Integer formId, AppType appType, MailType mailType) {
    ApplicationMail mail = null;
    // get mail def
    try {
        List<ApplicationMail> mails = jdbc.query(MAILS_SELECT_BY_PARAMS, new RowMapper<ApplicationMail>() {

            @Override
            public ApplicationMail mapRow(ResultSet rs, int arg1) throws SQLException {
                return new ApplicationMail(rs.getInt("id"), AppType.valueOf(rs.getString("app_type")), rs.getInt("form_id"), MailType.valueOf(rs.getString("mail_type")), rs.getBoolean("send"));
            }
        }, formId, appType.toString(), mailType.toString());
        // set
        if (mails.size() != 1) {
            log.error("[MAIL MANAGER] Wrong number of mail definitions returned by unique params, expected 1 but was: " + mails.size());
            return mail;
        }
        mail = mails.get(0);
    } catch (EmptyResultDataAccessException ex) {
        return mail;
    }
    List<MailText> texts = new ArrayList<MailText>();
    try {
        texts = jdbc.query(MAIL_TEXTS_SELECT_BY_MAIL_ID, new RowMapper<MailText>() {

            @Override
            public MailText mapRow(ResultSet rs, int arg1) throws SQLException {
                return new MailText(new Locale(rs.getString("locale")), rs.getString("subject"), rs.getString("text"));
            }
        }, mail.getId());
    } catch (EmptyResultDataAccessException ex) {
        // if no texts it's error
        log.error("[MAIL MANAGER] Mail do not contains any text message: {}", ex);
        return null;
    }
    for (MailText text : texts) {
        // fill localized messages
        mail.getMessage().put(text.getLocale(), text);
    }
    return mail;
}
Also used : SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) MailText(cz.metacentrum.perun.registrar.model.ApplicationMail.MailText) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) ApplicationMail(cz.metacentrum.perun.registrar.model.ApplicationMail) RowMapper(org.springframework.jdbc.core.RowMapper)

Example 13 with RowMapper

use of org.springframework.jdbc.core.RowMapper in project Gargoyle by callakrsos.

the class SqlMultiplePane method applySelectScript.

/**
	 * 테이블의 SELECT문을 리턴.
	 *
	 * @param e
	 */
public void applySelectScript(ActionEvent e) {
    TreeItem<K> selectedItem = schemaTree.getSelectionModel().getSelectedItem();
    String tableName = this.getSelectedTreeByTableName(selectedItem);
    SqlTab selectedTab = getSelectedSqlTab();
    TreeItem<K> schemaTreeItem = selectedItem.getParent();
    String schema = schemaTreeItem.getValue().toString();
    Connection connection = connectionSupplier.get();
    try {
        String driver = DbUtil.getDriverNameByConnection(connection);
        String sql = ConfigResourceLoader.getInstance().get(ConfigResourceLoader.SQL_TABLE_COLUMNS_WRAPPER, driver);
        Map<String, Object> map = new HashMap<>(2);
        map.put("databaseName", schema);
        map.put("tableName", tableName);
        sql = ValueUtil.getVelocityToText(sql, map, true);
        List<String> select = DbUtil.select(connection, sql, 10, (RowMapper<String>) (rs, rowNum) -> rs.getString(1));
        redueceAction(select, ",", v -> selectedTab.appendTextSql(String.format("select %s \nfrom %s ", v.substring(0, v.length()), tableName)));
    } catch (Exception e1) {
        LOGGER.error(ValueUtil.toString(e1));
    }
}
Also used : Button(javafx.scene.control.Button) SystemLayoutViewController(com.kyj.fx.voeditor.visual.main.layout.SystemLayoutViewController) CheckComboBox(org.controlsfx.control.CheckComboBox) Connection(java.sql.Connection) DbUtil(com.kyj.fx.voeditor.visual.util.DbUtil) LoggerFactory(org.slf4j.LoggerFactory) NullExpresion(com.kyj.fx.voeditor.visual.util.NullExpresion) ToExcelFileFunction(com.kyj.fx.voeditor.visual.functions.ToExcelFileFunction) Application(javafx.application.Application) TabPane(javafx.scene.control.TabPane) ListChangeListener(javafx.collections.ListChangeListener) EncrypUtil(com.kyj.fx.voeditor.visual.util.EncrypUtil) ContextMenu(javafx.scene.control.ContextMenu) Map(java.util.Map) SQLPaneMotionable(com.kyj.fx.voeditor.visual.component.sql.functions.SQLPaneMotionable) GargoyleExtensionFilters(com.kyj.fx.voeditor.visual.util.GargoyleExtensionFilters) SimpleIntegerProperty(javafx.beans.property.SimpleIntegerProperty) VariableMappingView(com.kyj.fx.voeditor.visual.component.popup.VariableMappingView) DockPos(com.kyj.fx.voeditor.visual.component.dock.pane.DockPos) DockPane(com.kyj.fx.voeditor.visual.component.dock.pane.DockPane) TableView(javafx.scene.control.TableView) SystemUtils(org.apache.commons.lang.SystemUtils) HBox(javafx.scene.layout.HBox) Pair(javafx.util.Pair) MenuItem(javafx.scene.control.MenuItem) KeyEvent(javafx.scene.input.KeyEvent) SimpleTextView(com.kyj.fx.voeditor.visual.component.text.SimpleTextView) ConfigResourceLoader(com.kyj.fx.voeditor.visual.momory.ConfigResourceLoader) Collectors(java.util.stream.Collectors) TreeView(javafx.scene.control.TreeView) ISchemaTreeItem(com.kyj.fx.voeditor.visual.component.sql.functions.ISchemaTreeItem) SeparatorMenuItem(javafx.scene.control.SeparatorMenuItem) FxUtil(com.kyj.fx.voeditor.visual.util.FxUtil) List(java.util.List) ResourceLoader(com.kyj.fx.voeditor.visual.momory.ResourceLoader) SqlTab(com.kyj.fx.voeditor.visual.component.sql.tab.SqlTab) RowMapper(org.springframework.jdbc.core.RowMapper) Optional(java.util.Optional) DateUtil(com.kyj.fx.voeditor.visual.util.DateUtil) ObservableList(javafx.collections.ObservableList) BorderPane(javafx.scene.layout.BorderPane) TableViewSelectionModel(javafx.scene.control.TableView.TableViewSelectionModel) MouseButton(javafx.scene.input.MouseButton) TreeItem(javafx.scene.control.TreeItem) MouseEvent(javafx.scene.input.MouseEvent) FXCollections(javafx.collections.FXCollections) HashMap(java.util.HashMap) TextFieldTableCell(javafx.scene.control.cell.TextFieldTableCell) DockNode(com.kyj.fx.voeditor.visual.component.dock.pane.DockNode) GagoyleTabProxy(com.kyj.fx.voeditor.visual.main.layout.GagoyleTabProxy) DialogUtil(com.kyj.fx.voeditor.visual.util.DialogUtil) Supplier(java.util.function.Supplier) IntegerProperty(javafx.beans.property.IntegerProperty) BigDataDVO(com.kyj.fx.voeditor.visual.framework.BigDataDVO) TableColumn(javafx.scene.control.TableColumn) Tooltip(javafx.scene.control.Tooltip) KeyCode(javafx.scene.input.KeyCode) Color(javafx.scene.paint.Color) Modality(javafx.stage.Modality) Logger(org.slf4j.Logger) Label(javafx.scene.control.Label) Iterator(java.util.Iterator) ValueUtil(com.kyj.fx.voeditor.visual.util.ValueUtil) StringConverter(javafx.util.StringConverter) SchoolMgrerSpreadSheetView(com.kyj.fx.voeditor.visual.main.layout.SchoolMgrerSpreadSheetView) File(java.io.File) SqlTabPane(com.kyj.fx.voeditor.visual.component.sql.tab.SqlTabPane) Menu(javafx.scene.control.Menu) Consumer(java.util.function.Consumer) KeyCodeCombination(javafx.scene.input.KeyCodeCombination) ActionEvent(javafx.event.ActionEvent) SelectionMode(javafx.scene.control.SelectionMode) Stage(javafx.stage.Stage) SimpleObjectProperty(javafx.beans.property.SimpleObjectProperty) Tab(javafx.scene.control.Tab) ExtensionFilter(javafx.stage.FileChooser.ExtensionFilter) Collections(java.util.Collections) SharedMemory(com.kyj.fx.voeditor.visual.momory.SharedMemory) HashMap(java.util.HashMap) Connection(java.sql.Connection) SqlTab(com.kyj.fx.voeditor.visual.component.sql.tab.SqlTab)

Aggregations

RowMapper (org.springframework.jdbc.core.RowMapper)13 ResultSet (java.sql.ResultSet)7 Map (java.util.Map)4 EmptyResultDataAccessException (org.springframework.dao.EmptyResultDataAccessException)4 ApplicationMail (cz.metacentrum.perun.registrar.model.ApplicationMail)3 MailText (cz.metacentrum.perun.registrar.model.ApplicationMail.MailText)3 SQLException (java.sql.SQLException)3 BeanPropertyRowMapper (org.springframework.jdbc.core.BeanPropertyRowMapper)3 ColumnMapRowMapper (org.springframework.jdbc.core.ColumnMapRowMapper)3 SqlTab (com.kyj.fx.voeditor.visual.component.sql.tab.SqlTab)2 Connection (java.sql.Connection)2 RowMapperResultSetExtractor (org.springframework.jdbc.core.RowMapperResultSetExtractor)2 AlbumInfo (com.github.hakko.musiccabinet.domain.model.music.AlbumInfo)1 DockNode (com.kyj.fx.voeditor.visual.component.dock.pane.DockNode)1 DockPane (com.kyj.fx.voeditor.visual.component.dock.pane.DockPane)1 DockPos (com.kyj.fx.voeditor.visual.component.dock.pane.DockPos)1 VariableMappingView (com.kyj.fx.voeditor.visual.component.popup.VariableMappingView)1 ISchemaTreeItem (com.kyj.fx.voeditor.visual.component.sql.functions.ISchemaTreeItem)1 SQLPaneMotionable (com.kyj.fx.voeditor.visual.component.sql.functions.SQLPaneMotionable)1 SqlTabPane (com.kyj.fx.voeditor.visual.component.sql.tab.SqlTabPane)1